feat(documents)!: unify offers and issued orders end to end
One coherent pass over the two sibling document models, driven by a 3-lens
1:1 scan (~60 divergences inventoried) + user decisions. Migration adds
issued_orders.locked_by/locked_at and the issued_order_sections table
(mirror of scope_sections; applied to dev + test DBs).
Issued orders gained (offers as reference implementation):
- rich-text SECTIONS with CZ/EN titles, rendered on their own PDF page in
the PO template's red style (shared DocumentSectionSchema, one-transaction
create/update incl. items - fixes a torn-write bug)
- edit LOCKING (lock/heartbeat/unlock routes, 423 + holder name, 30s TTL =
3 missed 10s heartbeats; locked_by enrichment on detail)
- archived-PDF serving: GET /:id/file reads the NAS copy (new
readIssuedByNumber sweep) with live-render fallback + re-archive; offers'
/file got the same fallback (kills the 'ulozte nabidku' dead end)
- NAS cleanup on delete, in-tx po_number uniqueness (409), collision-advancing
number previews (also invoice previews), PUT returns assigned po_number
Offers hardened (issued as reference):
- VALID_TRANSITIONS enforced (no more numberless 'ordered' offers; invalidate
follows the table; order creation only from active offers) +
valid_transitions on detail
- explicit 400 instead of silent edits outside draft/active (mirrored on
issued: explicit 400 replaced silent drops)
- customer existence check + Number(null)->0 clear bug fixed; delete of a
linked offer -> 409 instead of P2003 500; error-token convention; Zod caps
DB-aligned (desc 500/unit 20/number 50/project_code 100, isoDateString
dates, ints for positions); audit old/new values + koncept fallbacks;
list id tiebreaks; stats include trimmed; NAS delete dedupe
Frontend unification (6 new shared modules):
- components/document/{DocumentItemsEditor,SectionsEditor,LockBanner}
- hooks/{useDocumentLock,useUnsavedChangesGuard,useDocumentPdf(+list variant)}
- OfferDetail 1940->1100 lines, IssuedOrderDetail 1400->980: headline-only
document number (form field removed), one form layout/readonly convention,
view-permission opens read-only everywhere (issued's editable-for-viewers
hole closed), server-driven transition buttons, dirty guard + Enter submit
on both, useApiMutation everywhere (new opt-in envelope mode), fixed
infinite spinner on failed detail fetch, draft PDFs hidden (no number yet)
- lists: supplier filter + count line on issued, Mena column dropped + mono
numbers on offers, shared hardened per-row PDF flow (spinner, double-click
guard, 401 close, blob cleanup), proper Czech quotes, real CTA empty
states, query-lib cleanups (["offers","customers"] key, typed list rows,
shared CurrencyAmount, retry:false on details)
- pdf-shared.ts: one escapeHtml/cleanQuillHtml(strict)/formatNum(NBSP)/
formatCurrency/formatDate for all four PDF routes; offer PDF keeps its
monochrome look (fractional qty fix: 1.5 no longer prints as 2); issued
PDF language now comes from the document column
+49 tests (suite 364 -> 413). Each stage passed an independent review; final
cross-stage integration review verified the FE<->BE contracts.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,9 @@ import { useState, useEffect, useRef } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, Link as RouterLink } from "react-router-dom";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { useAlert } from "../context/AlertContext";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import Forbidden from "../components/Forbidden";
|
||||
@@ -10,18 +12,21 @@ import {
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
formatMultiCurrency,
|
||||
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 apiFetch from "../utils/api";
|
||||
import { useDocumentListPdf } from "../hooks/useDocumentPdf";
|
||||
import {
|
||||
issuedOrderListOptions,
|
||||
issuedOrderStatsOptions,
|
||||
issuedOrderSuppliersOptions,
|
||||
type IssuedOrder,
|
||||
} from "../lib/queries/issued-orders";
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
DataTable,
|
||||
Pagination,
|
||||
@@ -44,9 +49,15 @@ import {
|
||||
|
||||
const API_BASE = "/api/admin";
|
||||
|
||||
// DELIBERATE deviation from the Offers status-Tabs row: this page is embedded
|
||||
// under the parent Orders page, which already renders the identical centered
|
||||
// kit <Tabs> (Vydané/Přijaté) directly above this component — a second
|
||||
// same-styled tab row would visually fight it (and the sibling "Přijaté" tab
|
||||
// filters via a Select too). So the status filter stays a Select, with the
|
||||
// "all" entry relabeled to match the offers tabs ("Všechny").
|
||||
const STATUS_OPTIONS = statusOptions(ISSUED_ORDER_STATUS, {
|
||||
value: "",
|
||||
label: "Všechny stavy",
|
||||
label: "Všechny",
|
||||
});
|
||||
|
||||
const ViewIcon = (
|
||||
@@ -62,6 +73,19 @@ const ViewIcon = (
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
);
|
||||
const EditIcon = (
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
|
||||
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||
</svg>
|
||||
);
|
||||
const PdfIcon = (
|
||||
<svg
|
||||
width="18"
|
||||
@@ -107,11 +131,18 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
const [search, setSearch] = useState("");
|
||||
const debouncedSearch = useDebounce(search, 300);
|
||||
const [status, setStatus] = useState("");
|
||||
const [supplierFilter, setSupplierFilter] = useState<number | "">("");
|
||||
const [page, setPage] = useState(1);
|
||||
// Track first successful load so later refetches (filter/status/page change)
|
||||
// keep the table visible instead of flashing the full-page skeleton.
|
||||
const hasLoadedOnce = useRef(false);
|
||||
|
||||
const { data: suppliers } = useQuery(issuedOrderSuppliersOptions());
|
||||
|
||||
// Shared hardened PDF flow (per-row spinner, double-click guard, 401 silent
|
||||
// close, blob-URL revoke + unmount cleanup) — same hook as the Offers list.
|
||||
const { openPdf, pdfLoadingId } = useDocumentListPdf();
|
||||
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{
|
||||
show: boolean;
|
||||
order: IssuedOrder | null;
|
||||
@@ -141,8 +172,8 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
sort,
|
||||
order,
|
||||
page,
|
||||
perPage: 20,
|
||||
status: status || undefined,
|
||||
supplier_id: supplierFilter || undefined,
|
||||
month,
|
||||
year,
|
||||
}),
|
||||
@@ -154,6 +185,7 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
issuedOrderStatsOptions({
|
||||
search: debouncedSearch,
|
||||
status: status || undefined,
|
||||
supplier_id: supplierFilter || undefined,
|
||||
month,
|
||||
year,
|
||||
}),
|
||||
@@ -176,30 +208,6 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportPdf = async (o: IssuedOrder) => {
|
||||
// Authenticated open: apiFetch attaches the access token, then we hand the
|
||||
// resulting PDF blob to a window. A raw window.open(url) would be an
|
||||
// unauthenticated top-level navigation and 401 on the token-guarded route.
|
||||
const newWindow = window.open("", "_blank");
|
||||
try {
|
||||
const response = await apiFetch(
|
||||
`${API_BASE}/issued-orders-pdf/${o.id}?lang=cs`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
newWindow?.close();
|
||||
alert.error("Nepodařilo se vygenerovat PDF");
|
||||
return;
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (newWindow) newWindow.location.href = url;
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60000);
|
||||
} catch {
|
||||
newWindow?.close();
|
||||
alert.error("Chyba při generování PDF");
|
||||
}
|
||||
};
|
||||
|
||||
// Only show the full-page skeleton on the very first load; on subsequent
|
||||
// refetches (filter/status/page change) keep the table visible (the Card
|
||||
// dims via isFetching) so it doesn't flash.
|
||||
@@ -234,6 +242,14 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
width: "24%",
|
||||
render: (o) => o.supplier_name || "—",
|
||||
},
|
||||
{
|
||||
key: "order_date",
|
||||
header: "Datum",
|
||||
width: "13%",
|
||||
sortKey: "order_date",
|
||||
mono: true,
|
||||
render: (o) => (o.order_date ? formatDate(o.order_date) : "—"),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
header: "Stav",
|
||||
@@ -246,14 +262,6 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
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",
|
||||
@@ -268,39 +276,52 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
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.view") && (
|
||||
render: (o) => {
|
||||
// Offers' semantics: read-only rows (completed/cancelled) get the
|
||||
// view icon, editable rows get the edit icon.
|
||||
const readOnly = o.status === "completed" || o.status === "cancelled";
|
||||
return (
|
||||
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => handleExportPdf(o)}
|
||||
aria-label="PDF"
|
||||
title="PDF"
|
||||
onClick={() => navigate(`/orders/issued/${o.id}`)}
|
||||
aria-label={readOnly ? "Zobrazit" : "Upravit"}
|
||||
title={readOnly ? "Zobrazit" : "Upravit"}
|
||||
>
|
||||
{PdfIcon}
|
||||
{readOnly ? ViewIcon : EditIcon}
|
||||
</IconButton>
|
||||
)}
|
||||
{hasPermission("orders.delete") && (
|
||||
<IconButton
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => setDeleteConfirm({ show: true, order: o })}
|
||||
aria-label="Smazat"
|
||||
title="Smazat"
|
||||
>
|
||||
{DeleteIcon}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
),
|
||||
{/* Drafts have no number yet — /file 404s for them. */}
|
||||
{hasPermission("orders.view") && o.po_number && (
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() =>
|
||||
openPdf(o.id, `${API_BASE}/issued-orders/${o.id}/file`)
|
||||
}
|
||||
aria-label="Zobrazit objednávku"
|
||||
title="Zobrazit objednávku"
|
||||
disabled={pdfLoadingId === o.id}
|
||||
>
|
||||
{pdfLoadingId === o.id ? (
|
||||
<CircularProgress size={16} />
|
||||
) : (
|
||||
PdfIcon
|
||||
)}
|
||||
</IconButton>
|
||||
)}
|
||||
{hasPermission("orders.delete") && (
|
||||
<IconButton
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => setDeleteConfirm({ show: true, order: o })}
|
||||
aria-label="Smazat"
|
||||
title="Smazat"
|
||||
>
|
||||
{DeleteIcon}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -326,12 +347,25 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
return {};
|
||||
};
|
||||
|
||||
// Search/status filter is active → an empty list means "nothing matches"
|
||||
// (no create CTA); a genuinely empty list keeps the create-CTA empty state.
|
||||
const isFiltered = !!debouncedSearch || !!status;
|
||||
// Search/status/supplier filter is active → an empty list means "nothing
|
||||
// matches" (no create CTA); a genuinely empty list keeps the create-CTA
|
||||
// empty state.
|
||||
const isFiltered = !!debouncedSearch || !!status || !!supplierFilter;
|
||||
|
||||
const total = pagination?.total ?? orders.length;
|
||||
const countLine = `${total} ${czechPlural(
|
||||
total,
|
||||
"objednávka",
|
||||
"objednávky",
|
||||
"objednávek",
|
||||
)}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
|
||||
{countLine}
|
||||
</Typography>
|
||||
|
||||
<FilterBar>
|
||||
<Box sx={{ flex: "1 1 320px" }}>
|
||||
<TextField
|
||||
@@ -354,6 +388,22 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
options={STATUS_OPTIONS}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ flex: "0 0 220px" }}>
|
||||
<Select
|
||||
value={supplierFilter === "" ? "" : String(supplierFilter)}
|
||||
onChange={(value) => {
|
||||
setSupplierFilter(value ? Number(value) : "");
|
||||
setPage(1);
|
||||
}}
|
||||
options={[
|
||||
{ value: "", label: "Všichni dodavatelé" },
|
||||
...(suppliers ?? []).map((s) => ({
|
||||
value: String(s.id),
|
||||
label: s.name,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</Box>
|
||||
</FilterBar>
|
||||
|
||||
<Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
|
||||
@@ -367,14 +417,19 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
onSort={handleSort}
|
||||
empty={
|
||||
isFiltered ? (
|
||||
<EmptyState title="Žádné objednávky neodpovídají filtru." />
|
||||
<EmptyState
|
||||
title="Žádné objednávky neodpovídají filtru"
|
||||
description="Zkuste změnit filtr nebo hledaný výraz."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="Zatím žádné vydané objednávky."
|
||||
description={
|
||||
hasPermission("orders.create")
|
||||
? "Vytvořte první tlačítkem „Vytvořit objednávku."
|
||||
: undefined
|
||||
action={
|
||||
hasPermission("orders.create") ? (
|
||||
<Button component={RouterLink} to="/orders/issued/new">
|
||||
Vytvořit objednávku
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
@@ -415,11 +470,10 @@ export default function IssuedOrders({ month, year }: IssuedOrdersProps) {
|
||||
title="Smazat objednávku"
|
||||
message={
|
||||
deleteConfirm.order
|
||||
? `Opravdu chcete smazat objednávku „${deleteConfirm.order.po_number || ""}"? Tato akce je nevratná.`
|
||||
? `Opravdu chcete smazat objednávku „${documentNumberLabel(deleteConfirm.order.po_number)}“? Budou smazány i všechny položky. Tato akce je nevratná.`
|
||||
: ""
|
||||
}
|
||||
confirmText="Smazat"
|
||||
cancelText="Zrušit"
|
||||
confirmVariant="danger"
|
||||
loading={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user