feat(issued-orders): counterparty is now a supplier (dodavatel), not a customer

Issued orders are purchase orders WE send - they must pick from suppliers
(sklad_suppliers), not from customers. Per user decision customer_id was
REPLACED (not kept alongside): migration drops issued_orders.customer_id and
adds supplier_id FK -> sklad_suppliers (existing rows lose their counterparty
- the feature is days old; re-point them in the UI).

- service: input/filters/search (suppliers.name + ico)/enrichment/detail all
  supplier-based; create validates the supplier inside the transaction and
  update before write -> Czech 400 'Dodavatel nenalezen' instead of P2003 500;
  detail returns a minimal supplier field set (no internal notes leak)
- routes: supplier_id on list + stats; new GET /issued-orders/suppliers
  lookup (orders.view/create/edit guard - orders users lack warehouse.manage
  which guards the warehouse suppliers CRUD), active suppliers only,
  name+id ordering
- PDF: Dodavatel block now renders the supplier (name, newline-split address,
  IC/DIC), layout and both language label sets unchanged
- frontend: new SupplierPicker kit component (CustomerPicker untouched),
  IssuedOrderDetail/IssuedOrders switched to supplier_id/supplier_name; the
  picker keeps a fallback option for orders whose supplier was later
  deactivated; WarehouseSuppliers CRUD now also invalidates issued-orders so
  the picker can't go stale
- tests: issued-orders suite switched to supplier fixtures + new coverage
  (lookup shape + 403, nonexistent supplier 400, PDF supplier block)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-10 11:29:06 +02:00
parent 74ce24e3fa
commit 6a22195c7d
15 changed files with 598 additions and 112 deletions

View File

