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:
@@ -1,4 +1,4 @@
|
||||
import type { $Enums } from "@prisma/client";
|
||||
import { Prisma, type $Enums } from "@prisma/client";
|
||||
import prisma from "../config/database";
|
||||
import { utcMidnightOfLocalDay } from "../utils/date";
|
||||
import {
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
previewIssuedOrderNumber,
|
||||
releaseIssuedOrderNumber,
|
||||
assignIssuedOrderNumber,
|
||||
isIssuedOrderNumberTaken,
|
||||
} from "./numbering.service";
|
||||
import { nasOrdersManager } from "./nas-financials-manager";
|
||||
|
||||
export interface IssuedOrderItemInput {
|
||||
description?: string | null;
|
||||
@@ -17,6 +19,13 @@ export interface IssuedOrderItemInput {
|
||||
position?: number | null;
|
||||
}
|
||||
|
||||
export interface IssuedOrderSectionInput {
|
||||
title?: string | null;
|
||||
title_cz?: string | null;
|
||||
content?: string | null;
|
||||
position?: number | null;
|
||||
}
|
||||
|
||||
export interface IssuedOrderInput {
|
||||
po_number?: string | number | null;
|
||||
supplier_id?: number | string | null;
|
||||
@@ -33,6 +42,7 @@ export interface IssuedOrderInput {
|
||||
notes?: string | null;
|
||||
internal_notes?: string | null;
|
||||
items?: IssuedOrderItemInput[];
|
||||
sections?: IssuedOrderSectionInput[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -100,9 +110,33 @@ const ALLOWED_SORT_FIELDS = [
|
||||
"po_number",
|
||||
"status",
|
||||
"order_date",
|
||||
"created_at",
|
||||
"currency",
|
||||
];
|
||||
|
||||
/**
|
||||
* Non-status update fields — used by the editable-state guard so a field edit
|
||||
* on a confirmed/completed/cancelled order is rejected EXPLICITLY (it used to
|
||||
* be silently dropped). `po_number` is stripped by the schema and the service
|
||||
* never reads it on update.
|
||||
*/
|
||||
const NON_STATUS_UPDATE_FIELDS = [
|
||||
"supplier_id",
|
||||
"currency",
|
||||
"exchange_rate",
|
||||
"order_date",
|
||||
"delivery_date",
|
||||
"language",
|
||||
"delivery_terms",
|
||||
"payment_terms",
|
||||
"issued_by",
|
||||
"order_text",
|
||||
"notes",
|
||||
"internal_notes",
|
||||
"items",
|
||||
"sections",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* NET-only total: issued orders (PO) are not tax documents — VAT never appears
|
||||
* on them. The total is the plain sum of qty × unit_price, rounded to 2dp.
|
||||
@@ -211,13 +245,18 @@ export async function getIssuedOrder(id: number) {
|
||||
},
|
||||
},
|
||||
issued_order_items: { orderBy: { position: "asc" } },
|
||||
// id tiebreak: position can repeat, keep the order deterministic.
|
||||
issued_order_sections: {
|
||||
orderBy: [{ position: "asc" }, { id: "asc" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!order) return null;
|
||||
const { issued_order_items, ...rest } = order;
|
||||
const { issued_order_items, issued_order_sections, ...rest } = order;
|
||||
return {
|
||||
...rest,
|
||||
items: issued_order_items,
|
||||
sections: issued_order_sections,
|
||||
supplier: order.suppliers,
|
||||
supplier_name: order.suppliers?.name || null,
|
||||
valid_transitions: VALID_TRANSITIONS[order.status as string] || [],
|
||||
@@ -225,83 +264,117 @@ export async function getIssuedOrder(id: number) {
|
||||
}
|
||||
|
||||
export async function createIssuedOrder(body: IssuedOrderInput) {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const status = body.status ? String(body.status) : "draft";
|
||||
try {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
const status = body.status ? String(body.status) : "draft";
|
||||
|
||||
// Validate the referenced supplier exists BEFORE the insert — a dangling
|
||||
// FK would otherwise surface as a P2003 500 instead of a clean 400.
|
||||
const supplierId = body.supplier_id ? Number(body.supplier_id) : null;
|
||||
if (supplierId) {
|
||||
const supplier = await tx.sklad_suppliers.findUnique({
|
||||
where: { id: supplierId },
|
||||
select: { id: true },
|
||||
// Validate the referenced supplier exists BEFORE the insert — a dangling
|
||||
// FK would otherwise surface as a P2003 500 instead of a clean 400.
|
||||
const supplierId = body.supplier_id ? Number(body.supplier_id) : null;
|
||||
if (supplierId) {
|
||||
const supplier = await tx.sklad_suppliers.findUnique({
|
||||
where: { id: supplierId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!supplier) return { error: "supplier_not_found" as const };
|
||||
}
|
||||
|
||||
// Deferred numbering: a draft carries NO po_number (the column is
|
||||
// nullable-unique so many drafts coexist). The official number is consumed
|
||||
// only when the draft is finalized (assignIssuedOrderNumber on draft->sent).
|
||||
// A caller-supplied number, or a doc created already-finalized, numbers now.
|
||||
const explicit =
|
||||
body.po_number !== undefined &&
|
||||
body.po_number !== null &&
|
||||
body.po_number !== ""
|
||||
? String(body.po_number)
|
||||
: null;
|
||||
|
||||
// Re-check caller-supplied uniqueness INSIDE the transaction so the
|
||||
// check-then-insert window can't race a concurrent create (mirrors
|
||||
// createOffer). generateIssuedOrderNumber verifies its own numbers,
|
||||
// so this guards only the explicit path.
|
||||
if (explicit !== null && (await isIssuedOrderNumberTaken(explicit, tx))) {
|
||||
return { error: "po_number_taken" as const };
|
||||
}
|
||||
|
||||
const poNumber =
|
||||
explicit ??
|
||||
(status === "draft"
|
||||
? null
|
||||
: (await generateIssuedOrderNumber(undefined, tx)).number);
|
||||
|
||||
const order = await tx.issued_orders.create({
|
||||
data: {
|
||||
po_number: poNumber,
|
||||
supplier_id: supplierId,
|
||||
status: status as $Enums.issued_orders_status,
|
||||
currency: body.currency ? String(body.currency) : "CZK",
|
||||
exchange_rate:
|
||||
body.exchange_rate != null ? Number(body.exchange_rate) : 1.0,
|
||||
// order_date is @db.Date (truncated to the UTC date part) — the
|
||||
// "today" default must be utcMidnightOfLocalDay, or it stores
|
||||
// yesterday during the 00:00–02:00 Prague window.
|
||||
order_date: body.order_date
|
||||
? new Date(String(body.order_date))
|
||||
: utcMidnightOfLocalDay(),
|
||||
delivery_date: body.delivery_date
|
||||
? new Date(String(body.delivery_date))
|
||||
: null,
|
||||
language: body.language ? String(body.language) : "cs",
|
||||
delivery_terms: body.delivery_terms
|
||||
? String(body.delivery_terms)
|
||||
: null,
|
||||
payment_terms: body.payment_terms ? String(body.payment_terms) : null,
|
||||
issued_by: body.issued_by ? String(body.issued_by) : null,
|
||||
order_text: body.order_text ? String(body.order_text) : null,
|
||||
notes: body.notes ? String(body.notes) : null,
|
||||
internal_notes: body.internal_notes
|
||||
? String(body.internal_notes)
|
||||
: null,
|
||||
},
|
||||
});
|
||||
if (!supplier) return { error: "supplier_not_found" as const };
|
||||
}
|
||||
|
||||
// Deferred numbering: a draft carries NO po_number (the column is
|
||||
// nullable-unique so many drafts coexist). The official number is consumed
|
||||
// only when the draft is finalized (assignIssuedOrderNumber on draft->sent).
|
||||
// A caller-supplied number, or a doc created already-finalized, numbers now.
|
||||
const explicit =
|
||||
body.po_number !== undefined &&
|
||||
body.po_number !== null &&
|
||||
body.po_number !== ""
|
||||
? String(body.po_number)
|
||||
: null;
|
||||
const poNumber =
|
||||
explicit ??
|
||||
(status === "draft"
|
||||
? null
|
||||
: (await generateIssuedOrderNumber(undefined, tx)).number);
|
||||
if (Array.isArray(body.items)) {
|
||||
await tx.issued_order_items.createMany({
|
||||
data: body.items.map((item, i) => ({
|
||||
issued_order_id: order.id,
|
||||
description: item.description ?? null,
|
||||
item_description: item.item_description ?? null,
|
||||
quantity: item.quantity ?? 1,
|
||||
unit: item.unit ?? null,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
position: item.position ?? i,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const order = await tx.issued_orders.create({
|
||||
data: {
|
||||
po_number: poNumber,
|
||||
supplier_id: supplierId,
|
||||
status: status as $Enums.issued_orders_status,
|
||||
currency: body.currency ? String(body.currency) : "CZK",
|
||||
exchange_rate:
|
||||
body.exchange_rate != null ? Number(body.exchange_rate) : 1.0,
|
||||
// order_date is @db.Date (truncated to the UTC date part) — the
|
||||
// "today" default must be utcMidnightOfLocalDay, or it stores
|
||||
// yesterday during the 00:00–02:00 Prague window.
|
||||
order_date: body.order_date
|
||||
? new Date(String(body.order_date))
|
||||
: utcMidnightOfLocalDay(),
|
||||
delivery_date: body.delivery_date
|
||||
? new Date(String(body.delivery_date))
|
||||
: null,
|
||||
language: body.language ? String(body.language) : "cs",
|
||||
delivery_terms: body.delivery_terms
|
||||
? String(body.delivery_terms)
|
||||
: null,
|
||||
payment_terms: body.payment_terms ? String(body.payment_terms) : null,
|
||||
issued_by: body.issued_by ? String(body.issued_by) : null,
|
||||
order_text: body.order_text ? String(body.order_text) : null,
|
||||
notes: body.notes ? String(body.notes) : null,
|
||||
internal_notes: body.internal_notes
|
||||
? String(body.internal_notes)
|
||||
: null,
|
||||
},
|
||||
if (Array.isArray(body.sections)) {
|
||||
await tx.issued_order_sections.createMany({
|
||||
data: body.sections.map((s, i) => ({
|
||||
issued_order_id: order.id,
|
||||
title: s.title ?? null,
|
||||
title_cz: s.title_cz ?? null,
|
||||
content: s.content ?? null,
|
||||
position: s.position ?? i,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return order;
|
||||
});
|
||||
|
||||
if (Array.isArray(body.items)) {
|
||||
await tx.issued_order_items.createMany({
|
||||
data: body.items.map((item, i) => ({
|
||||
issued_order_id: order.id,
|
||||
description: item.description ?? null,
|
||||
item_description: item.item_description ?? null,
|
||||
quantity: item.quantity ?? 1,
|
||||
unit: item.unit ?? null,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
position: item.position ?? i,
|
||||
})),
|
||||
});
|
||||
} catch (err) {
|
||||
// P2002 on the po_number unique index = a concurrent insert won the race
|
||||
// between the in-tx check and our insert — surface the same clean
|
||||
// conflict token instead of a 500 (mirrors offers).
|
||||
if (
|
||||
err instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
err.code === "P2002"
|
||||
) {
|
||||
return { error: "po_number_taken" as const };
|
||||
}
|
||||
|
||||
return order;
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateIssuedOrder(id: number, body: IssuedOrderInput) {
|
||||
@@ -318,7 +391,18 @@ export async function updateIssuedOrder(id: number, body: IssuedOrderInput) {
|
||||
}
|
||||
}
|
||||
|
||||
// Editable-state guard: non-status fields may change only in draft/sent.
|
||||
// In confirmed/completed/cancelled a field edit is REJECTED explicitly
|
||||
// (offers parity — it used to be silently ignored). Status-only transition
|
||||
// payloads (e.g. confirmed -> completed) still work.
|
||||
const editable = currentStatus === "draft" || currentStatus === "sent";
|
||||
if (
|
||||
!editable &&
|
||||
NON_STATUS_UPDATE_FIELDS.some((f) => body[f] !== undefined)
|
||||
) {
|
||||
return { error: "not_editable" as const, currentStatus };
|
||||
}
|
||||
|
||||
const data: Record<string, unknown> = { modified_at: new Date() };
|
||||
|
||||
if (editable) {
|
||||
@@ -375,46 +459,67 @@ export async function updateIssuedOrder(id: number, body: IssuedOrderInput) {
|
||||
body.status !== undefined &&
|
||||
String(body.status) === "sent";
|
||||
|
||||
if (finalizing) {
|
||||
// ONE transaction for the header write, the finalize numbering AND the
|
||||
// items/sections full-replace. The items replace used to run in a SECOND
|
||||
// transaction after the header tx — a failure between the two left a torn
|
||||
// write (new header, old items). Now either everything lands or nothing.
|
||||
const replaceItems = editable && Array.isArray(body.items);
|
||||
const replaceSections = editable && Array.isArray(body.sections);
|
||||
|
||||
let assignedNumber: string | null = null;
|
||||
if (finalizing || replaceItems || replaceSections) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.issued_orders.update({ where: { id }, data });
|
||||
await assignIssuedOrderNumber(id, tx);
|
||||
if (finalizing) assignedNumber = await assignIssuedOrderNumber(id, tx);
|
||||
if (replaceItems) {
|
||||
await tx.issued_order_items.deleteMany({
|
||||
where: { issued_order_id: id },
|
||||
});
|
||||
await tx.issued_order_items.createMany({
|
||||
data: body.items!.map((item, i) => ({
|
||||
issued_order_id: id,
|
||||
description: item.description ?? null,
|
||||
item_description: item.item_description ?? null,
|
||||
quantity: item.quantity ?? 1,
|
||||
unit: item.unit ?? null,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
position: item.position ?? i,
|
||||
})),
|
||||
});
|
||||
}
|
||||
if (replaceSections) {
|
||||
await tx.issued_order_sections.deleteMany({
|
||||
where: { issued_order_id: id },
|
||||
});
|
||||
await tx.issued_order_sections.createMany({
|
||||
data: body.sections!.map((s, i) => ({
|
||||
issued_order_id: id,
|
||||
title: s.title ?? null,
|
||||
title_cz: s.title_cz ?? null,
|
||||
content: s.content ?? null,
|
||||
position: s.position ?? i,
|
||||
})),
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await prisma.issued_orders.update({ where: { id }, data });
|
||||
}
|
||||
|
||||
if (editable && Array.isArray(body.items)) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.issued_order_items.deleteMany({
|
||||
where: { issued_order_id: id },
|
||||
});
|
||||
await tx.issued_order_items.createMany({
|
||||
data: body.items!.map((item, i) => ({
|
||||
issued_order_id: id,
|
||||
description: item.description ?? null,
|
||||
item_description: item.item_description ?? null,
|
||||
quantity: item.quantity ?? 1,
|
||||
unit: item.unit ?? null,
|
||||
unit_price: item.unit_price ?? 0,
|
||||
position: item.position ?? i,
|
||||
})),
|
||||
});
|
||||
});
|
||||
}
|
||||
// newValues for the audit diff: the header fields actually written plus the
|
||||
// replaced collections (JSON.stringify drops the undefined = untouched keys).
|
||||
const newValues: Record<string, unknown> = { ...data };
|
||||
if (replaceItems) newValues.items = body.items;
|
||||
if (replaceSections) newValues.sections = body.sections;
|
||||
|
||||
// Reflect the number the finalize transition just assigned (existing was read
|
||||
// before the assign, so its po_number is still the pre-finalize null).
|
||||
const poNumber = finalizing
|
||||
? ((
|
||||
await prisma.issued_orders.findUnique({
|
||||
where: { id },
|
||||
select: { po_number: true },
|
||||
})
|
||||
)?.po_number ?? existing.po_number)
|
||||
: existing.po_number;
|
||||
|
||||
return { id, po_number: poNumber };
|
||||
return {
|
||||
id,
|
||||
po_number: assignedNumber ?? existing.po_number,
|
||||
oldValues: existing as unknown as Record<string, unknown>,
|
||||
newValues,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteIssuedOrder(id: number) {
|
||||
@@ -428,6 +533,23 @@ export async function deleteIssuedOrder(id: number) {
|
||||
? new Date(existing.created_at).getFullYear()
|
||||
: new Date().getFullYear();
|
||||
await releaseIssuedOrderNumber(year, existing.po_number ?? undefined);
|
||||
|
||||
// Remove the archived PDF from the NAS so the DB delete doesn't orphan it
|
||||
// (mirrors deleteOffer). cleanIssued sweeps every Vydané/YYYY/MM folder, so
|
||||
// an order whose order_date moved after archiving is still found.
|
||||
// Best-effort: log, never throw.
|
||||
if (existing.po_number && nasOrdersManager.isConfigured()) {
|
||||
try {
|
||||
nasOrdersManager.cleanIssued(existing.po_number);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"[issued-orders.service] NAS issued-order PDF delete failed for",
|
||||
existing.po_number,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return existing;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user