Skip to content

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.

fix(purchasing): a PO email attaches its own PDF, not every PO PDF in the shared folder

Raul40011b2f5e87
diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.md
index 6dd37306b4..0ff9665572 100644
--- a/apps/erp/app/modules/purchasing/AGENTS.md
+++ b/apps/erp/app/modules/purchasing/AGENTS.md
@@ -85,7 +85,7 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing
Each is a `defineServiceFn` const in `purchasing.server.ts`. The route calls it as `api.purchasing.<name>(input)`; the API and MCP publish the ones tagged `@mcp` as `purchasing_<name>`. It holds every check the route made. Routes validate the request, call one, and answer with `respond(request, result).redirect(…)` (a flash) or the result.
-- 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`), `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; 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.
+- 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`), `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).
- 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).
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
index efb362e931..a1e599d1f5 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
@@ -23,6 +23,7 @@ import * as purchasingModels from "./purchasing.models";
import {
canCreatePurchaseOrderRevision,
isPurchaseOrderLocked,
+ isStoredPurchaseOrderPdf,
leaseClassificationValidator,
leaseDetailsValidator,
leaseDurationOf,
@@ -37,6 +38,7 @@ import {
lockedReturnLineField,
PURCHASE_ORDER_LOCKED_STATUSES,
purchaseOrderDeleteRefusal,
+ purchaseOrderPdfFileName,
purchaseOrderStatusType,
purchaseOrderValidator,
resolveLeaseDates,
@@ -649,3 +651,43 @@ describe("splitRfqModelAttachments", () => {
expect(link.map((m) => m.id)).toEqual(["a"]);
});
});
+
+describe("isStoredPurchaseOrderPdf", () => {
+ // Two orders converted from one supplier quote share the interaction folder.
+ const orders = ["PO000146", "PO000148"];
+ const stored = (displayId: string) =>
+ purchaseOrderPdfFileName(displayId, "2026-10-22T14:03:22.123Z");
+
+ it("names a stored PDF by display id and the UTC second", () => {
+ expect(stored("PO000148-1")).toBe("PO000148-1 - 2026-10-22T14:03:22.pdf");
+ });
+
+ it("matches every order's stored PDF, at any revision", () => {
+ expect(isStoredPurchaseOrderPdf(stored("PO000146"), orders)).toBe(true);
+ expect(isStoredPurchaseOrderPdf(stored("PO000148"), orders)).toBe(true);
+ expect(isStoredPurchaseOrderPdf(stored("PO000148-2"), orders)).toBe(true);
+ });
+
+ it("keeps the files a person added", () => {
+ for (const name of [
+ "drawing.pdf",
+ "PO000148 notes.pdf",
+ "PO000148 - signed copy.pdf",
+ "PO000148 - 2026-10-22T14:03:22.step"
+ ]) {
+ expect(isStoredPurchaseOrderPdf(name, orders)).toBe(false);
+ }
+ });
+
+ it("leaves another order's PDF alone when only the id prefix matches", () => {
+ expect(isStoredPurchaseOrderPdf(stored("PO0001480"), orders)).toBe(false);
+ expect(isStoredPurchaseOrderPdf(stored("PO000146"), ["PO00014"])).toBe(
+ false
+ );
+ });
+
+ it("matches nothing without orders", () => {
+ expect(isStoredPurchaseOrderPdf(stored("PO000146"), [])).toBe(false);
+ expect(isStoredPurchaseOrderPdf(stored("PO000146"), [""])).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index 9e3d1e0512..3e4318cb5a 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -9,6 +9,7 @@ import {
bicMatchesCountry,
getBankFieldConfig,
isValidSwiftBic,
+ stripSpecialCharacters,
type TaxPair,
taxableBase,
taxPairFromAmount,
@@ -891,6 +892,36 @@ export function canCreatePurchaseOrderRevision(transition: {
);
}
+/**
+ * The name finalize gives the PDF it stores with a purchase order's supplier
+ * interaction files: `<display id> - <UTC time to the second>.pdf`, such as
+ * `PO000123-1 - 2026-10-22T14:03:22.pdf`. `timestamp` is an ISO instant.
+ */
+export function purchaseOrderPdfFileName(displayId: string, timestamp: string) {
+ return stripSpecialCharacters(`${displayId} - ${timestamp.slice(0, 19)}.pdf`);
+}
+
+const STORED_PDF_SUFFIX =
+ /^(-\d+)? - \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.pdf$/;
+
+/**
+ * Whether a file in a supplier interaction's folder is a PDF finalize stored
+ * (`purchaseOrderPdfFileName`) for one of `purchaseOrderIds`, at any revision.
+ */
+export function isStoredPurchaseOrderPdf(
+ fileName: string,
+ purchaseOrderIds: string[]
+) {
+ return purchaseOrderIds.some((purchaseOrderId) => {
+ const prefix = stripSpecialCharacters(purchaseOrderId);
+ return (
+ prefix.length > 0 &&
+ fileName.startsWith(prefix) &&
+ STORED_PDF_SUFFIX.test(fileName.slice(prefix.length))
+ );
+ });
+}
+
/**
* Why `userId` may not delete a purchase order, or null. Only a Draft,
* Planned or Needs Approval order can be deleted, and one that needs approval
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index 976c098020..f307a79a07 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -743,7 +743,12 @@ export const sendSupplierQuoteToSupplier = defineServiceFn({
const interactionId = quote.data.supplierInteractionId;
const attachments = [
...(interactionId
- ? await service.interactionAttachments(client, companyId, interactionId)
+ ? await service.interactionAttachments(
+ client,
+ companyId,
+ interactionId,
+ { withoutPurchaseOrderPdfs: true }
+ )
: []),
...(await service.getSupplierInteractionLineAttachments(
client,
@@ -2470,11 +2475,15 @@ export const finalizePurchaseOrderAndNotify = defineServiceFn({
]
});
const attachments = [
+ ...(await service.signedAttachments(system, companyId, [
+ { filename: pdf.fileName, path: pdf.path }
+ ])),
...(interactionId
? await service.interactionAttachments(
system,
companyId,
- interactionId
+ interactionId,
+ { withoutPurchaseOrderPdfs: true }
)
: []),
...(await service.signedAttachments(
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 627dace4a5..0e998eb021 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -122,7 +122,6 @@ import { getUser } from "~/modules/users/users.service";
import { path } from "~/utils/path";
import type { GenericQueryFilters } from "~/utils/query";
import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
-import { stripSpecialCharacters } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import {
getCurrencyByCode,
@@ -172,6 +171,7 @@ import type {
supplierValidator
} from "./purchasing.models";
import {
+ isStoredPurchaseOrderPdf,
leaseDetailFields,
leaseLineColumns,
leaseLinePaymentFields,
@@ -181,6 +181,7 @@ import {
PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES,
PURCHASE_ORDER_LOCKED_STATUSES,
type PURCHASE_ORDER_REOPEN_STATUSES,
+ purchaseOrderPdfFileName,
taxPairForQuantity
} from "./purchasing.models";
import { renderPurchaseOrderPdf } from "./purchasing.pdf";
@@ -6011,18 +6012,70 @@ export async function draftLeaseSetupPath(
return path.to.leaseSetup(id, "assets");
}
+/**
+ * A supplier interaction's files without the PDFs finalize stored for its
+ * purchase orders. Every order converted from one supplier quote shares the
+ * interaction's folder, so attaching the whole listing sent a supplier the
+ * other orders' PDFs and every earlier copy of the order's own. Throws when
+ * the orders cannot be read, rather than let those PDFs through.
+ */
+export async function withoutStoredPurchaseOrderPdfs<
+ T extends { name: string }
+>(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ interactionId: string,
+ docs: T[]
+): Promise<T[]> {
+ if (docs.length === 0) return docs;
+ const orders = await client
+ .from("purchaseOrder")
+ .select("purchaseOrderId")
+ .eq("companyId", companyId)
+ .eq("supplierInteractionId", interactionId);
+ if (orders.error) {
+ logger.error("Failed to read the supplier interaction's purchase orders", {
+ companyId,
+ interactionId,
+ error: orders.error
+ });
+ throw new Error(
+ "Failed to read the supplier interaction's purchase orders"
+ );
+ }
+ const purchaseOrderIds = orders.data.flatMap((order) =>
+ order.purchaseOrderId ? [order.purchaseOrderId] : []
+ );
+ return docs.filter(
+ (doc) => !isStoredPurchaseOrderPdf(doc.name, purchaseOrderIds)
+ );
+}
+
/** Signed links to a supplier interaction's documents, for an email. A file
- * that cannot be signed is logged and left out. */
+ * that cannot be signed is logged and left out. With
+ * `withoutPurchaseOrderPdfs`, the PDFs finalize stored for the interaction's
+ * purchase orders are left out too (`withoutStoredPurchaseOrderPdfs`). */
export async function interactionAttachments(
client: SupabaseClient<Database>,
companyId: string,
- interactionId: string
+ interactionId: string,
+ {
+ withoutPurchaseOrderPdfs = false
+ }: { withoutPurchaseOrderPdfs?: boolean } = {}
): Promise<{ filename: string; path: string; size?: number }[]> {
- const docs = await getSupplierInteractionDocuments(
+ const listed = await getSupplierInteractionDocuments(
client,
companyId,
interactionId
);
+ const docs = withoutPurchaseOrderPdfs
+ ? await withoutStoredPurchaseOrderPdfs(
+ client,
+ companyId,
+ interactionId,
+ listed
+ )
+ : listed;
return signedAttachments(
client,
companyId,
@@ -6480,10 +6533,9 @@ export async function attachPurchaseOrderPdf(
return ctx.error("internal", "Failed to generate PDF", err);
}
- const fileName = stripSpecialCharacters(
- `${getPurchaseOrderDisplayId(purchaseOrder)} - ${datetime
- .timestamp()
- .slice(0, -5)}.pdf`
+ const fileName = purchaseOrderPdfFileName(
+ getPurchaseOrderDisplayId(purchaseOrder),
+ datetime.timestamp()
);
const path = `${companyId}/supplier-interaction/${purchaseOrder.supplierInteractionId}/${fileName}`;
const upload = await storage(ctx.asSystem.supabase)
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 7ae9424aab..781ff25295 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -30,7 +30,8 @@ import {
getPurchaseOrderLines,
getSupplier,
getSupplierInteraction,
- getSupplierInteractionDocuments
+ getSupplierInteractionDocuments,
+ withoutStoredPurchaseOrderPdfs
} from "~/modules/purchasing/purchasing.service";
import {
PurchaseOrderExplorer,
@@ -212,7 +213,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
const supplierInteractionId = purchaseOrder.data?.supplierInteractionId;
// One listing feeds both the documents panel and the attachment list, and
- // neither holds up the page.
+ // neither holds up the page. The attachment list leaves out the stored PO
+ // PDFs, as the finalize email does: it attaches this order's new PDF itself.
const files = supplierInteractionId
? getSupplierInteractionDocuments(
serviceRole,
@@ -226,7 +228,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
supplierId: purchaseOrder.data?.supplierId ?? null,
itemIds
}),
- files
+ supplierInteractionId
+ ? files.then((docs) =>
+ withoutStoredPurchaseOrderPdfs(
+ serviceRole,
+ companyId,
+ supplierInteractionId,
+ docs
+ )
+ )
+ : files
])
.then(([defaults, adHocDocs]) => [
...defaults,