feat(orders): Orders page Přijaté|Vydané tabs + issued list

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-09 11:37:03 +02:00
parent 8476ffebd6
commit 8b90cfed1f
3 changed files with 1102 additions and 695 deletions

View File

@@ -0,0 +1,371 @@
import { useState } from "react";
import { useNavigate, Link as RouterLink } from "react-router-dom";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { useApiMutation } from "../lib/queries/mutations";
import {
issuedOrderListOptions,
type IssuedOrder,
} from "../lib/queries/issued-orders";
import {
Button,
Card,
DataTable,
Pagination,
ConfirmDialog,
TextField,
Select,
StatusChip,
PageHeader,
PageEnter,
FilterBar,
EmptyState,
LoadingState,
type DataColumn,
} from "../ui";
const API_BASE = "/api/admin";
const STATUS_LABELS: Record<string, string> = {
draft: "Koncept",
sent: "Odeslaná",
confirmed: "Potvrzená",
completed: "Dokončená",
cancelled: "Stornovaná",
};
const STATUS_COLORS: Record<
string,
"default" | "success" | "error" | "warning" | "info"
> = {
draft: "default",
sent: "info",
confirmed: "warning",
completed: "success",
cancelled: "error",
};
const STATUS_OPTIONS = [
{ value: "", label: "Všechny stavy" },
...Object.entries(STATUS_LABELS).map(([value, label]) => ({ value, label })),
];
const PlusIcon = (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
);
const ViewIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
);
const PdfIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" />
</svg>
);
const DeleteIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
);
export default function IssuedOrders() {
const alert = useAlert();
const { hasPermission } = useAuth();
const navigate = useNavigate();
const { sort, order, handleSort } = useTableSort("po_number");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [status, setStatus] = useState("");
const [page, setPage] = useState(1);
const [deleteConfirm, setDeleteConfirm] = useState<{
show: boolean;
order: IssuedOrder | null;
}>({ show: false, order: null });
const deleteMutation = useApiMutation<
{ id: number },
{ message?: string; error?: string }
>({
url: ({ id }) => `${API_BASE}/issued-orders/${id}`,
method: () => "DELETE",
invalidate: ["issued-orders"],
onSuccess: (data) => {
setDeleteConfirm({ show: false, order: null });
alert.success(data?.message || "Objednávka byla smazána");
},
});
const {
items: orders,
pagination,
isPending,
isFetching,
} = usePaginatedQuery<IssuedOrder>(
issuedOrderListOptions({
search: debouncedSearch,
sort,
order,
page,
perPage: 20,
status: status || undefined,
}),
);
if (!hasPermission("orders.view")) return <Forbidden />;
const handleDelete = async () => {
if (!deleteConfirm.order) return;
try {
await deleteMutation.mutateAsync({ id: deleteConfirm.order.id });
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
}
};
if (isPending) {
return <LoadingState />;
}
const total = pagination?.total ?? orders.length;
const subtitle = `${total} ${czechPlural(
total,
"objednávka",
"objednávky",
"objednávek",
)}`;
const columns: DataColumn<IssuedOrder>[] = [
{
key: "po_number",
header: "Číslo",
width: "16%",
sortKey: "po_number",
mono: true,
render: (o) => (
<Box
component={RouterLink}
to={`/orders/issued/${o.id}`}
sx={{
color: "primary.main",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{o.po_number || "—"}
</Box>
),
},
{
key: "customer_name",
header: "Dodavatel",
width: "24%",
render: (o) => o.customer_name || "—",
},
{
key: "status",
header: "Stav",
width: "14%",
sortKey: "status",
render: (o) => (
<StatusChip
label={STATUS_LABELS[o.status] || o.status}
color={STATUS_COLORS[o.status] || "default"}
/>
),
},
{
key: "order_date",
header: "Datum",
width: "13%",
sortKey: "order_date",
mono: true,
render: (o) => (o.order_date ? formatDate(o.order_date) : "—"),
},
{
key: "total",
header: "Celkem",
width: "14%",
align: "right",
mono: true,
bold: true,
render: (o) => formatCurrency(o.total, o.currency ?? "CZK"),
},
{
key: "actions",
header: "Akce",
width: "14%",
align: "right",
render: (o) => (
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
<IconButton
size="small"
onClick={() => navigate(`/orders/issued/${o.id}`)}
aria-label={hasPermission("orders.edit") ? "Upravit" : "Detail"}
title={hasPermission("orders.edit") ? "Upravit" : "Detail"}
>
{ViewIcon}
</IconButton>
{hasPermission("orders.export") && (
<IconButton
size="small"
onClick={() =>
window.open(
`${API_BASE}/issued-orders-pdf/${o.id}?lang=cs`,
"_blank",
)
}
aria-label="PDF"
title="PDF"
>
{PdfIcon}
</IconButton>
)}
{hasPermission("orders.delete") && (
<IconButton
size="small"
color="error"
onClick={() => setDeleteConfirm({ show: true, order: o })}
aria-label="Smazat"
title="Smazat"
>
{DeleteIcon}
</IconButton>
)}
</Box>
),
},
];
return (
<PageEnter>
<PageHeader
title="Objednávky vydané"
subtitle={subtitle}
actions={
hasPermission("orders.create") ? (
<Button
startIcon={PlusIcon}
onClick={() => navigate("/orders/issued/new")}
>
Vytvořit objednávku vydanou
</Button>
) : undefined
}
/>
<FilterBar>
<Box sx={{ flex: "1 1 320px" }}>
<TextField
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
placeholder="Hledat podle čísla nebo dodavatele..."
fullWidth
/>
</Box>
<Box sx={{ flex: "0 1 200px" }}>
<Select
value={status}
onChange={(value) => {
setStatus(value);
setPage(1);
}}
options={STATUS_OPTIONS}
/>
</Box>
</FilterBar>
<Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
<DataTable<IssuedOrder>
columns={columns}
rows={orders}
rowKey={(o) => o.id}
sortBy={sort}
sortDir={order}
onSort={handleSort}
empty={
<EmptyState
title="Zatím žádné vydané objednávky."
description={
hasPermission("orders.create")
? "Vytvořte první tlačítkem „Vytvořit objednávku vydanou“."
: undefined
}
/>
}
/>
<Pagination
page={page}
pageCount={pagination?.total_pages ?? 1}
onChange={setPage}
/>
</Card>
<ConfirmDialog
isOpen={deleteConfirm.show}
onClose={() => setDeleteConfirm({ show: false, order: null })}
onConfirm={handleDelete}
title="Smazat objednávku"
message={
deleteConfirm.order
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.po_number || ""}"? Tato akce je nevratná.`
: ""
}
confirmText="Smazat"
cancelText="Zrušit"
confirmVariant="danger"
loading={deleteMutation.isPending}
/>
</PageEnter>
);
}

View File

@@ -1,704 +1,36 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import { lazy, Suspense } from "react";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import apiFetch from "../utils/api";
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
orderListOptions,
orderNextNumberOptions,
} from "../lib/queries/orders";
import { offerCustomersOptions } from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import {
Button,
Card,
DataTable,
Pagination,
Modal,
ConfirmDialog,
Field,
TextField,
Select,
StatusChip,
CheckboxField,
FileUpload,
PageHeader,
PageEnter,
FilterBar,
EmptyState,
LoadingState,
type DataColumn,
} from "../ui";
import { useSearchParams } from "react-router-dom";
import { Tabs, LoadingState } from "../ui";
import OrdersReceived from "./OrdersReceived";
const API_BASE = "/api/admin";
const STATUS_LABELS: Record<string, string> = {
prijata: "Přijatá",
v_realizaci: "V realizaci",
dokoncena: "Dokončená",
stornovana: "Stornována",
};
const STATUS_COLORS: Record<
string,
"default" | "success" | "error" | "warning" | "info"
> = {
prijata: "info",
v_realizaci: "warning",
dokoncena: "success",
stornovana: "error",
};
interface Order {
id: number;
order_number: string;
quotation_id: number;
quotation_number: string;
customer_name: string;
status: string;
created_at: string;
total: number;
currency: string;
invoice_id?: number;
}
const PlusIcon = (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
);
const ViewIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
);
const InvoiceViewIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<text
x="12"
y="16.5"
textAnchor="middle"
fill="currentColor"
stroke="none"
fontSize="9"
fontWeight="700"
>
F
</text>
</svg>
);
const InvoiceCreateIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="12" y1="11" x2="12" y2="17" />
<line x1="9" y1="14" x2="15" y2="14" />
</svg>
);
const DeleteIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
);
const IssuedOrders = lazy(() => import("./IssuedOrders"));
export default function Orders() {
const alert = useAlert();
const { hasPermission } = useAuth();
const { sort, order, handleSort } = useTableSort("order_number");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [page, setPage] = useState(1);
const [deleteConfirm, setDeleteConfirm] = useState<{
show: boolean;
order: Order | null;
}>({ show: false, order: null });
const [deleteFiles, setDeleteFiles] = useState(false);
const deleteMutation = useApiMutation<
{ id: number; delete_files: boolean },
{ message?: string; error?: string }
>({
url: ({ id }) => `${API_BASE}/orders/${id}`,
method: () => "DELETE",
invalidate: ["orders", "offers", "projects", "invoices"],
onSuccess: (data) => {
setDeleteConfirm({ show: false, order: null });
setDeleteFiles(false);
alert.success(data?.message || "Objednávka byla smazána");
},
});
const [showCreate, setShowCreate] = useState(false);
const [createForm, setCreateForm] = useState({
customer_id: "",
customer_order_number: "",
currency: "CZK",
vat_rate: "21",
apply_vat: true,
scope_title: "",
scope_description: "",
notes: "",
create_project: true,
price: "",
quantity: "1",
});
const [creating, setCreating] = useState(false);
const queryClient = useQueryClient();
const navigate = useNavigate();
const [orderAttachment, setOrderAttachment] = useState<File | null>(null);
const customersQuery = useQuery({
...offerCustomersOptions(),
enabled: showCreate,
});
const nextNumberQuery = useQuery({
...orderNextNumberOptions(),
enabled: showCreate,
});
const openCreate = () => {
setCreateForm({
customer_id: "",
customer_order_number: "",
currency: "CZK",
vat_rate: "21",
apply_vat: true,
scope_title: "",
scope_description: "",
notes: "",
create_project: true,
price: "",
quantity: "1",
});
setOrderAttachment(null);
setShowCreate(true);
};
const handleCreate = async () => {
setCreating(true);
try {
const priceNum = createForm.price ? Number(createForm.price) : 0;
const qtyNum = createForm.quantity ? Number(createForm.quantity) : 1;
const items =
priceNum > 0
? [
{
description: createForm.scope_title || "Položka",
quantity: qtyNum,
unit_price: priceNum,
is_included_in_total: true,
},
]
: undefined;
let fetchOptions: RequestInit;
if (orderAttachment) {
const fd = new FormData();
if (createForm.customer_id)
fd.append("customer_id", createForm.customer_id);
fd.append("customer_order_number", createForm.customer_order_number);
fd.append("currency", createForm.currency);
fd.append("vat_rate", createForm.vat_rate);
fd.append("apply_vat", createForm.apply_vat ? "1" : "0");
fd.append("scope_title", createForm.scope_title);
fd.append("scope_description", createForm.scope_description);
fd.append("notes", createForm.notes);
fd.append("create_project", createForm.create_project ? "1" : "0");
if (items) fd.append("items", JSON.stringify(items));
fd.append("attachment", orderAttachment);
fetchOptions = { method: "POST", body: fd };
} else {
fetchOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: createForm.customer_id
? Number(createForm.customer_id)
: null,
customer_order_number: createForm.customer_order_number,
currency: createForm.currency,
vat_rate: createForm.vat_rate,
apply_vat: createForm.apply_vat,
scope_title: createForm.scope_title,
scope_description: createForm.scope_description,
notes: createForm.notes,
create_project: createForm.create_project,
...(items ? { items } : {}),
}),
};
}
const response = await apiFetch(`${API_BASE}/orders`, fetchOptions);
const result = await response.json();
if (result.success) {
setShowCreate(false);
alert.success(result.message || "Objednávka byla vytvořena");
await queryClient.invalidateQueries({ queryKey: ["orders"] });
await queryClient.invalidateQueries({ queryKey: ["projects"] });
await queryClient.invalidateQueries({ queryKey: ["offers"] });
await queryClient.invalidateQueries({ queryKey: ["invoices"] });
if (result.data?.id) navigate(`/orders/${result.data.id}`);
} else {
alert.error(result.error || "Nepodařilo se vytvořit objednávku");
}
} catch {
alert.error("Chyba připojení");
} finally {
setCreating(false);
}
};
const {
items: orders,
pagination,
isPending,
isFetching,
} = usePaginatedQuery<Order>(
orderListOptions({ search: debouncedSearch, sort, order, page }),
);
if (!hasPermission("orders.view")) return <Forbidden />;
const handleDelete = async () => {
if (!deleteConfirm.order) return;
try {
await deleteMutation.mutateAsync({
id: deleteConfirm.order.id,
delete_files: deleteFiles,
});
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
}
};
if (isPending) {
return <LoadingState />;
}
const total = pagination?.total ?? orders.length;
const subtitle = `${total} ${czechPlural(
total,
"objednávka",
"objednávky",
"objednávek",
)}`;
const columns: DataColumn<Order>[] = [
{
key: "order_number",
header: "Číslo",
width: "14%",
sortKey: "order_number",
mono: true,
render: (o) => (
<Box
component={RouterLink}
to={`/orders/${o.id}`}
sx={{
color: "primary.main",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{o.order_number}
</Box>
),
},
{
key: "quotation",
header: "Nabídka",
width: "14%",
render: (o) => (
<Box
component={RouterLink}
to={`/offers/${o.quotation_id}`}
sx={{
color: "text.secondary",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{o.quotation_number}
</Box>
),
},
{
key: "customer",
header: "Zákazník",
width: "20%",
render: (o) => o.customer_name || "—",
},
{
key: "status",
header: "Stav",
width: "13%",
sortKey: "status",
render: (o) => (
<StatusChip
label={STATUS_LABELS[o.status] || o.status}
color={STATUS_COLORS[o.status] || "default"}
/>
),
},
{
key: "created_at",
header: "Datum",
width: "12%",
sortKey: "created_at",
mono: true,
render: (o) => formatDate(o.created_at),
},
{
key: "total",
header: "Celkem",
width: "13%",
align: "right",
mono: true,
bold: true,
render: (o) => formatCurrency(o.total, o.currency),
},
{
key: "actions",
header: "Akce",
width: "14%",
align: "right",
render: (o) => (
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
<IconButton
size="small"
onClick={() => navigate(`/orders/${o.id}`)}
aria-label="Detail"
title="Detail"
>
{ViewIcon}
</IconButton>
{o.invoice_id ? (
<IconButton
size="small"
color="primary"
onClick={() => navigate(`/invoices/${o.invoice_id}`)}
aria-label="Zobrazit fakturu"
title="Zobrazit fakturu"
>
{InvoiceViewIcon}
</IconButton>
) : (
hasPermission("invoices.create") && (
<IconButton
size="small"
onClick={() => navigate(`/invoices/new?fromOrder=${o.id}`)}
aria-label="Vytvořit fakturu"
title="Vytvořit fakturu"
>
{InvoiceCreateIcon}
</IconButton>
)
)}
{hasPermission("orders.delete") && (
<IconButton
size="small"
color="error"
onClick={() => setDeleteConfirm({ show: true, order: o })}
aria-label="Smazat"
title="Smazat"
>
{DeleteIcon}
</IconButton>
)}
</Box>
),
},
];
const [searchParams, setSearchParams] = useSearchParams();
const activeTab = searchParams.get("tab") === "vydane" ? "vydane" : "prijate";
const setActiveTab = (tab: string) =>
setSearchParams({ tab }, { replace: true });
return (
<PageEnter>
<PageHeader
title="Objednávky"
subtitle={subtitle}
actions={
hasPermission("orders.create") ? (
<Button startIcon={PlusIcon} onClick={openCreate}>
Vytvořit objednávku
</Button>
) : undefined
}
/>
<FilterBar>
<Box sx={{ flex: "1 1 320px" }}>
<TextField
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
placeholder="Hledat podle čísla, nabídky, projektu nebo zákazníka..."
fullWidth
/>
</Box>
</FilterBar>
<Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
<DataTable<Order>
columns={columns}
rows={orders}
rowKey={(o) => o.id}
sortBy={sort}
sortDir={order}
onSort={handleSort}
empty={
<EmptyState
title="Zatím nejsou žádné objednávky."
description="Objednávky se vytvářejí z nabídek."
/>
}
/>
<Pagination
page={page}
pageCount={pagination?.total_pages ?? 1}
onChange={setPage}
/>
</Card>
<ConfirmDialog
isOpen={deleteConfirm.show}
onClose={() => {
setDeleteConfirm({ show: false, order: null });
setDeleteFiles(false);
}}
onConfirm={handleDelete}
title="Smazat objednávku"
message={
deleteConfirm.order
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.order_number}"? Bude smazán i přidružený projekt. Tato akce je nevratná.`
: ""
}
confirmText="Smazat"
confirmVariant="danger"
loading={deleteMutation.isPending}
>
<CheckboxField
label="Smazat i soubory projektu na disku"
checked={deleteFiles}
onChange={setDeleteFiles}
/>
</ConfirmDialog>
<Modal
isOpen={showCreate}
onClose={() => setShowCreate(false)}
onSubmit={handleCreate}
title="Vytvořit objednávku bez nabídky"
subtitle={`Číslo objednávky: ${
nextNumberQuery.data?.number ??
nextNumberQuery.data?.next_number ??
"…"
} (přiděleno automaticky)`}
submitText="Vytvořit"
loading={creating}
>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Zákazník">
<Select
value={createForm.customer_id}
onChange={(value) =>
setCreateForm({ ...createForm, customer_id: value })
}
options={[
{ value: "", label: "— bez zákazníka —" },
...(customersQuery.data ?? []).map((c) => ({
value: String(c.id),
label: c.name,
})),
<>
<Box sx={{ display: "flex", justifyContent: "center", mb: 2.5 }}>
<Tabs
value={activeTab}
onChange={(v) => setActiveTab(v)}
tabs={[
{ value: "prijate", label: "Přijaté" },
{ value: "vydane", label: "Vydané" },
]}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Číslo objednávky zákazníka">
<TextField
value={createForm.customer_order_number}
onChange={(e) =>
setCreateForm({
...createForm,
customer_order_number: e.target.value,
})
}
/>
</Field>
</Box>
</Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Měna">
<Select
value={createForm.currency}
onChange={(value) =>
setCreateForm({ ...createForm, currency: value })
}
options={[
{ value: "CZK", label: "CZK" },
{ value: "EUR", label: "EUR" },
{ value: "USD", label: "USD" },
{ value: "GBP", label: "GBP" },
]}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Sazba DPH (%)">
<TextField
type="number"
inputMode="numeric"
value={createForm.vat_rate}
onChange={(e) =>
setCreateForm({ ...createForm, vat_rate: e.target.value })
}
slotProps={{ htmlInput: { min: 0 } }}
/>
</Field>
</Box>
</Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Cena za jednotku (bez DPH)">
<TextField
type="number"
inputMode="decimal"
value={createForm.price}
onChange={(e) =>
setCreateForm({ ...createForm, price: e.target.value })
}
placeholder="0"
slotProps={{ htmlInput: { min: 0, step: 0.01 } }}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Množství">
<TextField
type="number"
inputMode="decimal"
value={createForm.quantity}
onChange={(e) =>
setCreateForm({ ...createForm, quantity: e.target.value })
}
slotProps={{ htmlInput: { min: 0, step: 1 } }}
/>
</Field>
</Box>
</Box>
<Field label="Předmět (scope)">
<TextField
value={createForm.scope_title}
onChange={(e) =>
setCreateForm({ ...createForm, scope_title: e.target.value })
}
/>
</Field>
<Field label="Popis">
<TextField
multiline
minRows={3}
value={createForm.scope_description}
onChange={(e) =>
setCreateForm({
...createForm,
scope_description: e.target.value,
})
}
/>
</Field>
<Field label="Poznámka">
<TextField
multiline
minRows={2}
value={createForm.notes}
onChange={(e) =>
setCreateForm({ ...createForm, notes: e.target.value })
}
/>
</Field>
<Field label="Příloha (PO zákazníka, PDF)">
<FileUpload
files={orderAttachment ? [orderAttachment] : []}
onFilesChange={(files) => setOrderAttachment(files[0] ?? null)}
accept="application/pdf"
multiple={false}
/>
</Field>
<CheckboxField
label="Účtovat DPH"
checked={createForm.apply_vat}
onChange={(v) => setCreateForm({ ...createForm, apply_vat: v })}
/>
<CheckboxField
label="Vytvořit propojený projekt"
checked={createForm.create_project}
onChange={(v) => setCreateForm({ ...createForm, create_project: v })}
/>
</Modal>
</PageEnter>
{activeTab === "vydane" ? (
<Suspense fallback={<LoadingState />}>
<IssuedOrders />
</Suspense>
) : (
<OrdersReceived />
)}
</>
);
}

View File

@@ -0,0 +1,704 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import apiFetch from "../utils/api";
import { formatCurrency, formatDate, czechPlural } from "../utils/formatters";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
orderListOptions,
orderNextNumberOptions,
} from "../lib/queries/orders";
import { offerCustomersOptions } from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import {
Button,
Card,
DataTable,
Pagination,
Modal,
ConfirmDialog,
Field,
TextField,
Select,
StatusChip,
CheckboxField,
FileUpload,
PageHeader,
PageEnter,
FilterBar,
EmptyState,
LoadingState,
type DataColumn,
} from "../ui";
const API_BASE = "/api/admin";
const STATUS_LABELS: Record<string, string> = {
prijata: "Přijatá",
v_realizaci: "V realizaci",
dokoncena: "Dokončená",
stornovana: "Stornována",
};
const STATUS_COLORS: Record<
string,
"default" | "success" | "error" | "warning" | "info"
> = {
prijata: "info",
v_realizaci: "warning",
dokoncena: "success",
stornovana: "error",
};
interface Order {
id: number;
order_number: string;
quotation_id: number;
quotation_number: string;
customer_name: string;
status: string;
created_at: string;
total: number;
currency: string;
invoice_id?: number;
}
const PlusIcon = (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
);
const ViewIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
);
const InvoiceViewIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<text
x="12"
y="16.5"
textAnchor="middle"
fill="currentColor"
stroke="none"
fontSize="9"
fontWeight="700"
>
F
</text>
</svg>
);
const InvoiceCreateIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="12" y1="11" x2="12" y2="17" />
<line x1="9" y1="14" x2="15" y2="14" />
</svg>
);
const DeleteIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
);
export default function OrdersReceived() {
const alert = useAlert();
const { hasPermission } = useAuth();
const { sort, order, handleSort } = useTableSort("order_number");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [page, setPage] = useState(1);
const [deleteConfirm, setDeleteConfirm] = useState<{
show: boolean;
order: Order | null;
}>({ show: false, order: null });
const [deleteFiles, setDeleteFiles] = useState(false);
const deleteMutation = useApiMutation<
{ id: number; delete_files: boolean },
{ message?: string; error?: string }
>({
url: ({ id }) => `${API_BASE}/orders/${id}`,
method: () => "DELETE",
invalidate: ["orders", "offers", "projects", "invoices"],
onSuccess: (data) => {
setDeleteConfirm({ show: false, order: null });
setDeleteFiles(false);
alert.success(data?.message || "Objednávka byla smazána");
},
});
const [showCreate, setShowCreate] = useState(false);
const [createForm, setCreateForm] = useState({
customer_id: "",
customer_order_number: "",
currency: "CZK",
vat_rate: "21",
apply_vat: true,
scope_title: "",
scope_description: "",
notes: "",
create_project: true,
price: "",
quantity: "1",
});
const [creating, setCreating] = useState(false);
const queryClient = useQueryClient();
const navigate = useNavigate();
const [orderAttachment, setOrderAttachment] = useState<File | null>(null);
const customersQuery = useQuery({
...offerCustomersOptions(),
enabled: showCreate,
});
const nextNumberQuery = useQuery({
...orderNextNumberOptions(),
enabled: showCreate,
});
const openCreate = () => {
setCreateForm({
customer_id: "",
customer_order_number: "",
currency: "CZK",
vat_rate: "21",
apply_vat: true,
scope_title: "",
scope_description: "",
notes: "",
create_project: true,
price: "",
quantity: "1",
});
setOrderAttachment(null);
setShowCreate(true);
};
const handleCreate = async () => {
setCreating(true);
try {
const priceNum = createForm.price ? Number(createForm.price) : 0;
const qtyNum = createForm.quantity ? Number(createForm.quantity) : 1;
const items =
priceNum > 0
? [
{
description: createForm.scope_title || "Položka",
quantity: qtyNum,
unit_price: priceNum,
is_included_in_total: true,
},
]
: undefined;
let fetchOptions: RequestInit;
if (orderAttachment) {
const fd = new FormData();
if (createForm.customer_id)
fd.append("customer_id", createForm.customer_id);
fd.append("customer_order_number", createForm.customer_order_number);
fd.append("currency", createForm.currency);
fd.append("vat_rate", createForm.vat_rate);
fd.append("apply_vat", createForm.apply_vat ? "1" : "0");
fd.append("scope_title", createForm.scope_title);
fd.append("scope_description", createForm.scope_description);
fd.append("notes", createForm.notes);
fd.append("create_project", createForm.create_project ? "1" : "0");
if (items) fd.append("items", JSON.stringify(items));
fd.append("attachment", orderAttachment);
fetchOptions = { method: "POST", body: fd };
} else {
fetchOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
customer_id: createForm.customer_id
? Number(createForm.customer_id)
: null,
customer_order_number: createForm.customer_order_number,
currency: createForm.currency,
vat_rate: createForm.vat_rate,
apply_vat: createForm.apply_vat,
scope_title: createForm.scope_title,
scope_description: createForm.scope_description,
notes: createForm.notes,
create_project: createForm.create_project,
...(items ? { items } : {}),
}),
};
}
const response = await apiFetch(`${API_BASE}/orders`, fetchOptions);
const result = await response.json();
if (result.success) {
setShowCreate(false);
alert.success(result.message || "Objednávka byla vytvořena");
await queryClient.invalidateQueries({ queryKey: ["orders"] });
await queryClient.invalidateQueries({ queryKey: ["projects"] });
await queryClient.invalidateQueries({ queryKey: ["offers"] });
await queryClient.invalidateQueries({ queryKey: ["invoices"] });
if (result.data?.id) navigate(`/orders/${result.data.id}`);
} else {
alert.error(result.error || "Nepodařilo se vytvořit objednávku");
}
} catch {
alert.error("Chyba připojení");
} finally {
setCreating(false);
}
};
const {
items: orders,
pagination,
isPending,
isFetching,
} = usePaginatedQuery<Order>(
orderListOptions({ search: debouncedSearch, sort, order, page }),
);
if (!hasPermission("orders.view")) return <Forbidden />;
const handleDelete = async () => {
if (!deleteConfirm.order) return;
try {
await deleteMutation.mutateAsync({
id: deleteConfirm.order.id,
delete_files: deleteFiles,
});
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
}
};
if (isPending) {
return <LoadingState />;
}
const total = pagination?.total ?? orders.length;
const subtitle = `${total} ${czechPlural(
total,
"objednávka",
"objednávky",
"objednávek",
)}`;
const columns: DataColumn<Order>[] = [
{
key: "order_number",
header: "Číslo",
width: "14%",
sortKey: "order_number",
mono: true,
render: (o) => (
<Box
component={RouterLink}
to={`/orders/${o.id}`}
sx={{
color: "primary.main",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{o.order_number}
</Box>
),
},
{
key: "quotation",
header: "Nabídka",
width: "14%",
render: (o) => (
<Box
component={RouterLink}
to={`/offers/${o.quotation_id}`}
sx={{
color: "text.secondary",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{o.quotation_number}
</Box>
),
},
{
key: "customer",
header: "Zákazník",
width: "20%",
render: (o) => o.customer_name || "—",
},
{
key: "status",
header: "Stav",
width: "13%",
sortKey: "status",
render: (o) => (
<StatusChip
label={STATUS_LABELS[o.status] || o.status}
color={STATUS_COLORS[o.status] || "default"}
/>
),
},
{
key: "created_at",
header: "Datum",
width: "12%",
sortKey: "created_at",
mono: true,
render: (o) => formatDate(o.created_at),
},
{
key: "total",
header: "Celkem",
width: "13%",
align: "right",
mono: true,
bold: true,
render: (o) => formatCurrency(o.total, o.currency),
},
{
key: "actions",
header: "Akce",
width: "14%",
align: "right",
render: (o) => (
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
<IconButton
size="small"
onClick={() => navigate(`/orders/${o.id}`)}
aria-label="Detail"
title="Detail"
>
{ViewIcon}
</IconButton>
{o.invoice_id ? (
<IconButton
size="small"
color="primary"
onClick={() => navigate(`/invoices/${o.invoice_id}`)}
aria-label="Zobrazit fakturu"
title="Zobrazit fakturu"
>
{InvoiceViewIcon}
</IconButton>
) : (
hasPermission("invoices.create") && (
<IconButton
size="small"
onClick={() => navigate(`/invoices/new?fromOrder=${o.id}`)}
aria-label="Vytvořit fakturu"
title="Vytvořit fakturu"
>
{InvoiceCreateIcon}
</IconButton>
)
)}
{hasPermission("orders.delete") && (
<IconButton
size="small"
color="error"
onClick={() => setDeleteConfirm({ show: true, order: o })}
aria-label="Smazat"
title="Smazat"
>
{DeleteIcon}
</IconButton>
)}
</Box>
),
},
];
return (
<PageEnter>
<PageHeader
title="Objednávky"
subtitle={subtitle}
actions={
hasPermission("orders.create") ? (
<Button startIcon={PlusIcon} onClick={openCreate}>
Vytvořit objednávku
</Button>
) : undefined
}
/>
<FilterBar>
<Box sx={{ flex: "1 1 320px" }}>
<TextField
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
placeholder="Hledat podle čísla, nabídky, projektu nebo zákazníka..."
fullWidth
/>
</Box>
</FilterBar>
<Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
<DataTable<Order>
columns={columns}
rows={orders}
rowKey={(o) => o.id}
sortBy={sort}
sortDir={order}
onSort={handleSort}
empty={
<EmptyState
title="Zatím nejsou žádné objednávky."
description="Objednávky se vytvářejí z nabídek."
/>
}
/>
<Pagination
page={page}
pageCount={pagination?.total_pages ?? 1}
onChange={setPage}
/>
</Card>
<ConfirmDialog
isOpen={deleteConfirm.show}
onClose={() => {
setDeleteConfirm({ show: false, order: null });
setDeleteFiles(false);
}}
onConfirm={handleDelete}
title="Smazat objednávku"
message={
deleteConfirm.order
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.order_number}"? Bude smazán i přidružený projekt. Tato akce je nevratná.`
: ""
}
confirmText="Smazat"
confirmVariant="danger"
loading={deleteMutation.isPending}
>
<CheckboxField
label="Smazat i soubory projektu na disku"
checked={deleteFiles}
onChange={setDeleteFiles}
/>
</ConfirmDialog>
<Modal
isOpen={showCreate}
onClose={() => setShowCreate(false)}
onSubmit={handleCreate}
title="Vytvořit objednávku bez nabídky"
subtitle={`Číslo objednávky: ${
nextNumberQuery.data?.number ??
nextNumberQuery.data?.next_number ??
"…"
} (přiděleno automaticky)`}
submitText="Vytvořit"
loading={creating}
>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Zákazník">
<Select
value={createForm.customer_id}
onChange={(value) =>
setCreateForm({ ...createForm, customer_id: value })
}
options={[
{ value: "", label: "— bez zákazníka —" },
...(customersQuery.data ?? []).map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Číslo objednávky zákazníka">
<TextField
value={createForm.customer_order_number}
onChange={(e) =>
setCreateForm({
...createForm,
customer_order_number: e.target.value,
})
}
/>
</Field>
</Box>
</Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Měna">
<Select
value={createForm.currency}
onChange={(value) =>
setCreateForm({ ...createForm, currency: value })
}
options={[
{ value: "CZK", label: "CZK" },
{ value: "EUR", label: "EUR" },
{ value: "USD", label: "USD" },
{ value: "GBP", label: "GBP" },
]}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Sazba DPH (%)">
<TextField
type="number"
inputMode="numeric"
value={createForm.vat_rate}
onChange={(e) =>
setCreateForm({ ...createForm, vat_rate: e.target.value })
}
slotProps={{ htmlInput: { min: 0 } }}
/>
</Field>
</Box>
</Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Cena za jednotku (bez DPH)">
<TextField
type="number"
inputMode="decimal"
value={createForm.price}
onChange={(e) =>
setCreateForm({ ...createForm, price: e.target.value })
}
placeholder="0"
slotProps={{ htmlInput: { min: 0, step: 0.01 } }}
/>
</Field>
</Box>
<Box sx={{ flex: "1 1 200px" }}>
<Field label="Množství">
<TextField
type="number"
inputMode="decimal"
value={createForm.quantity}
onChange={(e) =>
setCreateForm({ ...createForm, quantity: e.target.value })
}
slotProps={{ htmlInput: { min: 0, step: 1 } }}
/>
</Field>
</Box>
</Box>
<Field label="Předmět (scope)">
<TextField
value={createForm.scope_title}
onChange={(e) =>
setCreateForm({ ...createForm, scope_title: e.target.value })
}
/>
</Field>
<Field label="Popis">
<TextField
multiline
minRows={3}
value={createForm.scope_description}
onChange={(e) =>
setCreateForm({
...createForm,
scope_description: e.target.value,
})
}
/>
</Field>
<Field label="Poznámka">
<TextField
multiline
minRows={2}
value={createForm.notes}
onChange={(e) =>
setCreateForm({ ...createForm, notes: e.target.value })
}
/>
</Field>
<Field label="Příloha (PO zákazníka, PDF)">
<FileUpload
files={orderAttachment ? [orderAttachment] : []}
onFilesChange={(files) => setOrderAttachment(files[0] ?? null)}
accept="application/pdf"
multiple={false}
/>
</Field>
<CheckboxField
label="Účtovat DPH"
checked={createForm.apply_vat}
onChange={(v) => setCreateForm({ ...createForm, apply_vat: v })}
/>
<CheckboxField
label="Vytvořit propojený projekt"
checked={createForm.create_project}
onChange={(v) => setCreateForm({ ...createForm, create_project: v })}
/>
</Modal>
</PageEnter>
);
}