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:
BOHA
2026-06-10 16:22:39 +02:00
parent 1c1b9dca17
commit d1533ffc4d
35 changed files with 4762 additions and 2835 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -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}
/>

File diff suppressed because it is too large Load Diff

View File

@@ -23,10 +23,12 @@ import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { useDocumentListPdf } from "../hooks/useDocumentPdf";
import {
offerListOptions,
offerStatsOptions,
offerCustomersOptions,
type Quotation,
} from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import {
@@ -69,20 +71,6 @@ const STATUS_FILTERS = statusOptions(OFFER_STATUS, {
label: "Všechny",
}).filter((o) => o.value !== "expired");
interface Quotation {
id: number;
quotation_number: string;
project_code: string;
customer_name: string;
created_at: string;
valid_until: string;
currency: string;
total: number;
status: string;
order_id?: number;
order_status?: string;
}
const TemplatesIcon = (
<svg
width="20"
@@ -336,25 +324,17 @@ export default function Offers() {
show: boolean;
quotation: Quotation | null;
}>({ show: false, quotation: null });
const [deleting, setDeleting] = useState(false);
const [invalidateConfirm, setInvalidateConfirm] = useState<{
show: boolean;
quotation: Quotation | null;
}>({ show: false, quotation: null });
const [invalidating, setInvalidating] = useState(false);
const blobUrlRef = useRef<string | null>(null);
useEffect(() => {
return () => {
if (blobUrlRef.current) {
URL.revokeObjectURL(blobUrlRef.current);
blobUrlRef.current = null;
}
};
}, []);
const [duplicating, setDuplicating] = useState<number | null>(null);
const [pdfLoading, setPdfLoading] = useState<number | null>(null);
const [creatingOrder, setCreatingOrder] = useState<number | null>(null);
// Shared hardened PDF flow (per-row spinner, double-click guard, 401 silent
// close, blob-URL revoke + unmount cleanup) — same hook as the issued list.
const { openPdf, pdfLoadingId } = useDocumentListPdf();
const [orderModal, setOrderModal] = useState<{
show: boolean;
quotation: Quotation | null;
@@ -490,13 +470,10 @@ export default function Offers() {
const handleDelete = async () => {
if (!deleteConfirm.quotation) return;
setDeleting(true);
try {
await deleteOfferMutation.mutateAsync(deleteConfirm.quotation.id);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
setDeleting(false);
}
};
@@ -512,37 +489,6 @@ export default function Offers() {
}
};
const handlePdf = async (quotation: Quotation) => {
if (pdfLoading) return;
const newWindow = window.open("", "_blank");
setPdfLoading(quotation.id);
try {
const response = await apiFetch(
`${API_BASE}/offers/${quotation.id}/file`,
);
if (response.status === 401) {
newWindow?.close();
return;
}
if (!response.ok) {
newWindow?.close();
alert.error("PDF soubor nenalezen — otevřete nabídku a uložte ji");
return;
}
const blob = await response.blob();
if (blobUrlRef.current) {
URL.revokeObjectURL(blobUrlRef.current);
}
blobUrlRef.current = URL.createObjectURL(blob);
if (newWindow) newWindow.location.href = blobUrlRef.current;
} catch {
newWindow?.close();
alert.error("Chyba připojení");
} finally {
setPdfLoading(null);
}
};
// Only show the full-page skeleton on the very first load; on subsequent
// refetches (filter/customer/tab/page change) keep the table visible (the
// Card dims via isFetching) so it doesn't flash.
@@ -573,6 +519,7 @@ export default function Offers() {
header: "Číslo",
width: "13%",
sortKey: "quotation_number",
mono: true,
render: (q) => (
<Box
component={RouterLink}
@@ -597,7 +544,7 @@ export default function Offers() {
{
key: "customer_name",
header: "Zákazník",
width: "13%",
width: "16%",
render: (q) => q.customer_name || "—",
},
{
@@ -637,17 +584,10 @@ export default function Offers() {
);
},
},
{
key: "currency",
header: "Měna",
width: "7%",
sortKey: "currency",
render: (q) => <StatusChip label={q.currency} color="default" />,
},
{
key: "total",
header: "Celkem",
width: "11%",
width: "12%",
align: "right",
mono: true,
bold: true,
@@ -693,7 +633,9 @@ export default function Offers() {
{OrderViewIcon}
</IconButton>
) : (
!readOnly &&
// Only active offers can spawn an order — the server transition
// guard rejects drafts/invalidated with a 400.
q.status === "active" &&
hasPermission("orders.create") && (
<IconButton
size="small"
@@ -714,15 +656,20 @@ export default function Offers() {
</IconButton>
)
)}
{hasPermission("offers.view") && (
{/* Drafts have no number yet — /file 404s for them. */}
{hasPermission("offers.view") && q.quotation_number && (
<IconButton
size="small"
onClick={() => handlePdf(q)}
onClick={() => openPdf(q.id, `${API_BASE}/offers/${q.id}/file`)}
aria-label="Zobrazit nabídku"
title="Zobrazit nabídku"
disabled={pdfLoading === q.id}
disabled={pdfLoadingId === q.id}
>
{pdfLoading === q.id ? <CircularProgress size={16} /> : PdfIcon}
{pdfLoadingId === q.id ? (
<CircularProgress size={16} />
) : (
PdfIcon
)}
</IconButton>
)}
{hasPermission("offers.delete") && (
@@ -927,10 +874,10 @@ export default function Offers() {
onClose={() => setDeleteConfirm({ show: false, quotation: null })}
onConfirm={handleDelete}
title="Smazat nabídku"
message={`Opravdu chcete smazat nabídku "${deleteConfirm.quotation?.quotation_number}"? Budou smazány i všechny položky a sekce. Tato akce je nevratná.`}
message={`Opravdu chcete smazat nabídku ${documentNumberLabel(deleteConfirm.quotation?.quotation_number)}? Budou smazány i všechny položky a sekce. Tato akce je nevratná.`}
confirmText="Smazat"
confirmVariant="danger"
loading={deleting}
loading={deleteOfferMutation.isPending}
/>
<ConfirmDialog
@@ -938,7 +885,7 @@ export default function Offers() {
onClose={() => setInvalidateConfirm({ show: false, quotation: null })}
onConfirm={handleInvalidate}
title="Zneplatnit nabídku"
message={`Opravdu chcete zneplatnit nabídku "${invalidateConfirm.quotation?.quotation_number}"? Nabídka bude pouze pro čtení a nepůjde upravovat.`}
message={`Opravdu chcete zneplatnit nabídku ${documentNumberLabel(invalidateConfirm.quotation?.quotation_number)}? Nabídka bude pouze pro čtení a nepůjde upravovat.`}
confirmText="Zneplatnit"
confirmVariant="danger"
loading={invalidating}

View File

@@ -198,7 +198,8 @@ export default function OffersCustomers() {
? `${API_BASE}/customers/${editingCustomer.id}`
: `${API_BASE}/customers`,
method: () => (editingCustomer ? "PUT" : "POST"),
invalidate: ["offer-customers", "offers"],
// Broad domain key — covers the ["offers","customers"] picker query too.
invalidate: ["offers"],
onSuccess: (data) => {
closeModal();
setTimeout(
@@ -214,7 +215,8 @@ export default function OffersCustomers() {
>({
url: (id) => `${API_BASE}/customers/${id}`,
method: () => "DELETE",
invalidate: ["offer-customers", "offers"],
// Broad domain key — covers the ["offers","customers"] picker query too.
invalidate: ["offers"],
onSuccess: (data) => {
setDeleteConfirm({ show: false, customer: null });
alert.success(data?.message || "Zákazník byl smazán");