Files
app/src/admin/pages/Offers.tsx
BOHA d1533ffc4d 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>
2026-06-10 16:22:39 +02:00

933 lines
28 KiB
TypeScript

import { useState, useEffect, useRef } from "react";
import { Link as RouterLink, useNavigate } 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 Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import apiFetch from "../utils/api";
import {
formatCurrency,
formatDate,
formatMultiCurrency,
czechPlural,
} from "../utils/formatters";
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 {
Button,
Card,
DataTable,
Pagination,
Modal,
ConfirmDialog,
Field,
TextField,
Select,
StatusChip,
FileUpload,
EmptyState,
FilterBar,
Tabs,
PageHeader,
PageEnter,
LoadingState,
type DataColumn,
type TabDef,
} from "../ui";
import {
OFFER_STATUS,
statusLabel,
statusColor,
statusOptions,
documentNumberLabel,
} from "../lib/documentStatus";
const API_BASE = "/api/admin";
// Filter tabs derive from OFFER_STATUS so `draft` ("Koncept") flows in
// automatically; the leading "Všechny" tab is the all-statuses filter. The
// `expired` entry in OFFER_STATUS is a front-end-derived state (not a stored
// value), so it is excluded from the filter tabs.
const STATUS_FILTERS = statusOptions(OFFER_STATUS, {
value: "",
label: "Všechny",
}).filter((o) => o.value !== "expired");
const TemplatesIcon = (
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<rect x="3" y="3" width="18" height="18" rx="2" />
<path d="M3 9h18M9 21V9" />
</svg>
);
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 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 DuplicateIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
);
const OrderViewIcon = (
<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"
>
O
</text>
</svg>
);
const OrderCreateIcon = (
<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 InvalidateIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<circle cx="12" cy="12" r="10" />
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
</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"
>
<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 MoreIcon = (
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="currentColor"
stroke="none"
>
<circle cx="12" cy="5" r="1.6" />
<circle cx="12" cy="12" r="1.6" />
<circle cx="12" cy="19" r="1.6" />
</svg>
);
/**
* Per-row overflow menu for the secondary offer actions (Duplicate +
* Zneplatnit). Hook state (anchorEl) lives HERE, in a child component — never
* in the page-level `.map`/render callback — so each row owns its own menu
* (no shared-open bug) and Rules of Hooks stay satisfied. The page passes in
* the same handlers + permission/disabled flags the inline icons used, so
* behavior/permissions/confirms are preserved verbatim; the items are merely
* relocated. The menu renders nothing (returns null) when no secondary action
* is available for the row.
*/
function RowActionsMenu({
canDuplicate,
duplicating,
onDuplicate,
canInvalidate,
onInvalidate,
}: {
canDuplicate: boolean;
duplicating: boolean;
onDuplicate: () => void;
canInvalidate: boolean;
onInvalidate: () => void;
}) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
if (!canDuplicate && !canInvalidate) return null;
const close = () => setAnchorEl(null);
return (
<>
<IconButton
size="small"
onClick={(e) => setAnchorEl(e.currentTarget)}
aria-label="Další akce"
title="Další akce"
>
{MoreIcon}
</IconButton>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={close}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
transformOrigin={{ vertical: "top", horizontal: "right" }}
>
{canDuplicate && (
<MenuItem
disabled={duplicating}
onClick={() => {
close();
onDuplicate();
}}
>
<ListItemIcon>
{duplicating ? <CircularProgress size={16} /> : DuplicateIcon}
</ListItemIcon>
<ListItemText>Duplikovat</ListItemText>
</MenuItem>
)}
{canInvalidate && (
<MenuItem
onClick={() => {
close();
onInvalidate();
}}
>
<ListItemIcon>{InvalidateIcon}</ListItemIcon>
<ListItemText>Zneplatnit</ListItemText>
</MenuItem>
)}
</Menu>
</>
);
}
export default function Offers() {
const alert = useAlert();
const { hasPermission } = useAuth();
const navigate = useNavigate();
const { sort, order, handleSort } = useTableSort("quotation_number");
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [page, setPage] = useState(1);
const [statusFilter, setStatusFilter] = useState("");
const [customerFilter, setCustomerFilter] = useState<number | "">("");
// Track first successful load so later refetches (filter/customer/tab/page
// change) keep the table visible instead of flashing the full skeleton.
const hasLoadedOnce = useRef(false);
const { data: customers } = useQuery(offerCustomersOptions());
const [deleteConfirm, setDeleteConfirm] = useState<{
show: boolean;
quotation: Quotation | null;
}>({ show: false, quotation: null });
const [invalidateConfirm, setInvalidateConfirm] = useState<{
show: boolean;
quotation: Quotation | null;
}>({ show: false, quotation: null });
const [invalidating, setInvalidating] = useState(false);
const [duplicating, setDuplicating] = 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;
}>({ show: false, quotation: null });
const [customerOrderNumber, setCustomerOrderNumber] = useState("");
const [orderAttachment, setOrderAttachment] = useState<File | null>(null);
const queryClient = useQueryClient();
const {
items: quotations,
pagination,
isPending,
isFetching,
} = usePaginatedQuery<Quotation>(
offerListOptions({
search: debouncedSearch,
sort,
order,
page,
status: statusFilter || undefined,
customer_id: customerFilter || undefined,
}),
);
// Per-currency total over the WHOLE filtered set (not one page). Uses the
// SAME filters as the list query so the summary matches what's shown.
const statsQuery = useQuery(
offerStatsOptions({
search: debouncedSearch,
status: statusFilter || undefined,
customer_id: customerFilter || undefined,
}),
);
// Mark first load done in an effect (not during render) to avoid a
// render-phase ref mutation.
useEffect(() => {
if (!isPending) hasLoadedOnce.current = true;
}, [isPending]);
const duplicateMutation = useApiMutation<
number,
{ message?: string; error?: string }
>({
url: (id) => `${API_BASE}/offers/${id}/duplicate`,
method: () => "POST",
invalidate: ["offers", "orders", "projects", "invoices"],
onSuccess: (data) => {
alert.success(data?.message || "Nabídka byla duplikována");
},
});
const deleteOfferMutation = useApiMutation<
number,
{ message?: string; error?: string }
>({
url: (id) => `${API_BASE}/offers/${id}`,
method: () => "DELETE",
invalidate: ["offers", "orders", "projects", "invoices"],
onSuccess: (data) => {
setDeleteConfirm({ show: false, quotation: null });
alert.success(data?.message || "Nabídka byla smazána");
},
});
const invalidateMutation = useApiMutation<
number,
{ message?: string; error?: string }
>({
url: (id) => `${API_BASE}/offers/${id}/invalidate`,
method: () => "POST",
invalidate: ["offers", "orders", "projects", "invoices"],
onSuccess: (data) => {
setInvalidateConfirm({ show: false, quotation: null });
alert.success(data?.message || "Nabídka byla zneplatněna");
},
});
if (!hasPermission("offers.view")) return <Forbidden />;
const handleDuplicate = async (quotation: Quotation) => {
setDuplicating(quotation.id);
try {
await duplicateMutation.mutateAsync(quotation.id);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
setDuplicating(null);
}
};
const handleCreateOrder = async () => {
if (!customerOrderNumber.trim() || !orderModal.quotation) return;
setCreatingOrder(orderModal.quotation.id);
try {
let fetchOptions: RequestInit;
if (orderAttachment) {
// With attachment: send as multipart/form-data
const formData = new FormData();
formData.append("quotationId", String(orderModal.quotation.id));
formData.append("customerOrderNumber", customerOrderNumber.trim());
formData.append("attachment", orderAttachment);
fetchOptions = { method: "POST", body: formData };
} else {
fetchOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
quotationId: orderModal.quotation.id,
customerOrderNumber: customerOrderNumber.trim(),
}),
};
}
const response = await apiFetch(`${API_BASE}/orders`, fetchOptions);
const result = await response.json();
if (result.success) {
setOrderModal({ show: false, quotation: null });
alert.success(result.message || "Objednávka byla vytvořena");
queryClient.invalidateQueries({ queryKey: ["offers"] });
queryClient.invalidateQueries({ queryKey: ["orders"] });
queryClient.invalidateQueries({ queryKey: ["projects"] });
queryClient.invalidateQueries({ queryKey: ["invoices"] });
navigate(`/orders/${result.data.order_id}`);
} else {
alert.error(result.error || "Nepodařilo se vytvořit objednávku");
}
} catch {
alert.error("Chyba připojení");
} finally {
setCreatingOrder(null);
}
};
const handleDelete = async () => {
if (!deleteConfirm.quotation) return;
try {
await deleteOfferMutation.mutateAsync(deleteConfirm.quotation.id);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
}
};
const handleInvalidate = async () => {
if (!invalidateConfirm.quotation) return;
setInvalidating(true);
try {
await invalidateMutation.mutateAsync(invalidateConfirm.quotation.id);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {
setInvalidating(false);
}
};
// 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.
if (isPending && !hasLoadedOnce.current) {
return <LoadingState />;
}
const total = pagination?.total ?? quotations.length;
const subtitle = `${total} ${czechPlural(
total,
"nabídka",
"nabídky",
"nabídek",
)}`;
const tabs: TabDef[] = STATUS_FILTERS.map((f) => ({
value: f.value,
label: f.label,
}));
// 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 || !!statusFilter;
const columns: DataColumn<Quotation>[] = [
{
key: "quotation_number",
header: "Číslo",
width: "13%",
sortKey: "quotation_number",
mono: true,
render: (q) => (
<Box
component={RouterLink}
to={`/offers/${q.id}`}
sx={{
color: "primary.main",
textDecoration: "none",
"&:hover": { textDecoration: "underline" },
}}
>
{documentNumberLabel(q.quotation_number)}
</Box>
),
},
{
key: "project_code",
header: "Projekt",
width: "13%",
sortKey: "project_code",
render: (q) => q.project_code || "—",
},
{
key: "customer_name",
header: "Zákazník",
width: "16%",
render: (q) => q.customer_name || "—",
},
{
key: "created_at",
header: "Datum",
width: "11%",
sortKey: "created_at",
mono: true,
render: (q) => formatDate(q.created_at),
},
{
key: "valid_until",
header: "Platnost",
width: "10%",
sortKey: "valid_until",
mono: true,
render: (q) => formatDate(q.valid_until),
},
{
key: "status",
header: "Stav",
width: "10%",
sortKey: "status",
render: (q) => {
// The offer's own status is `active`/`ordered`/`invalidated`. When its
// linked order is completed, surface that as "Dokončená" (success) —
// matching the OfferDetail header chip and the completed row tint.
const completed =
q.status !== "invalidated" && q.order_status === "dokoncena";
return completed ? (
<StatusChip label="Dokončená" color="success" />
) : (
<StatusChip
label={statusLabel(OFFER_STATUS, q.status)}
color={statusColor(OFFER_STATUS, q.status)}
/>
);
},
},
{
key: "total",
header: "Celkem",
width: "12%",
align: "right",
mono: true,
bold: true,
render: (q) => formatCurrency(q.total, q.currency),
},
{
key: "actions",
header: "Akce",
width: "15%",
align: "right",
render: (q) => {
const isInvalidated = q.status === "invalidated";
const isCompleted = !isInvalidated && q.order_status === "dokoncena";
const readOnly = isInvalidated || isCompleted;
// Secondary actions (relocated into the overflow menu). Same gates as
// before: Duplicate needs offers.create and an editable (not
// read-only) row; Zneplatnit needs offers.edit and a row that is not
// invalidated/completed/ordered.
const canDuplicate = !readOnly && hasPermission("offers.create");
const canInvalidate =
!isInvalidated &&
!isCompleted &&
!q.order_id &&
hasPermission("offers.edit");
return (
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
<IconButton
size="small"
onClick={() => navigate(`/offers/${q.id}`)}
aria-label={readOnly ? "Zobrazit" : "Upravit"}
title={readOnly ? "Zobrazit" : "Upravit"}
>
{readOnly ? ViewIcon : EditIcon}
</IconButton>
{!readOnly && q.order_id ? (
<IconButton
size="small"
color="primary"
onClick={() => navigate(`/orders/${q.order_id}`)}
aria-label="Zobrazit objednávku"
title="Zobrazit objednávku"
>
{OrderViewIcon}
</IconButton>
) : (
// 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"
onClick={() => {
setCustomerOrderNumber("");
setOrderAttachment(null);
setOrderModal({ show: true, quotation: q });
}}
aria-label="Vytvořit objednávku"
title="Vytvořit objednávku"
disabled={creatingOrder === q.id}
>
{creatingOrder === q.id ? (
<CircularProgress size={16} />
) : (
OrderCreateIcon
)}
</IconButton>
)
)}
{/* Drafts have no number yet — /file 404s for them. */}
{hasPermission("offers.view") && q.quotation_number && (
<IconButton
size="small"
onClick={() => openPdf(q.id, `${API_BASE}/offers/${q.id}/file`)}
aria-label="Zobrazit nabídku"
title="Zobrazit nabídku"
disabled={pdfLoadingId === q.id}
>
{pdfLoadingId === q.id ? (
<CircularProgress size={16} />
) : (
PdfIcon
)}
</IconButton>
)}
{hasPermission("offers.delete") && (
<IconButton
size="small"
color="error"
onClick={() => setDeleteConfirm({ show: true, quotation: q })}
aria-label="Smazat"
title="Smazat"
>
{DeleteIcon}
</IconButton>
)}
<RowActionsMenu
canDuplicate={canDuplicate}
duplicating={duplicating === q.id}
onDuplicate={() => handleDuplicate(q)}
canInvalidate={canInvalidate}
onInvalidate={() =>
setInvalidateConfirm({ show: true, quotation: q })
}
/>
</Box>
);
},
},
];
// Per-status row tints (replaces offers-invalidated-row / offers-completed-row
// / offers-expired-row). These are LOW-ALPHA washes via the palette channel
// vars (not solid `.light` fills — those turn the white dark-mode row text
// invisible and read garish in light mode). Invalidated = faded/muted, matching
// the original "voided" look. Readable in BOTH schemes because the underlying
// row text keeps its normal theme color.
const rowSx = (q: Quotation) => {
const isInvalidated = q.status === "invalidated";
const isCompleted = !isInvalidated && q.order_status === "dokoncena";
const isExpired =
!isInvalidated &&
!isCompleted &&
!q.order_id &&
q.valid_until &&
new Date(q.valid_until) < new Date(new Date().toDateString());
if (isInvalidated) {
return {
opacity: 0.6,
"& td": { color: "var(--mui-palette-text-secondary)" },
};
}
if (isCompleted) {
return {
backgroundColor: "rgba(var(--mui-palette-success-mainChannel) / 0.12)",
"&:hover": {
backgroundColor:
"rgba(var(--mui-palette-success-mainChannel) / 0.18)",
},
};
}
if (isExpired) {
return {
backgroundColor: "rgba(var(--mui-palette-warning-mainChannel) / 0.12)",
"&:hover": {
backgroundColor:
"rgba(var(--mui-palette-warning-mainChannel) / 0.18)",
},
};
}
return {};
};
return (
<PageEnter>
<PageHeader
title="Nabídky"
subtitle={subtitle}
actions={
<>
{hasPermission("settings.templates") && (
<Button
component={RouterLink}
to="/offers/templates"
variant="outlined"
color="inherit"
startIcon={TemplatesIcon}
>
Šablony
</Button>
)}
{hasPermission("offers.create") && (
<Button
component={RouterLink}
to="/offers/new"
startIcon={PlusIcon}
>
Nová nabídka
</Button>
)}
</>
}
/>
<Box sx={{ display: "flex", justifyContent: "center", mb: 2.5 }}>
<Tabs
value={statusFilter}
onChange={(v) => {
setStatusFilter(v);
setPage(1);
}}
tabs={tabs}
/>
</Box>
<FilterBar>
<Box sx={{ flex: "1 1 320px" }}>
<TextField
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
placeholder="Hledat podle čísla, projektu nebo zákazníka..."
fullWidth
/>
</Box>
<Box sx={{ flex: "0 0 220px" }}>
<Select
value={customerFilter === "" ? "" : String(customerFilter)}
onChange={(value) => {
setCustomerFilter(value ? Number(value) : "");
setPage(1);
}}
options={[
{ value: "", label: "Všichni zákazníci" },
...(customers ?? []).map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
</Box>
</FilterBar>
<Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
<DataTable<Quotation>
columns={columns}
rows={quotations}
rowKey={(q) => q.id}
rowSx={rowSx}
sortBy={sort}
sortDir={order}
onSort={handleSort}
empty={
isFiltered ? (
<EmptyState
title="Žádné nabídky neodpovídají filtru"
description="Zkuste změnit filtr nebo hledaný výraz."
/>
) : (
<EmptyState
title="Zatím nejsou žádné nabídky."
action={
hasPermission("offers.create") ? (
<Button component={RouterLink} to="/offers/new">
Vytvořit první nabídku
</Button>
) : undefined
}
/>
)
}
/>
{(statsQuery.data?.length ?? 0) > 0 && (
<Box
sx={{
display: "flex",
justifyContent: "flex-end",
mt: 1.5,
px: 1,
gap: 1,
color: "text.secondary",
fontSize: "0.9rem",
}}
>
<span>Celkem bez DPH:</span>
<Box
component="span"
sx={{ fontWeight: 700, color: "text.primary" }}
>
{formatMultiCurrency(statsQuery.data ?? [])}
</Box>
</Box>
)}
<Pagination
page={page}
pageCount={pagination?.total_pages ?? 1}
onChange={setPage}
/>
</Card>
<ConfirmDialog
isOpen={deleteConfirm.show}
onClose={() => setDeleteConfirm({ show: false, quotation: null })}
onConfirm={handleDelete}
title="Smazat nabídku"
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={deleteOfferMutation.isPending}
/>
<ConfirmDialog
isOpen={invalidateConfirm.show}
onClose={() => setInvalidateConfirm({ show: false, quotation: null })}
onConfirm={handleInvalidate}
title="Zneplatnit nabídku"
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}
/>
<Modal
isOpen={orderModal.show}
onClose={() => setOrderModal({ show: false, quotation: null })}
onSubmit={handleCreateOrder}
title="Vytvořit objednávku"
subtitle={`Nabídka: ${orderModal.quotation?.quotation_number ?? ""}`}
submitText="Vytvořit"
loading={!!creatingOrder}
>
<Field label="Číslo objednávky zákazníka" required>
<TextField
value={customerOrderNumber}
onChange={(e) => setCustomerOrderNumber(e.target.value)}
onKeyDown={(e) =>
e.key === "Enter" && !creatingOrder && handleCreateOrder()
}
placeholder="Např. PO-2026-001"
autoFocus
/>
</Field>
<Field label="Příloha (PDF)">
<FileUpload
files={orderAttachment ? [orderAttachment] : []}
onFilesChange={(files) => setOrderAttachment(files[0] ?? null)}
accept="application/pdf"
multiple={false}
/>
<Typography
variant="caption"
color="text.secondary"
sx={{ display: "block", mt: 0.5 }}
>
Max 10 MB
</Typography>
</Field>
</Modal>
</PageEnter>
);
}