@@ -156,6 +156,31 @@ function buildAddressLines(
return { name, lines };
}
/**
* Address block for the sklad_suppliers counterparty. Unlike customers (which
* have structured street/city/postal columns), suppliers.address is a single
* Text blob — split it on newlines into one rendered line each (a blob without
* newlines renders as one line). IČO/DIČ come from the supplier's ico/dic
* columns, prefixed with the same translated labels the customer block used.
*/
function buildSupplierLines(
supplier: Record<string, unknown> | null,
tObj: Record<string, string>,
): AddressResult {
if (!supplier) return { name: "", lines: [] };
const name = String(supplier.name || "");
const lines: string[] = [];
if (supplier.address) {
for (const part of String(supplier.address).split(/\r?\n/)) {
const line = part.trim();
if (line) lines.push(line);
}
}
if (supplier.ico) lines.push(`${tObj.ico}${supplier.ico}`);
if (supplier.dic) lines.push(`${tObj.dic}${supplier.dic}`);
return { name, lines };
}
/* ── Translations ────────────────────────────────────────────────── */
type Lang = "cs" | "en";
@@ -165,7 +190,7 @@ const translations: Record<Lang, Record<string, string>> = {
title: "OBJEDNÁVKA",
heading: "OBJEDNÁVKA č.",
// PO direction: WE (company) are the buyer (Odběratel), the
// selected customer record is the supplier (Dodavatel).
// selected sklad_suppliers record is the supplier (Dodavatel).
supplier: "Dodavatel",
buyer: "Odběratel",
issue_date: "Datum vystavení:",
@@ -244,7 +269,7 @@ interface IssuedOrderPdfItem {
export function renderIssuedOrderHtml(
order: IssuedOrderPdfData,
items: IssuedOrderPdfItem[],
customer: Record<string, unknown> | null,
supplier: Record<string, unknown> | null,
settings: Record<string, unknown> | null,
lang: Lang,
issuer: { name: string },
@@ -268,14 +293,14 @@ export function renderIssuedOrderHtml(
}
// PO direction: our company (settings) = Odběratel (buyer);
// the customer record = Dodavatel (supplier).
// the sklad_suppliers record = Dodavatel (supplier).
const buyer = buildAddressLines(settings, true, t); // company → Odběratel
const supplier = buildAddressLines(customer, false, t); // customer → Dodavatel
const supplierAddr = buildSupplierLines(supplier, t); // supplier → Dodavatel
const buyerLinesHtml = buyer.lines
.map((l) => `<div class="address-line">${escapeHtml(l)}</div>`)
.join("");
const supplierLinesHtml = supplier.lines
const supplierLinesHtml = supplierAddr.lines
.map((l) => `<div class="address-line">${escapeHtml(l)}</div>`)
.join("");
@@ -450,7 +475,7 @@ export function renderIssuedOrderHtml(
vertical-align: top;
width: 50%;
}
.header-grid td.addr-customer {
.header-grid td.addr-supplier {
background: #f5f5f5;
}
.header-grid td.details-bank {
@@ -715,7 +740,7 @@ ${indentCSS}
<div class="invoice-title">${escapeHtml(t.heading)} ${poNumber}</div>
</div>
<!-- Odberatel (nase firma) / Dodavatel (zakaznik) + Detaily -->
<!-- Odberatel (nase firma) / Dodavatel (sklad_suppliers) + Detaily -->
<table class="header-grid" cellspacing="0">
<tr>
<td>
@@ -723,9 +748,9 @@ ${indentCSS}
<div class="address-name">${escapeHtml(buyer.name)}</div>
${buyerLinesHtml}
</td>
<td class="addr-customer">
<td class="addr-supplier">
<div class="address-label">${escapeHtml(t.supplier)}</div>
<div class="address-name">${escapeHtml(supplier.name)}</div>
<div class="address-name">${escapeHtml(supplierAddr.name)}</div>
${supplierLinesHtml}
</td>
</tr>
@@ -818,9 +843,9 @@ export default async function issuedOrdersPdfRoutes(fastify: FastifyInstance) {
where: { issued_order_id: id },
orderBy: { position: "asc" },
});
const customer = order.customer_id
? ((await prisma.customers.findUnique({
where: { id: order.customer_id },
const supplier = order.supplier_id
? ((await prisma.sklad_suppliers.findUnique({
where: { id: order.supplier_id },
})) as Record<string, unknown> | null)
: null;
const settings = (await prisma.company_settings.findFirst()) as Record<
@@ -838,7 +863,7 @@ export default async function issuedOrdersPdfRoutes(fastify: FastifyInstance) {
const html = renderIssuedOrderHtml(
order,
items,
customer,
supplier,
settings,
lang,
issuer,

View File

@@ -1,5 +1,6 @@
import { FastifyInstance } from "fastify";
import { requirePermission } from "../../middleware/auth";
import prisma from "../../config/database";
import { requirePermission, requireAnyPermission } from "../../middleware/auth";
import { logAudit } from "../../services/audit";
import { success, error, parseId, paginated } from "../../utils/response";
import { parsePagination, buildPaginationMeta } from "../../utils/pagination";
@@ -34,7 +35,7 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
order,
search,
status: query.status ? String(query.status) : undefined,
customer_id: query.customer_id ? Number(query.customer_id) : undefined,
supplier_id: query.supplier_id ? Number(query.supplier_id) : undefined,
month: query.month ? Number(query.month) : undefined,
year: query.year ? Number(query.year) : undefined,
});
@@ -66,7 +67,7 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
const result = await getIssuedOrderTotals({
search: query.search ? String(query.search) : undefined,
status: query.status ? String(query.status) : undefined,
customer_id: query.customer_id ? Number(query.customer_id) : undefined,
supplier_id: query.supplier_id ? Number(query.supplier_id) : undefined,
month: query.month ? Number(query.month) : undefined,
year: query.year ? Number(query.year) : undefined,
});
@@ -74,6 +75,40 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
},
);
// GET /api/admin/issued-orders/suppliers — lightweight supplier lookup for
// the PO supplier picker. Guarded by the ORDERS permissions (any of
// view/create/edit), NOT warehouse.manage: the warehouse suppliers CRUD is
// gated by warehouse.manage, which orders users typically lack — without
// this endpoint they couldn't populate the picker. Registered BEFORE "/:id"
// so the literal "suppliers" path isn't captured as an order id.
fastify.get(
"/suppliers",
{
preHandler: requireAnyPermission(
"orders.view",
"orders.create",
"orders.edit",
),
},
async (_request, reply) => {
const suppliers = await prisma.sklad_suppliers.findMany({
where: { is_active: true },
select: {
id: true,
name: true,
ico: true,
dic: true,
address: true,
email: true,
phone: true,
},
// id tiebreak so same-name suppliers sort deterministically.
orderBy: [{ name: "asc" }, { id: "asc" }],
});
return success(reply, suppliers);
},
);
// GET /api/admin/issued-orders/:id
fastify.get<{ Params: { id: string } }>(
"/:id",
@@ -95,6 +130,11 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
const parsed = parseBody(CreateIssuedOrderSchema, request.body);
if ("error" in parsed) return error(reply, parsed.error, 400);
const order = await createIssuedOrder(parsed.data);
if ("error" in order) {
if (order.error === "supplier_not_found")
return error(reply, "Dodavatel nenalezen", 400);
return error(reply, "Neznámá chyba", 500);
}
await logAudit({
request,
authData: request.authData,
@@ -125,6 +165,8 @@ export default async function issuedOrdersRoutes(fastify: FastifyInstance) {
if ("error" in result) {
if (result.error === "not_found")
return error(reply, "Objednávka nenalezena", 404);
if (result.error === "supplier_not_found")
return error(reply, "Dodavatel nenalezen", 400);
if (result.error === "invalid_transition")
return error(
reply,