Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(purchasing): lay the RFQ PDF out as a letter to the supplier (#2080)
Brad Barbin3842ea5dbbd6
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 5164903825..c947e2f423 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -4264,3 +4264,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Rule:** A create input leaves the new row's `id` optional when the table has a default (`mcp-create-inputs.test.ts` fails otherwise). A database refusal the caller can fix is reported as itself: `defineServiceFn` maps an `internal` error whose cause is one (`databaseRefusal`), so don't swallow the cause. A yes/no field is a real boolean that also parses the form's `"true"` / `"false"` (`booleanField`, `shared.models.ts`), so the API publishes `boolean`. A rich-text (JSON) column takes `optionalTiptapDoc` / `requiredTiptapDoc`, never `z.string()` or `z.unknown()`: a raw string is stored as a JSON scalar the editor cannot read. A JSON value a form posts as text takes `jsonInput(schema)`. Never `z.preprocess` / `z.coerce` / `z.any()` bare in an operation's input: the manifest publishes those as "anything".**Applies to:** every `defineServiceFn` in `apps/erp/app/modules/*/*.server.ts`, and any validator reused as an operation's input.++## Code outside an Inngest step runs again after every step++**Context:** Printing a Make kanban to a printer printed the Create card only, never Start or Complete (2026-10-28).++**Problem:** `print-job` wrote its `printJob` rows in the function body and called `step.sendEvent` per job. Each step makes Inngest invoke the function again from the top with the finished steps memoized, so the body ran again: its 30 s duplicate guard found the job the first pass had just written and threw `NonRetriableError`. Every document with more than one label (kanban cards, a receipt's serials) printed its first label only, and the run read as a "duplicate" rather than a failure.++**Rule:** In an Inngest function, every database read that decides something and every write goes inside a `step.run`; the body between steps must be safe to run again. Collect the events in the step and send them with one `step.sendEvent` after it.++**Applies to:** `packages/jobs/src/inngest/functions/**` — any function that writes outside `step.run` and then calls a `step.*` method.diff --git a/.claude/rules/kanban-system.md b/.claude/rules/kanban-system.mdindex 9fe1126864..28939c08a7 100644--- a/.claude/rules/kanban-system.md+++ b/.claude/rules/kanban-system.md@@ -136,9 +136,9 @@ Spec: `.ai/specs/2026-10-06-kanban-internal-replenishment-level.md`.- QR PNG route: `apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx`, 36px modules, **color-coded by action**: order=black `#000000`, start=emerald `#059669`, complete=blue `#2563eb`. (The old doc claiming "no color differentiation" was stale.)- Label PDF route: `apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx` — `?ids=` (comma-separated), one `.in()` read of the `kanbans` view scoped by `companyId`, rendered at the company's `kanbanLabelSize` (`?labelSize=` overrides). Thumbnails are fetched for the letter sheet only.- The card is defined once in `packages/documents/src/zpl/KanbanLabelZPL.tsx`: `KanbanLabelItem`, `kanbanLabelCode` (the card's one code for its `action`, with a caption: CREATE, START or COMPLETE), the text helpers, `canHoldKanbanLabel` (3" x 2" and up; 100 x 50 mm passes), `getKanbanLabelLayout` (inches: the code on the right, as large as the label allows (at most 45% of its width), caption under it; a text column on the left — each field cut to the column — the part name up to two lines (`wrapKanbanLabelText`), every other field one line (`fitKanbanLabelText`): name, item ID, bins, `QTY` and `MIN` on their own lines (`kanbanLabelQuantityLines`), supplier — with the kanban ID small at the bottom), `KANBAN_LABEL_COLORS` and `generateKanbanLabelZPL(item, size, baseUrl, action)`. Text is cut by an estimated glyph width (`fitKanbanLabelText`) and escaped with `^FH` (`zplFieldData`, `zpl/utils.ts`). Pinned by `kanbanLabelZPL.test.ts`.-- `KanbanLabelPDF` (`packages/documents/src/pdf/KanbanLabelPDF.tsx`, via `@carbon/documents/pdf`): takes the `action`; without `labelSize`, a letter page, **2×3 grid = 6 labels/page** — the action-colored code (like the PNG route) with the item thumbnail beside it, name, item readable id, storage unit/location, `QTY: {quantity} {uom}` (plus `MIN: {replenishmentLevel}` — no unit, because `uom` is the purchase unit and the level is in stock units), and a bottom row with the `kanbanId` (bold, left) and supplier (right). With a `labelSize`, one card per page laid out by `getKanbanLabelLayout`, so the PDF and the ZPL print alike; the PDF colors the code and caption by action (black Create, green Start, blue Complete), and the ZPL (black only) relies on the caption.+- `KanbanLabelPDF` (`packages/documents/src/pdf/KanbanLabelPDF.tsx`, via `@carbon/documents/pdf`): takes the `action`; without `labelSize`, a letter page, **2×3 grid = 6 labels/page** — the action-colored code (like the PNG route) with the item thumbnail beside it, name, item readable id, storage unit/location, `QTY: {quantity} {uom}` (plus `MIN: {replenishmentLevel}` — no unit, because `uom` is the purchase unit and the level is in stock units), and a bottom row with the `kanbanId` (bold, left) and supplier (right). The code carries its caption (CREATE / START / COMPLETE, in the action's color) on the letter sheet too, since one sheet can hold all three cards of a kanban. With a `labelSize`, one card per page laid out by `getKanbanLabelLayout`, so the PDF and the ZPL print alike; the PDF colors the code and caption by action (black Create, green Start, blue Complete), and the ZPL (black only) relies on the caption.- Print job: `resolveKanbanData` (`print-job/resolvers.ts`) returns one `KanbanCardItem` per action — `order`, `start`, `complete` for a Make kanban, `order` only for Buy and Transfer — so each card is its own `printJob` (description ends Create / Start / Complete) and `renderKanbanCard` (`print-job/renderers.tsx`) renders the item's `action`; `kanbanUrl` (BinderyPress data) is that action's scan URL from `kanbanLabelCode`. A printer whose media size holds a card prints one at that size — ZPL, or a one-card PDF. A ZPL printer with smaller media fails the job; a PDF printer with smaller or no media prints the company's `kanbanLabelSize`. `resolveKanbanData` uses the `kanbanId` as the job's readable id.-- `KanbansTable` renders Create/Start/Complete per `kanbanOutput`: `label`→PDF links (one card per action), `qrcode`→hover-card iframes (one open at a time: `KanbanQrCodeHoverCard` reads a table-level `OpenQrCodeContext`), `url`→copyable API links; Start/Complete show for Make only. Bulk **Print Labels** (and the row menu's **Print Label**) prints each kanban's cards (all three for Make) when it goes to a printer, the Create cards when it falls back to the PDF: it opens a printer picker, pre-selecting the location's `kanban` printer context (Settings → Printing → Kanbans row, falling back to the location default), and POSTs one `Kanban` print job per kanban to `path.to.manualPrint` when the company has printer routes (the storage-unit list's pattern), else opens the PDF.+- `KanbansTable` renders Create/Start/Complete per `kanbanOutput`: `label`→PDF links (one card per action), `qrcode`→hover-card iframes (one open at a time: `KanbanQrCodeHoverCard` reads a table-level `OpenQrCodeContext`), `url`→copyable API links; Start/Complete show for Make only. Bulk **Print Labels** (and the row menu's **Print Label**) prints each kanban's cards (all three for Make) whether it goes to a printer or falls back to the PDF (`kanbanLabelsPdf(ids, "all")`: the route's `all` action expands each Make kanban into Create, Start and Complete cards, each `KanbanLabelPDF` card carrying its own `action`): it opens a printer picker, pre-selecting the location's `kanban` printer context (Settings → Printing → Kanbans row, falling back to the location default), and POSTs one `Kanban` print job per kanban to `path.to.manualPrint` when the company has printer routes (the storage-unit list's pattern), else opens the PDF.- `createKanban` auto-prints the new kanban's cards through `autoPrint` (`inventory.service.ts`, context `kanban`) when the context's Auto-print is on — like a posted receipt or shipment. Update does not print.## Gotchasdiff --git a/.claude/rules/printing-system.md b/.claude/rules/printing-system.mdindex 3ec9e78ba3..d672fcd6eb 100644--- a/.claude/rules/printing-system.md+++ b/.claude/rules/printing-system.md@@ -41,16 +41,23 @@ a ProxyBox HTTP endpoint. There is no Trigger.dev here.workCenterId?, printerRouteId? }` (`packages/lib/src/events.ts`).2. **Generate** — `print-job/index.tsx` (`packages/jobs/src/inngest/functions/tasks/print-job/`,`retries: 0`):+ - **One step, `create-print-jobs`,** holds the dedupe, the printer config and every job write, so+ they run once. A step makes Inngest run the function again from the top; when the job writes+ sat outside a step, each `deliver-<jobId>` send re-ran the dedupe, which found the job just+ written and threw — only a document's FIRST label ever printed (a Make kanban's Create card,+ never Start or Complete).- **30s auto-dedupe:** if an `origin="auto"` `printJob` for the same `sourceDocumentId`+`companyId`- was created in the last 30s, throws `NonRetriableError`.+ was created in the last 30s, throws `NonRetriableError`. Every job the task writes is+ `origin="auto"`, the manual route's included.- **Resolve printer config once:** explicit `printerRouteId` → fetch that route; else if `locationId`,`getCachedPrinterConfig(client, companyId, locationId, getPrinterContextForSource(sourceDocument,workCenterId), workCenterId)`. Falls back to `docType.defaultFormat` and media size `"label2x1"`when no config.- For each doc-type-for-source: resolve items (`resolvers.ts`: `resolveTrackedEntityData` /`resolveKanbanData` / `resolveStorageUnitData`), then per item create a `printJob` (`generating`),- render (`renderers.tsx`), update content (→ `queued`), and if a `printerUrl` exists send a- `carbon/print-job-deliver` event (else mark `completed`).+ render (`renderers.tsx`), update content (→ `queued`), and if a `printerUrl` exists collect it+ for delivery (else mark `completed`). After the step, one `step.sendEvent("deliver", …)` sends a+ `carbon/print-job-deliver` event per collected job.3. **Deliver** — `print-job-deliver.ts` (event `carbon/print-job-deliver`, `retries: 0`): loads the job,sets `printing`, looks up the route `apiKey` by `printerUrl`, `sendToProxyBox` (PDF content isbase64 → Buffer), then `completed`. Timeouts throw `NonRetriableError` (content may already havediff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsxindex e51e2b413d..ead6789f97 100644--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx@@ -633,8 +633,8 @@ const KanbansTable = memo(/* Printing kanban cards (one row, or the selection): to a configuredprinter, the location's Kanbans printer first (a Zebra prints at its ownmedia size), one card per action, so a Make kanban prints Create, Start- and Complete. With no printer, the Create cards' PDF at the company's- Label Size. */+ and Complete. With no printer, the same cards as one PDF at the+ company's Label Size. */const { printerRoutes, resolvePrinterRoute } = usePrinting();const printerModal = useDisclosure();const defaultPrinter = resolvePrinterRoute(locationId, "kanban");@@ -652,7 +652,7 @@ const KanbansTable = memo();printerModal.onOpen();} else {- window.open(path.to.file.kanbanLabelsPdf(ids, "order"), "_blank");+ window.open(path.to.file.kanbanLabelsPdf(ids, "all"), "_blank");}},[printerRoutes, defaultPrinter?.id, printerModal]diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.mdindex 30ab2c6f45..9092a40aae 100644--- a/apps/erp/app/modules/purchasing/AGENTS.md+++ b/apps/erp/app/modules/purchasing/AGENTS.md@@ -89,7 +89,7 @@ Each is a `defineServiceFn` const in `purchasing.server.ts`. The route calls it- **Line dates** — every PO line keeps its own `requiredDate` (requested), `promisedDate` and `receivedDate` (delivery; receipt posting also sets it), mapped to the order's `receiptRequestedDate` / `receiptPromisedDate` / `deliveryDate` by `purchaseOrderLineDateOfOrderDate` (`purchasing.models.ts`). A new line starts on the order's requested and promised dates (`upsertPurchaseOrderLine` fills them when absent; both line forms default them). A changed order date is copied by `cascadePurchaseOrderDateToLines` (`purchasing.service.ts`) to every line whose date is empty or still the order's previous one, in the transaction that writes the delivery row; a line given its own date keeps it, and received-complete lines keep their requested and promised dates. An order whose date is not changing moves no line, so saving the Shipping card fills no empty line. The delivery date is when the goods arrived (receipt posting sets the order's), so it reaches only lines with something received (`quantityReceived > 0`). Receipt posting also overwrites a line's `receivedDate` with the posting day on every receipt, so a hand-corrected delivery date lasts until the line's next receipt. Pinned by `apps/erp/test/database/purchase-order-line-dates.test.ts`. A saved line's dates save one at a time (`updatePurchaseOrderLineDate`), outside the line form's submit: the requested date is fixed once the order is released, the promised date once the line is received complete or the order fully received, and the delivery date stays correctable. The line page edits them in the form's Dates section (`PurchaseOrderLineDateFields`); the order summary edits each line's promised date in place (`PurchaseOrderLinePromisedDate`). The line details route drops the date fields from its update, because `updatePurchaseOrderLineRestatingCompletion` sanitizes a missing field to null.- Purchase orders — `updatePurchaseOrder` (the details form: header columns only, never `status`, refused on a finalized order), `updatePurchaseOrders` (one field of the properties panel, refused on a released order except `deliveryDate`, and `receiptPromisedDate` until the order is fully received: `isPurchaseOrderPromisedDateEditable`. A new requested, promised or delivery date also moves the order's lines — see Line dates), `updatePurchaseOrderDelivery` (the Shipping card, `$orderId.delivery.tsx`; refused on a released order; cascades its three dates the same way), `updatePurchaseOrderLineDate` (one date of one line, `$orderId.$lineId.date.tsx`; `purchaseOrderLineDateRefusal`), `deletePurchaseOrders` (Draft / Planned, or Needs Approval by its requester — `purchaseOrderDeleteRefusal` in `purchasing.models.ts`; cancels the pending approvals in the delete's transaction), `finalizePurchaseOrderAndNotify` (party contact and supplier approval rules, the approval rule or the planning bypass, then prices, the PDF document and the email; the email attaches the new PDF, the supplier interaction's files without the PDFs stored for its orders (`withoutStoredPurchaseOrderPdfs`: every order converted from one supplier quote shares the folder) and the default attachments, and the PO page's Finalize list shows the same files; an order that needs approval is never released: `submitPurchaseOrderForApproval` sets Needs Approval and opens the request in one transaction, and the approvers are notified after it commits), `decidePurchaseOrderApproval`, `reopenPurchaseOrder` (Draft / Planned, optionally as a revision; `delete` permission from a released status), `closePurchaseOrderAndApprovals`. The status route takes only Draft, Planned and Closed.- Return orders — `updateReturnOrders`, `confirmReturnOrder` (stores the PDF; a failed PDF is a `warning`), `cancelReturnOrder`, `reopenReturnOrder`, `addReturnOrderLine` (Draft only), `updateReturnOrderLine` (post-confirm locks: `lockedReturnLineField`).-- RFQs — `createPurchasingRfq`, `updatePurchasingRfqs`, `cancelPurchasingRfq` (cancels the linked supplier quotes), `finalizePurchasingRfqAndNotify` (`service.finalizePurchasingRfq`, ported from `finalize-purchasing-rfq`, then the emails: the RFQ and line documents, and each line item's original CAD file from `getItemModelFiles` — attached in line order while the total stays under `PO_EMAIL_ATTACHMENT_LIMIT_MB` (`splitRfqModelAttachments`), the rest signed for 7 days and listed as links in the body; a model with no known size goes as a link, one whose attachment cannot be signed falls back to a link, and one with no link either is named in the body). The RFQ PDF (`file+/purchasing-rfq+/$id[.]pdf.tsx`, template type `purchasingRfq`, the header's PDF action at any status) is for suppliers who quote on paper: one row per quantity break with the line's purchase unit, and blank Unit Price, Lead Time and Total cells. Both share pages (`share+/purchasing-rfq.$id.tsx`, `share+/supplier-quote.$id.tsx`) show the line's purchase unit (else inventory unit) beside each quantity.+- RFQs — `createPurchasingRfq`, `updatePurchasingRfqs`, `cancelPurchasingRfq` (cancels the linked supplier quotes), `finalizePurchasingRfqAndNotify` (`service.finalizePurchasingRfq`, ported from `finalize-purchasing-rfq`, then the emails: the RFQ and line documents, and each line item's original CAD file from `getItemModelFiles` — attached in line order while the total stays under `PO_EMAIL_ATTACHMENT_LIMIT_MB` (`splitRfqModelAttachments`), the rest signed for 7 days and listed as links in the body; a model with no known size goes as a link, one whose attachment cannot be signed falls back to a link, and one with no link either is named in the body). The RFQ PDF (`file+/purchasing-rfq+/$id[.]pdf.tsx`, template type `purchasingRfq`, the header's PDF action at any status) is a letter for suppliers who quote in their own format: letterhead, date, reference and due date, what the quotation should include, the delivery address and the buyer to send it to (the RFQ's assignee, else its author), a ruled table of each line's quantity breaks in its purchase unit, then the notes and a sign-off (the notes block) and the terms on their own page. It has no price cells; the share page is where a supplier enters prices. Both share pages (`share+/purchasing-rfq.$id.tsx`, `share+/supplier-quote.$id.tsx`) show the line's purchase unit (else inventory unit) beside each quantity.- Supplier quotes — `updateSupplierQuotes`, `finalizeSupplierQuoteWithLink`, `sendSupplierQuoteToSupplier`; `submitDigitalSupplierQuote` / `declineDigitalSupplierQuote` / `updateDigitalSupplierQuoteLineNotes` / `recordSupplierQuoteLinkVisit` (system only, not published: the supplier's share link runs them through `shareLinkContext`, `~/modules/service-context.server`; submit refuses a line that is not the quote's).- Suppliers — `requestSupplierApproval`, `deactivateSupplier`, `decideSupplierApproval`.- Planning — `orderPlannedPurchases` (suggestions to Planned POs, one per supplier per week), `updatePlanningPurchaseOrderLine`, `applyPlanningActions`, `dismissPurchasingPlanningActions`, `reopenPurchasingPlanningActions`, `assignPurchasingPlanningActions`. The route answers `{ success, message }`, the shape `usePlanningActions` (production module, shared with production planning) reads.diff --git a/apps/erp/app/modules/purchasing/purchasing.pdf.tsx b/apps/erp/app/modules/purchasing/purchasing.pdf.tsxindex 3f582565a5..1cb4d3033a 100644--- a/apps/erp/app/modules/purchasing/purchasing.pdf.tsx+++ b/apps/erp/app/modules/purchasing/purchasing.pdf.tsx@@ -34,6 +34,7 @@ import {resolveSections} from "~/modules/settings/settings.service";import { getBase64ImageFromSupabase } from "~/modules/shared/shared.service";+import { getUser } from "~/modules/users/users.service";import {getPurchaseOrder,getPurchaseOrderApproval,@@ -483,10 +484,14 @@ export async function renderPurchasingRfqPdf("purchasingRfq");- const [location, thumbnailRows] = await Promise.all([+ // The buyer the supplier answers: the RFQ's assignee, else its author.+ const buyerId = purchasingRfq.data.assignee ?? purchasingRfq.data.createdBy;++ const [location, buyer, thumbnailRows] = await Promise.all([purchasingRfq.data.locationId? getLocation(client, purchasingRfq.data.locationId): null,+ buyerId ? getUser(client, buyerId) : null,showThumbnails? Promise.all((purchasingRfqLines.data ?? []).map((line) =>@@ -537,6 +542,11 @@ export async function renderPurchasingRfqPdf(purchasingRfq={purchasingRfq.data}purchasingRfqLines={purchasingRfqLines.data ?? []}shipToAddress={shipToAddress}+ contact={+ buyer?.data+ ? { name: buyer.data.fullName, email: buyer.data.email }+ : null+ }thumbnails={thumbnails}terms={(terms?.data?.purchasingTerms ?? {}) as JSONContent}template={templateConfig}diff --git a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsxindex b4844739a2..5d9ef765ee 100644--- a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx+++ b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { KanbanLabelPDF } from "@carbon/documents/pdf";+import type { KanbanLabelAction } from "@carbon/documents/zpl";import { getLogger } from "@carbon/logger";import { getRequestOrigin, labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";@@ -17,7 +18,9 @@ import { getBase64ImageFromSupabase } from "~/modules/shared/shared.service";const logger = getLogger("erp", "kanban-labels-pdf");-const ACTIONS = ["order", "start", "complete"] as const;+// `all` prints every card a kanban has: Create, Start and Complete for Make,+// Create only for Buy and Transfer.+const ACTIONS = ["order", "start", "complete", "all"] as const;export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -97,28 +100,32 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const labels = rows.map((kanban) => ({- id: kanban.id!,- kanbanId: kanban.kanbanId,- itemName: kanban.name || "",- itemReadableId: kanban.readableIdWithRevision || kanban.itemId || "",- locationName: kanban.locationName || "",- storageUnitName: kanban.storageUnitName,- fromStorageUnitName: kanban.fromStorageUnitName,- supplierName: kanban.supplierName,- quantity: kanban.quantity ?? 0,- replenishmentLevel: kanban.replenishmentLevel,- unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,- thumbnail: thumbnails[kanban.id!] ?? null- }));+ const labels = rows.flatMap((kanban) => {+ const actions: KanbanLabelAction[] =+ action !== "all"+ ? [action]+ : kanban.replenishmentSystem === "Make"+ ? ["order", "start", "complete"]+ : ["order"];+ return actions.map((cardAction) => ({+ action: cardAction,+ id: kanban.id!,+ kanbanId: kanban.kanbanId,+ itemName: kanban.name || "",+ itemReadableId: kanban.readableIdWithRevision || kanban.itemId || "",+ locationName: kanban.locationName || "",+ storageUnitName: kanban.storageUnitName,+ fromStorageUnitName: kanban.fromStorageUnitName,+ supplierName: kanban.supplierName,+ quantity: kanban.quantity ?? 0,+ replenishmentLevel: kanban.replenishmentLevel,+ unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,+ thumbnail: thumbnails[kanban.id!] ?? null+ }));+ });const stream = await renderToStream(- <KanbanLabelPDF- baseUrl={baseUrl}- labels={labels}- action={action}- labelSize={labelSize}- />+ <KanbanLabelPDF baseUrl={baseUrl} labels={labels} labelSize={labelSize} />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 11208bfbbb..1184e35270 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1154,7 +1154,7 @@ export const path = {generatePath(`${file}/job/${jobId}/traveler.pdf`),kanbanLabelsPdf: (ids: string | string[],- action: "order" | "start" | "complete"+ action: "order" | "start" | "complete" | "all") => {const idString = Array.isArray(ids) ? ids.join(",") : ids;return generatePath(diff --git a/packages/documents/src/pdf/KanbanLabelPDF.tsx b/packages/documents/src/pdf/KanbanLabelPDF.tsxindex 539dea0c9f..5036367f4a 100644--- a/packages/documents/src/pdf/KanbanLabelPDF.tsx+++ b/packages/documents/src/pdf/KanbanLabelPDF.tsx@@ -19,9 +19,13 @@ import {} from "../zpl/KanbanLabelZPL";import Footer from "./components/Footer";+/** A card, with its own action when one PDF mixes Create, Start and Complete. */+type KanbanLabelCard = KanbanLabelItem & { action?: KanbanLabelAction };+interface KanbanLabelPDFProps {baseUrl: string;- labels: KanbanLabelItem[];+ labels: KanbanLabelCard[];+ /** The action of every card that names none. */action?: KanbanLabelAction;/** A thermal label: one card per page at its size. Omitted = a letter* sheet of six. */@@ -84,21 +88,6 @@ const KanbanLabelPDF = ({// QR code size - make it prominentconst qrCodeSize = Math.min(labelHeight * 0.35, labelWidth * 0.4);- // QR code color based on action type- const getQRColor = () => {- if (action === "start") return "059669"; // emerald-600- if (action === "complete") return "2563eb"; // blue-600- return "000000"; // black for order- };-- // Get appropriate API endpoint based on action- const getKanbanUrl = (labelId: string) => {- if (action === "start") return `${baseUrl}/api/kanban/start/${labelId}`;- if (action === "complete")- return `${baseUrl}/api/kanban/complete/${labelId}`;- return `${baseUrl}/api/kanban/${labelId}`;- };-return (<Document>{Array.from({ length: pageCount }).map((_, pageIndex) => (@@ -129,6 +118,10 @@ const KanbanLabelPDF = ({/>);+ const cardAction = label.action ?? action;+ const code = kanbanLabelCode(label, baseUrl, cardAction);+ const color = KANBAN_LABEL_COLORS[cardAction];+return (<Viewkey={`label-${itemIndex}`}@@ -146,19 +139,31 @@ const KanbanLabelPDF = ({"flex flex-row items-center justify-center mb-3")}>- {/* QR Code */}- <Image- src={generateQRCode(- getKanbanUrl(label.id),- qrCodeSize / 72,- getQRColor()- )}- style={{- width: qrCodeSize,- height: qrCodeSize,- objectFit: "contain"- }}- />+ {/* QR Code, its caption under it: one sheet can+ hold a kanban's Create, Start and Complete cards */}+ <View style={tw("flex flex-col items-center")}>+ <Image+ src={generateQRCode(+ code.url,+ qrCodeSize / 72,+ color+ )}+ style={{+ width: qrCodeSize,+ height: qrCodeSize,+ objectFit: "contain"+ }}+ />+ <Text+ style={{+ fontSize: "10pt",+ fontFamily: "Helvetica-Bold",+ color: `#${color}`+ }}+ >+ {code.caption}+ </Text>+ </View>{/* Thumbnail if available */}{label.thumbnail ? (@@ -307,12 +312,13 @@ const ThermalKanbanLabels = ({labelSize}: Required<KanbanLabelPDFProps>) => {const pt = (inches: number) => inches * 72;- const color = `#${KANBAN_LABEL_COLORS[action]}`;return (<Document>- {labels.map((label) => {- const code = kanbanLabelCode(label, baseUrl, action);+ {labels.map((label, cardIndex) => {+ const cardAction = label.action ?? action;+ const code = kanbanLabelCode(label, baseUrl, cardAction);+ const color = `#${KANBAN_LABEL_COLORS[cardAction]}`;const column = getKanbanLabelLayout(labelSize.width, labelSize.height);const name = wrapKanbanLabelText(label.itemName,@@ -352,7 +358,7 @@ const ThermalKanbanLabels = ({return (<Page- key={label.id}+ key={`${label.id}-${cardAction}-${cardIndex}`}size={[pt(labelSize.width), pt(labelSize.height)]}>{name.map((nameLine, index) =>@@ -402,7 +408,7 @@ const ThermalKanbanLabels = ({src={generateQRCode(code.url,layout.codeSize,- KANBAN_LABEL_COLORS[action]+ KANBAN_LABEL_COLORS[cardAction])}style={{position: "absolute",diff --git a/packages/documents/src/pdf/PurchasingRfqPDF.tsx b/packages/documents/src/pdf/PurchasingRfqPDF.tsxindex 2c4cd1f923..9415ec0eb6 100644--- a/packages/documents/src/pdf/PurchasingRfqPDF.tsx+++ b/packages/documents/src/pdf/PurchasingRfqPDF.tsx@@ -4,7 +4,7 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import { Fragment } from "react";+import { View } from "@react-pdf/renderer";import type { DocumentTemplate, ResolvedSection } from "../template";import {DEFAULT_HEADER_OPTIONS,@@ -15,6 +15,7 @@ import type { PDF } from "../types";import { resolveRegistrationLine } from "../utils/shared";import type {PurchasingRfqAddress,+ PurchasingRfqContact,PurchasingRfqData,PurchasingRfqPdfLine} from "./blocks/purchasingRfq";@@ -22,6 +23,7 @@ import {buildPurchasingRfqVars,purchasingRfqBlockRegistry} from "./blocks/purchasingRfq";+import { hasContent, resolveTerms } from "./blocks/resolveTerms";import { Template } from "./components";interface PurchasingRfqPDFProps extends PDF {@@ -29,6 +31,8 @@ interface PurchasingRfqPDFProps extends PDF {purchasingRfqLines: PurchasingRfqPdfLine[];/** The receiving location the supplier quotes delivery to. */shipToAddress?: PurchasingRfqAddress | null;+ /** The buyer the supplier answers; signs the letter. */+ contact?: PurchasingRfqContact | null;/** Base64 thumbnails keyed by line id. */thumbnails?: Record<string, string | null>;companySettings?:@@ -42,8 +46,9 @@ interface PurchasingRfqPDFProps extends PDF {}/**- * A purchasing RFQ on paper: the lines and quantity breaks the supplier- * prices, with blank Unit Price, Lead Time and Total cells to fill in.+ * A purchasing RFQ as a letter to the supplier: letterhead, the request, the+ * items and quantity breaks, a sign-off, then the terms. The supplier answers+ * with a quotation in their own format; the share page is the structured path.*/const PurchasingRfqPDF = ({company,@@ -52,6 +57,7 @@ const PurchasingRfqPDF = ({purchasingRfq,purchasingRfqLines,shipToAddress,+ contact,thumbnails,terms,locale,@@ -88,6 +94,7 @@ const PurchasingRfqPDF = ({purchasingRfq,purchasingRfqLines,shipToAddress,+ contact,thumbnails,terms,theme,@@ -109,6 +116,12 @@ const PurchasingRfqPDF = ({? interpolateContent(footerSection, vars): undefined;+ // Terms start on their own page, after the sign-off.+ const termsBlock = blocks.find((block) => block.type === "terms");+ const hasTerms =+ termsBlock?.type === "terms" &&+ hasContent(resolveTerms(termsBlock, terms, vars));+const showHeader = headerSectionId !== null;const showFooter = footerSectionId !== null;const visibleBlocks = blocks.filter(@@ -134,10 +147,22 @@ const PurchasingRfqPDF = ({headerContent={headerContent}footerContent={footerContent}>+ {/* Letter margins: the page shell's are sized for dense documents.+ The fixed spacer holds the top margin on every page; each block gets+ its own side margins so a block's `break` still starts a page. */}+ <View fixed style={{ height: 18 }} />{visibleBlocks.map((block) => {const render = purchasingRfqBlockRegistry[block.type];if (!render) return null;- return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ return (+ <View+ key={block.id}+ break={block.type === "terms" && hasTerms}+ style={{ paddingHorizontal: 30 }}+ >+ {render({ block, data })}+ </View>+ );})}</Template>);diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/purchasingRfq/HeaderBlock.tsxindex bfa1856032..03ea981707 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/HeaderBlock.tsx+++ b/packages/documents/src/pdf/blocks/purchasingRfq/HeaderBlock.tsx@@ -2,17 +2,80 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { Header } from "../../components";+import { formatCityStatePostalCode } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { DEFAULT_HEADER_OPTIONS } from "../../../template";+import { LogoImage } from "../../components";+import { useTw } from "../tw";import type { PurchasingRfqData } from "./types";+/**+ * Letterhead: the logo on the left, the company's address and contact details+ * on the right, a rule under both, then the title. The RFQ number and dates+ * sit in the letter below (PartiesBlock), as they would in a typed letter.+ */export function HeaderBlock({ data }: { data: PurchasingRfqData }) {+ const tw = useTw();+ const { company } = data;+ const opts = { ...DEFAULT_HEADER_OPTIONS, ...data.headerOptions };+ const logoSrc =+ opts.logoVariant === "icon"+ ? (company.logoLightIcon ?? company.logoLight)+ : (company.logoLight ?? company.logoLightIcon);+ const showLogo = opts.showLogo && Boolean(logoSrc);+ const cityLine =+ company.city || company.stateProvince || company.postalCode+ ? formatCityStatePostalCode(+ company.city,+ company.stateProvince,+ company.postalCode+ )+ : null;+ const contactLines = [company.phone, company.email, company.website].filter(+ Boolean+ );+return (- <Header- company={data.company}- title="Request for Quote"- documentId={data.purchasingRfq?.rfqId}- locale={data.locale}- options={data.headerOptions}- />+ <View style={tw("mb-6")}>+ <View style={tw("flex flex-row justify-between items-end pb-3")}>+ <View style={tw("shrink pr-6")}>+ {showLogo ? (+ <LogoImage+ src={logoSrc!}+ height={opts.logoHeight}+ crop={opts.logoCrop}+ />+ ) : (+ <Text style={tw("text-[18px] font-bold text-gray-800")}>+ {company.name}+ </Text>+ )}+ </View>+ {opts.showCompanyDetails ? (+ <View style={tw("flex flex-col items-end text-[8px] text-gray-600")}>+ {showLogo && company.name ? (+ <Text style={tw("font-bold text-gray-800")}>{company.name}</Text>+ ) : null}+ {company.addressLine1 ? <Text>{company.addressLine1}</Text> : null}+ {company.addressLine2 ? <Text>{company.addressLine2}</Text> : null}+ {cityLine ? <Text>{cityLine}</Text> : null}+ {contactLines.map((line) => (+ <Text key={line}>{line}</Text>+ ))}+ </View>+ ) : null}+ </View>+ <View style={tw("h-[1px] bg-gray-400")} />+ {opts.showDocumentTitle ? (+ <Text+ style={[+ tw("text-[16px] font-bold mt-5"),+ { color: data.theme.accent }+ ]}+ >+ Request for Quote+ </Text>+ ) : null}+ </View>);}diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/purchasingRfq/LineItemsBlock.tsxindex 7bff686e1b..b4251007be 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/LineItemsBlock.tsx+++ b/packages/documents/src/pdf/blocks/purchasingRfq/LineItemsBlock.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { JSONContent } from "@carbon/react";-import { distinctItemText } from "@carbon/utils";+import { distinctItemText, formatQuantity } from "@carbon/utils";import { Image, Text, View } from "@react-pdf/renderer";import {DEFAULT_LINE_ITEMS_OPTIONS,@@ -21,6 +21,15 @@ function quantitiesOf(line: PurchasingRfqPdfLine): number[] {: [1];}+const RULE = "#9ca3af";+const HEADER_FILL = "#f3f4f6";+const ZEBRA_FILL = "#f9fafb";++/**+ * The items to quote, as a plain ruled table: the part, then each quantity+ * break on its own line with its unit. No price columns — the supplier quotes+ * in their own format.+ */export function LineItemsBlock({block,data@@ -29,107 +38,94 @@ export function LineItemsBlock({data: PurchasingRfqData;}) {const tw = useTw();- const { purchasingRfqLines, thumbnails, theme } = data;+ const { purchasingRfqLines, thumbnails, locale } = data;const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };const overflow = itemTextOverflowStyle(opts);- // The supplier writes the price and lead time in by hand.- const blank = tw("border-b border-gray-400 h-[12px] mx-2");++ const cell = { borderRightWidth: 0.5, borderColor: RULE };+ // Each row carries its own rules: a border on the table's wrapper is drawn+ // to the bottom of the page when the table breaks across pages.+ const rowRules = {+ borderLeftWidth: 0.5,+ borderRightWidth: 0.5,+ borderBottomWidth: 0.5,+ borderColor: RULE+ };+ const columns = {+ index: [tw("w-[7%] px-2 py-1.5 text-center"), cell],+ item: [tw("w-[59%] px-2 py-1.5"), cell],+ quantity: [tw("w-[20%] px-2 py-1.5 text-right"), cell],+ unit: tw("w-[14%] px-2 py-1.5")+ };return (- <View style={tw("mb-4")}>+ <View style={tw("mb-5 text-[9px] text-gray-800")}><Viewfixedstyle={[- tw("flex flex-row py-2 px-3 text-[9px] font-bold items-center"),- { backgroundColor: theme.accent, color: theme.accentForeground }+ tw("flex flex-row font-bold"),+ { backgroundColor: HEADER_FILL, borderTopWidth: 0.5 },+ rowRules]}>- <Text style={tw("w-[5%] text-center")}>#</Text>- <Text style={tw("w-[35%]")}>Item</Text>- <Text style={tw("w-[12%] text-center")}>Qty</Text>- <Text style={tw("w-[8%] text-center")}>UOM</Text>- <Text style={tw("w-[14%] text-center")}>Unit Price</Text>- <Text style={tw("w-[12%] text-center")}>Lead Time</Text>- <Text style={tw("w-[14%] text-center")}>Total</Text>+ <Text style={columns.index}>#</Text>+ <Text style={columns.item}>Item</Text>+ <Text style={columns.quantity}>Quantity</Text>+ <Text style={columns.unit}>Unit</Text></View>{purchasingRfqLines.map((line, index) => {const notes = (line.externalNotes ?? {}) as JSONContent;const thumbnail = line.id ? thumbnails?.[line.id] : null;const quantities = quantitiesOf(line);+ const unit =+ line.purchaseUnitOfMeasureCode ??+ line.inventoryUnitOfMeasureCode ??+ "";return (<Viewkey={line.id ?? index}wrap={false}style={[- tw("flex flex-col py-2 px-3 border-b border-gray-200 text-[9px]"),- {- backgroundColor:- opts.zebra && index % 2 === 1- ? "rgba(249, 250, 251, 0.6)"- : "transparent"- }+ tw("flex flex-row"),+ rowRules,+ opts.zebra && index % 2 === 1+ ? { backgroundColor: ZEBRA_FILL }+ : {}]}>- <View style={tw("flex flex-row")}>- <Text style={tw("w-[5%] text-center text-gray-600")}>- {index + 1}+ <Text style={columns.index}>{index + 1}</Text>+ <View style={columns.item}>+ <Text style={{ ...tw("font-bold"), ...overflow }}>+ {line.itemReadableId ?? ""}</Text>- <View style={tw("w-[35%] pr-2")}>- <Text style={{ ...tw("text-gray-800"), ...overflow }}>- {line.itemReadableId ?? ""}+ {distinctItemText(line.itemReadableId, line.description) ? (+ <Text style={{ ...tw("mt-0.5"), ...overflow }}>+ {line.description}</Text>- {distinctItemText(line.itemReadableId, line.description) ? (- <Text- style={{- ...tw("text-[8px] text-gray-600 mt-0.5"),- ...overflow- }}- >- {line.description}- </Text>- ) : null}- {opts.showThumbnails && thumbnail ? (- <View style={tw("mt-1 w-16")}>- <Image src={thumbnail} style={tw("w-full h-auto")} />- </View>- ) : null}- </View>- <View style={tw("w-[60%] flex flex-col")}>- {quantities.map((quantity, qtyIndex) => (- <View- key={qtyIndex}- style={tw(- `flex flex-row items-end ${qtyIndex > 0 ? "mt-2" : ""}`- )}- >- <Text style={tw("w-[20%] text-center text-gray-800")}>- {quantity}- </Text>- <Text style={tw("w-[13.33%] text-center text-gray-600")}>- {line.purchaseUnitOfMeasureCode ??- line.inventoryUnitOfMeasureCode ??- ""}- </Text>- <View style={tw("w-[23.33%]")}>- <View style={blank} />- </View>- <View style={tw("w-[20%]")}>- <View style={blank} />- </View>- <View style={tw("w-[23.33%]")}>- <View style={blank} />- </View>- </View>- ))}- </View>+ ) : null}+ {Object.keys(notes).length > 0 ? (+ <View style={tw("mt-1 text-gray-600")}>+ <Note content={notes} />+ </View>+ ) : null}+ {opts.showThumbnails && thumbnail ? (+ <View style={tw("mt-1 w-16")}>+ <Image src={thumbnail} style={tw("w-full h-auto")} />+ </View>+ ) : null}+ </View>+ <View style={columns.quantity}>+ {quantities.map((quantity, qtyIndex) => (+ <Text key={qtyIndex}>{formatQuantity(quantity, locale)}</Text>+ ))}+ </View>+ <View style={columns.unit}>+ {quantities.map((_, qtyIndex) => (+ <Text key={qtyIndex}>{unit}</Text>+ ))}</View>- {Object.keys(notes).length > 0 ? (- <View style={tw("mt-1 pl-[5%] text-[8px] text-gray-600")}>- <Note content={notes} />- </View>- ) : null}</View>);})}diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/NotesBlock.tsx b/packages/documents/src/pdf/blocks/purchasingRfq/NotesBlock.tsxindex c7ffd151dc..e829ac1074 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/NotesBlock.tsx+++ b/packages/documents/src/pdf/blocks/purchasingRfq/NotesBlock.tsx@@ -5,24 +5,38 @@import type { JSONContent } from "@carbon/react";import { Text, View } from "@react-pdf/renderer";import { Note } from "../../components";+import { hasContent } from "../resolveTerms";import { useTw } from "../tw";import type { PurchasingRfqData } from "./types";+/**+ * The close of the letter: the RFQ's notes to the supplier, then the+ * sign-off with the buyer's name under the company's.+ */export function NotesBlock({ data }: { data: PurchasingRfqData }) {const tw = useTw();+ const { company, contact } = data;const notes = (data.purchasingRfq?.notes ?? {}) as JSONContent;- if (Object.keys(notes).length === 0) return null;return (- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Notes- </Text>- <View style={tw("text-[9px] text-gray-800")}>+ <View wrap={false} style={tw("mb-4 text-[10px] text-gray-800")}>+ {hasContent(notes) ? (+ <View style={tw("mb-1")}>+ <Text style={tw("font-bold mb-1")}>Notes</Text><Note content={notes} /></View>- </View>+ ) : null}+ <Text style={tw("mb-4")}>+ Thank you. We look forward to receiving your quotation.+ </Text>+ <Text style={tw("mb-6")}>Sincerely,</Text>+ {contact?.name ? (+ <Text style={tw("font-bold")}>{contact.name}</Text>+ ) : null}+ {company?.name ? <Text>{company.name}</Text> : null}+ {contact?.email ? (+ <Text style={tw("text-gray-600")}>{contact.email}</Text>+ ) : null}</View>);}diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/purchasingRfq/PartiesBlock.tsxindex 90684aeba4..e7aba6c5fd 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/PartiesBlock.tsx+++ b/packages/documents/src/pdf/blocks/purchasingRfq/PartiesBlock.tsx@@ -2,10 +2,9 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { formatDate } from "@carbon/utils";+import { formatCityStatePostalCode, formatDate } from "@carbon/utils";import { Text, View } from "@react-pdf/renderer";import { getCountryName } from "../../../utils/shared";-import { AddressBlock } from "../../components";import { useTw } from "../tw";import type { PurchasingRfqAddress, PurchasingRfqData } from "./types";@@ -14,53 +13,105 @@ function resolveCountry(address?: PurchasingRfqAddress | null): string {return address.country ?? getCountryName(address.countryCode);}+/** What a supplier is expected to put in a quotation of their own format. */+const QUOTATION_CONTENTS = [+ "a unit price for each quantity, in the unit of measure shown",+ "your lead time from receipt of order",+ "how long your prices remain valid",+ "freight and delivery terms to the address below"+];++/**+ * The opening of the letter: date, reference and due date, the salutation,+ * what to quote and by when, then where to deliver and who to answer. The+ * supplier answers in their own format, so this asks rather than prescribes.+ */export function PartiesBlock({ data }: { data: PurchasingRfqData }) {const tw = useTw();- const { purchasingRfq, shipToAddress, locale } = data;+ const { company, contact, purchasingRfq, shipToAddress, locale } = data;+ const dueDate = purchasingRfq?.expirationDate+ ? formatDate(purchasingRfq.expirationDate, undefined, locale)+ : null;++ const facts = [+ {+ label: "Date",+ value: purchasingRfq?.rfqDate+ ? formatDate(purchasingRfq.rfqDate, undefined, locale)+ : null+ },+ { label: "Reference", value: purchasingRfq?.rfqId },+ { label: "Quotation due", value: dueDate }+ ].filter((fact) => fact.value);++ // One line, as an address is written on a letter: "Detroit, MI 48201".+ const cityLine =+ shipToAddress?.city ||+ shipToAddress?.stateProvince ||+ shipToAddress?.postalCode+ ? formatCityStatePostalCode(+ shipToAddress.city,+ shipToAddress.stateProvince,+ shipToAddress.postalCode+ )+ : null;++ const reference = purchasingRfq?.rfqId+ ? `, quoting reference ${purchasingRfq.rfqId}`+ : "";+ const deadline = dueDate ? ` by ${dueDate}` : "";return (- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- {/* LEFT — the receiving location the supplier quotes delivery to */}- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Ship To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={data.company?.name}- addressLine1={shipToAddress?.addressLine1}- addressLine2={shipToAddress?.addressLine2}- city={shipToAddress?.city}- stateProvince={shipToAddress?.stateProvince}- postalCode={shipToAddress?.postalCode}- country={resolveCountry(shipToAddress)}- />- </View>+ <View style={tw("mb-5 text-[10px] text-gray-800")}>+ {facts.length > 0 ? (+ <View style={tw("mb-5")}>+ {facts.map((fact) => (+ <View key={fact.label} style={tw("flex flex-row")}>+ <Text style={tw("w-[90px] text-gray-600")}>{fact.label}</Text>+ <Text>{fact.value}</Text>+ </View>+ ))}</View>+ ) : null}- {/* RIGHT — request details */}- <View style={tw("w-1/2 p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Request Details- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {purchasingRfq?.rfqId ? (- <Text>RFQ Number: {purchasingRfq.rfqId}</Text>- ) : null}- {purchasingRfq?.rfqDate ? (- <Text>- Date: {formatDate(purchasingRfq.rfqDate, undefined, locale)}- </Text>- ) : null}- {purchasingRfq?.expirationDate ? (- <Text>- Quote Due:{" "}- {formatDate(purchasingRfq.expirationDate, undefined, locale)}- </Text>- ) : null}+ <Text style={tw("mb-3")}>Dear Supplier,</Text>+ <Text style={tw("mb-3")}>+ We invite you to quote for the items listed below. Please send your+ quotation in your usual format{deadline}+ {reference}.+ </Text>+ <Text style={tw("mb-1")}>Your quotation should include:</Text>+ <View style={tw("mb-5 pl-3")}>+ {QUOTATION_CONTENTS.map((line) => (+ <View key={line} style={tw("flex flex-row")}>+ <Text style={tw("w-[12px]")}>•</Text>+ <Text style={tw("shrink")}>{line}</Text></View>+ ))}+ </View>++ <View style={tw("flex flex-row")}>+ <View style={tw("w-1/2 pr-4")}>+ <Text style={tw("font-bold mb-1")}>Deliver to</Text>+ {[+ company?.name,+ shipToAddress?.addressLine1,+ shipToAddress?.addressLine2,+ cityLine,+ resolveCountry(shipToAddress)+ ]+ .filter(Boolean)+ .map((line) => (+ <Text key={line}>{line}</Text>+ ))}</View>+ {contact?.name || contact?.email ? (+ <View style={tw("w-1/2")}>+ <Text style={tw("font-bold mb-1")}>Send your quotation to</Text>+ {contact.name ? <Text>{contact.name}</Text> : null}+ {contact.email ? <Text>{contact.email}</Text> : null}+ </View>+ ) : null}</View></View>);diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/TermsBlock.tsx b/packages/documents/src/pdf/blocks/purchasingRfq/TermsBlock.tsxindex 2436c5c541..8bce035fea 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/TermsBlock.tsx+++ b/packages/documents/src/pdf/blocks/purchasingRfq/TermsBlock.tsx@@ -22,17 +22,12 @@ export function TermsBlock({if (!hasContent(terms)) return null;return (- <View break>- <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>- <Text- style={[- tw("text-[14px] font-bold uppercase tracking-wide"),- { color: theme.accent }- ]}- >- Terms & Conditions- </Text>- </View>+ <View>+ <Text+ style={[tw("text-[16px] font-bold mt-2 mb-3"), { color: theme.accent }]}+ >+ Terms and Conditions+ </Text><Note content={terms!} /></View>);diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/index.ts b/packages/documents/src/pdf/blocks/purchasingRfq/index.tsindex 7caa3591e9..1d9ff61ed3 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/index.ts+++ b/packages/documents/src/pdf/blocks/purchasingRfq/index.ts@@ -6,6 +6,7 @@ export { purchasingRfqBlockRegistry } from "./registry";export type {BlockRenderer,PurchasingRfqAddress,+ PurchasingRfqContact,PurchasingRfqData,PurchasingRfqPdfLine} from "./types";diff --git a/packages/documents/src/pdf/blocks/purchasingRfq/types.ts b/packages/documents/src/pdf/blocks/purchasingRfq/types.tsindex 9fd6641cf1..c9501ec1c2 100644--- a/packages/documents/src/pdf/blocks/purchasingRfq/types.ts+++ b/packages/documents/src/pdf/blocks/purchasingRfq/types.ts@@ -30,6 +30,12 @@ export interface PurchasingRfqAddress {countryCode?: string | null;}+/** The buyer a supplier sends the quotation to; signs the letter. */+export interface PurchasingRfqContact {+ name?: string | null;+ email?: string | null;+}+/** Everything a purchasing RFQ block renderer might need. */export interface PurchasingRfqData {company: Company;@@ -39,6 +45,7 @@ export interface PurchasingRfqData {purchasingRfqLines: PurchasingRfqPdfLine[];/** The receiving location the supplier quotes delivery to. */shipToAddress?: PurchasingRfqAddress | null;+ contact?: PurchasingRfqContact | null;/** Base64 thumbnails keyed by line id. */thumbnails?: Record<string, string | null>;terms: JSONContent;diff --git a/packages/documents/src/pdf/purchasingRfq.samples.ts b/packages/documents/src/pdf/purchasingRfq.samples.tsindex 6de3b8cca4..2802a50b4b 100644--- a/packages/documents/src/pdf/purchasingRfq.samples.ts+++ b/packages/documents/src/pdf/purchasingRfq.samples.ts@@ -16,6 +16,9 @@ export const SAMPLE_PURCHASING_RFQ = {stateProvince: "MI",postalCode: "48201",countryCode: "US",+ phone: "(313) 555-0100",+ email: "[email protected]",+ website: "acme.example",baseCurrencyCode: "USD",logoLight: null,logoLightIcon: null,@@ -77,6 +80,7 @@ export const SAMPLE_PURCHASING_RFQ = {postalCode: "48201",countryCode: "US"},+ contact: { name: "Jane Doe", email: "[email protected]" },thumbnails: {},terms: {},locale: "en-US"diff --git a/packages/documents/src/template/defaults.ts b/packages/documents/src/template/defaults.tsindex 6d39f570a2..11641affcb 100644--- a/packages/documents/src/template/defaults.ts+++ b/packages/documents/src/template/defaults.ts@@ -377,15 +377,16 @@ function returnOrderBlocks(): DocumentBlock[] {}/**- * Layout for a purchasing RFQ: no summary block — nothing is priced yet, the- * supplier fills the line-items table in.+ * Layout for a purchasing RFQ, read as a letter: letterhead, the request,+ * the items, the sign-off (notes block), then the terms. No summary block —+ * nothing is priced; the supplier quotes in their own format.*/function rfqBlocks(): DocumentBlock[] {return [{ id: "header", type: "header", visible: true },{ id: "parties", type: "parties", visible: true },- { id: "notes", type: "notes", visible: true },{ id: "lineItems", type: "lineItems", visible: true },+ { id: "notes", type: "notes", visible: true },{ id: "terms", type: "terms", visible: true }];}diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx b/packages/jobs/src/inngest/functions/tasks/print-job/index.tsxindex f929b74df7..25f05361c7 100644--- a/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx+++ b/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx@@ -59,75 +59,101 @@ export const printJobFunction = inngest.createFunction(printerRouteId: explicitPrinterRouteId} = payload;- const thirtySecondsAgo = new Date(Date.now() - 30_000).toISOString();- const { count: recentJobCount } = await client- .from("printJob")- .select("id", { count: "exact", head: true })- .eq("sourceDocumentId", sourceDocumentId)- .eq("companyId", companyId)- .eq("origin", "auto")- .gte("createdAt", thirtySecondsAgo);-- if (recentJobCount && recentJobCount > 0) {- throw new NonRetriableError(- `Print jobs already exist for ${sourceDocument} ${sourceDocumentId}`- );- }+ // Everything that writes print jobs runs in ONE step. A step makes Inngest+ // run the function again from the top, so code outside a step runs again:+ // the duplicate guard then saw the job just written and threw, and a+ // kanban's Start and Complete cards (the second label onward of any+ // document) were never printed.+ const { printJobIds, deliverJobIds } = await step.run(+ "create-print-jobs",+ async () => {+ const thirtySecondsAgo = new Date(Date.now() - 30_000).toISOString();+ const { count: recentJobCount } = await client+ .from("printJob")+ .select("id", { count: "exact", head: true })+ .eq("sourceDocumentId", sourceDocumentId)+ .eq("companyId", companyId)+ .eq("origin", "auto")+ .gte("createdAt", thirtySecondsAgo);- let printerConfig: Awaited<ReturnType<typeof getCachedPrinterConfig>> =- null;-- if (explicitPrinterRouteId) {- const { data: route } = await client- .from("printerRoute")- .select("id, name, format, mediaSizeId, printerUrl, apiKey, templateId")- .eq("id", explicitPrinterRouteId)- .eq("companyId", companyId)- .single();- if (route) {- printerConfig = {- printerRouteId: route.id,- printerUrl: route.printerUrl,- format: route.format as "zpl" | "pdf",- mediaSizeId: route.mediaSizeId,- templateId: route.templateId,- autoPrint: true- };- }- } else if (locationId) {- printerConfig = await getCachedPrinterConfig(- client,- companyId,- locationId,- getPrinterContextForSource(sourceDocument, workCenterId),- workCenterId- );- }+ if (recentJobCount && recentJobCount > 0) {+ throw new NonRetriableError(+ `Print jobs already exist for ${sourceDocument} ${sourceDocumentId}`+ );+ }- const documentTypeIds = getDocumentTypesForSource(sourceDocument);- const allPrintJobIds: string[] = [];+ let printerConfig: Awaited<ReturnType<typeof getCachedPrinterConfig>> =+ null;- for (const documentTypeId of documentTypeIds) {- const docType = getDocumentType(documentTypeId);- if (!docType) continue;+ if (explicitPrinterRouteId) {+ const { data: route } = await client+ .from("printerRoute")+ .select(+ "id, name, format, mediaSizeId, printerUrl, apiKey, templateId"+ )+ .eq("id", explicitPrinterRouteId)+ .eq("companyId", companyId)+ .single();+ if (route) {+ printerConfig = {+ printerRouteId: route.id,+ printerUrl: route.printerUrl,+ format: route.format as "zpl" | "pdf",+ mediaSizeId: route.mediaSizeId,+ templateId: route.templateId,+ autoPrint: true+ };+ }+ } else if (locationId) {+ printerConfig = await getCachedPrinterConfig(+ client,+ companyId,+ locationId,+ getPrinterContextForSource(sourceDocument, workCenterId),+ workCenterId+ );+ }- const printJobIds = await processDocumentType(client, step, {- documentTypeId,- hasBuiltInRenderer: docType.builtInRenderer !== null,- sourceDocument,- sourceDocumentId,- companyId,- userId,- printerUrl: printerConfig?.printerUrl ?? "",- format: printerConfig?.format ?? docType.defaultFormat,- mediaSizeId: printerConfig?.mediaSizeId ?? DEFAULT_MEDIA_SIZE_ID,- templateId: printerConfig?.templateId ?? null- });+ const documentTypeIds = getDocumentTypesForSource(sourceDocument);+ const allPrintJobIds: string[] = [];+ const allDeliverJobIds: string[] = [];++ for (const documentTypeId of documentTypeIds) {+ const docType = getDocumentType(documentTypeId);+ if (!docType) continue;++ const created = await processDocumentType(client, {+ documentTypeId,+ hasBuiltInRenderer: docType.builtInRenderer !== null,+ sourceDocument,+ sourceDocumentId,+ companyId,+ userId,+ printerUrl: printerConfig?.printerUrl ?? "",+ format: printerConfig?.format ?? docType.defaultFormat,+ mediaSizeId: printerConfig?.mediaSizeId ?? DEFAULT_MEDIA_SIZE_ID,+ templateId: printerConfig?.templateId ?? null+ });- allPrintJobIds.push(...printJobIds);+ allPrintJobIds.push(...created.printJobIds);+ allDeliverJobIds.push(...created.deliverJobIds);+ }++ return { printJobIds: allPrintJobIds, deliverJobIds: allDeliverJobIds };+ }+ );++ if (deliverJobIds.length > 0) {+ await step.sendEvent(+ "deliver",+ deliverJobIds.map((printJobId) => ({+ name: "carbon/print-job-deliver" as const,+ data: { printJobId, companyId }+ }))+ );}- return { printJobIds: allPrintJobIds, count: allPrintJobIds.length };+ return { printJobIds, count: printJobIds.length };});@@ -209,14 +235,10 @@ function describeDocument(return parts.join(" — ");}+/** Writes and renders a print job per document; returns the jobs to send+ * to a printer (the caller delivers them, outside the step). */async function processDocumentType(client: SupabaseClient<Database>,- step: {- sendEvent: (- id: string,- payload: { name: string; data: Record<string, unknown> }- ) => Promise<unknown>;- },ctx: {documentTypeId: DocumentTypeId;hasBuiltInRenderer: boolean;@@ -229,7 +251,7 @@ async function processDocumentType(mediaSizeId: string;templateId: string | null;}-): Promise<string[]> {+): Promise<{ printJobIds: string[]; deliverJobIds: string[] }> {const {documentTypeId,hasBuiltInRenderer,@@ -250,9 +272,9 @@ async function processDocumentType(sourceDocumentId,companyId);- if (docs.length === 0) return [];-const printJobIds: string[] = [];+ const deliverJobIds: string[] = [];+ if (docs.length === 0) return { printJobIds, deliverJobIds };for (const doc of docs) {const job = await createPrintJob(client, {@@ -309,10 +331,7 @@ async function processDocumentType();if (printerUrl) {- await step.sendEvent(`deliver-${jobId}`, {- name: "carbon/print-job-deliver",- data: { printJobId: jobId, companyId }- });+ deliverJobIds.push(jobId);} else {await updatePrintJobStatus(client, jobId, companyId, "completed");}@@ -328,5 +347,5 @@ async function processDocumentType(}}- return printJobIds;+ return { printJobIds, deliverJobIds };}