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.

refactor(files): one stored PDF name for every finalized document

Raul47f029bca863
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 9c7969eacb..4b7dff17c2 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -84,7 +84,7 @@ import {
} from "@carbon/database/stock-transfer";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { evaluateLinesForSurface } from "@carbon/ee/rules.server";
-import { storage } from "@carbon/files";
+import { storage, storedDocumentPdfName } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
@@ -192,7 +192,6 @@ import {
setGenericQueryFilters,
setSearchFilter
} from "~/utils/query";
-import { stripSpecialCharacters } from "~/utils/string";
import { ruleError, sanitize } from "~/utils/supabase";
import { getItemStorageUnitQuantities } from "../items/items.utils";
import { rescheduleJob } from "../production/production.service";
@@ -5147,8 +5146,9 @@ export async function savePackingSlip(
if (pdf.headers.get("content-type") !== "application/pdf") return;
const file = await pdf.arrayBuffer();
- const fileName = stripSpecialCharacters(
- `${shipment.data.shipmentId} - ${datetime.timestamp().slice(0, -5)}.pdf`
+ const fileName = storedDocumentPdfName(
+ shipment.data.shipmentId,
+ datetime.timestamp()
);
const documentFilePath = `${companyId}/opportunity/${salesOrder.data.opportunityId}/${fileName}`;
const upload = await storage(serviceRole)
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index de80e1994c..314117d446 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -82,7 +82,7 @@ import {
evaluateSalesRuleLines,
isBlocked
} from "@carbon/ee/rules.server";
-import { storage } from "@carbon/files";
+import { storage, storedDocumentPdfName } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import {
loadSalesInvoiceDocument,
@@ -212,7 +212,6 @@ import {
import { getUser } from "~/modules/users/users.service";
import type { GenericQueryFilters } from "~/utils/query";
import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
-import { stripSpecialCharacters } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import { getExchangeRate } from "../accounting/accounting.service";
import { getEmployeeJob } from "../people/people.service";
@@ -5237,8 +5236,9 @@ export async function sendPostedSalesInvoice(
storageUrl: SUPABASE_URL ?? ""
});
const file = await renderSalesInvoicePdf(document.pdfProps);
- const fileName = stripSpecialCharacters(
- `${salesInvoice.data.invoiceId} - ${datetime.timestamp().slice(0, -5)}.pdf`
+ const fileName = storedDocumentPdfName(
+ salesInvoice.data.invoiceId ?? "",
+ datetime.timestamp()
);
const { opportunityId } = salesInvoice.data;
const path = `${companyId}/${opportunityId ? `opportunity/${opportunityId}` : `sales-invoice/${invoiceId}`}/${fileName}`;
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
index a1e599d1f5..efb362e931 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
@@ -23,7 +23,6 @@ import * as purchasingModels from "./purchasing.models";
import {
canCreatePurchaseOrderRevision,
isPurchaseOrderLocked,
- isStoredPurchaseOrderPdf,
leaseClassificationValidator,
leaseDetailsValidator,
leaseDurationOf,
@@ -38,7 +37,6 @@ import {
lockedReturnLineField,
PURCHASE_ORDER_LOCKED_STATUSES,
purchaseOrderDeleteRefusal,
- purchaseOrderPdfFileName,
purchaseOrderStatusType,
purchaseOrderValidator,
resolveLeaseDates,
@@ -651,43 +649,3 @@ 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 3e4318cb5a..9e3d1e0512 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -9,7 +9,6 @@ import {
bicMatchesCountry,
getBankFieldConfig,
isValidSwiftBic,
- stripSpecialCharacters,
type TaxPair,
taxableBase,
taxPairFromAmount,
@@ -892,36 +891,6 @@ 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 f307a79a07..ce3a907c30 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -24,7 +24,7 @@ import {
isApprovalRequired,
rejectRequest
} from "@carbon/ee/approvals.server";
-import { storage } from "@carbon/files";
+import { storage, storedDocumentPdfName } from "@carbon/files";
import { trigger } from "@carbon/jobs";
import { checkPartyContactRequirement } from "@carbon/lib/party-contact.server";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -67,7 +67,6 @@ import {
} from "~/modules/shared/shared.service";
import { getUser } from "~/modules/users/users.service";
import { ERP_URL, path } from "~/utils/path";
-import { stripSpecialCharacters } from "~/utils/string";
import { fromServerFn } from "../shared/shared.service";
import {
canCreatePurchaseOrderRevision,
@@ -2703,10 +2702,9 @@ export const confirmReturnOrder = defineServiceFn({
purchaseReturnOrderId,
locale: locale ?? "en-US"
});
- const fileName = stripSpecialCharacters(
- `${order.data.purchaseReturnOrderId ?? ""} - ${datetime
- .timestamp()
- .slice(0, -5)}.pdf`
+ const fileName = storedDocumentPdfName(
+ order.data.purchaseReturnOrderId ?? "",
+ datetime.timestamp()
);
const path = `${companyId}/purchase-return-order/${purchaseReturnOrderId}/${fileName}`;
const upload = await storage(system)
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index ee0baa8683..b8f5c6b3f6 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -51,7 +51,9 @@ import { insertAuditLogEntries } from "@carbon/ee/audit.server";
import {
getCompanyPrivateBucket,
getFileExtension,
+ isStoredDocumentPdf,
storage,
+ storedDocumentPdfName,
TEMP_STAGING_BUCKET
} from "@carbon/files";
import { isModelRawDownloadable } from "@carbon/files/cad";
@@ -171,7 +173,6 @@ import type {
supplierValidator
} from "./purchasing.models";
import {
- isStoredPurchaseOrderPdf,
leaseDetailFields,
leaseLineColumns,
leaseLinePaymentFields,
@@ -181,7 +182,6 @@ 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";
@@ -6051,9 +6051,7 @@ export async function withoutStoredPurchaseOrderPdfs<
const purchaseOrderIds = orders.data.flatMap((order) =>
order.purchaseOrderId ? [order.purchaseOrderId] : []
);
- return docs.filter(
- (doc) => !isStoredPurchaseOrderPdf(doc.name, purchaseOrderIds)
- );
+ return docs.filter((doc) => !isStoredDocumentPdf(doc.name, purchaseOrderIds));
}
/** Signed links to a supplier interaction's documents, for an email. A file
@@ -6538,7 +6536,7 @@ export async function attachPurchaseOrderPdf(
return ctx.error("internal", "Failed to generate PDF", err);
}
- const fileName = purchaseOrderPdfFileName(
+ const fileName = storedDocumentPdfName(
getPurchaseOrderDisplayId(purchaseOrder),
datetime.timestamp()
);
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 4257c6bd6e..63936d40dc 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -73,7 +73,11 @@ import {
isBlocked,
resolveSalesOrderShipTo
} from "@carbon/ee/rules.server";
-import { storage, TEMP_STAGING_BUCKET } from "@carbon/files";
+import {
+ storage,
+ storedDocumentPdfName,
+ TEMP_STAGING_BUCKET
+} from "@carbon/files";
import { parseCsv } from "@carbon/files/csv";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -151,7 +155,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,
@@ -11934,9 +11937,7 @@ export async function attachDocumentPdf(
}
const companyId = ctx.company.id;
const file = await args.pdf.arrayBuffer();
- const fileName = stripSpecialCharacters(
- `${args.identifier} - ${datetime.timestamp().slice(0, -5)}.pdf`
- );
+ const fileName = storedDocumentPdfName(args.identifier, datetime.timestamp());
const documentFilePath = `${companyId}/${args.folder}/${fileName}`;
const upload = await storage(ctx.asSystem.supabase)
diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.md
index 7b745053be..0adb5c07cd 100644
--- a/packages/files/AGENTS.md
+++ b/packages/files/AGENTS.md
@@ -6,7 +6,7 @@ in the codebase, shared by the browser and Node.
| Subpath | Provides |
|---------|----------|
-| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, `downloadUrl(url, filename)` (fetches first and throws on a failed response, so an expired session never saves an error page under the file's name), and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id). Every read and write goes to the company bucket only; there is no shared `private` bucket. `list(folder)` takes no options: it reads the cursor-paged `listV2` endpoint to the end and returns every entry directly inside the folder, sorted by name, in the old `list` shape (`name` is the entry's own name; a sub-folder has a null `id`). Every key must sit under `${companyId}/` and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. `getCompanyPrivateBucket` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver). `PRIVATE_PREVIEW_ALIAS` (`"private"`) is a stored URL segment, not a bucket: `/file/preview/private/<path>` links in rich text and inspection documents are served from the caller's own company bucket |
+| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, `downloadUrl(url, filename)` (fetches first and throws on a failed response, so an expired session never saves an error page under the file's name), and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id). Every read and write goes to the company bucket only; there is no shared `private` bucket. `list(folder)` takes no options: it reads the cursor-paged `listV2` endpoint to the end and returns every entry directly inside the folder, sorted by name, in the old `list` shape (`name` is the entry's own name; a sub-folder has a null `id`). Every key must sit under `${companyId}/` and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. `getCompanyPrivateBucket` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver). `PRIVATE_PREVIEW_ALIAS` (`"private"`) is a stored URL segment, not a bucket: `/file/preview/private/<path>` links in rich text and inspection documents are served from the caller's own company bucket. **`storedDocumentPdfName(displayId, timestamp)`** is THE name of a document PDF stored when it is finalized, sent or posted (`<display id> - <UTC second>.pdf`: purchase order, purchase return, quote, sales order, sales return, sales invoice, shipment); **`isStoredDocumentPdf(fileName, documentIds)`** recognises one at any revision, for documents that share a folder |
| `./csv` | `encodeCsv` (object rows; `header: false` encodes a later page of a streamed file — pages join with `\r\n`, see the Sync Activity export) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell; `formulaSafe: false` turns that off for CSV a program reads and no spreadsheet opens, which today is only the MCP server's tool results); `parseCsv` (text) / `parseCsvFile` (browser File, streamed) / `parseCsvLines` (text → records with the line each starts on, blank and delimiter-only records left out; for messages that name a line); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection |
| `./markdown` | `TiptapText(value, { format? })` — the ONE place a rich-text document is turned into text or read from it, with no DOM (server and browser). `value` is a stored document, a document encoded as text, or text. `.toDocument()` (text read as CommonMark through `@tiptap/pm/markdown`, raw HTML kept as text, the editor's node and mark names; `format: "text"` stores it as typed: a paragraph per line, `**bold**`), `.toString()` (plain text), `.toMarkdown()` (editor-only nodes such as mentions become text, unknown wrappers keep their children). Used by every API / MCP rich-text input (`toTiptapDoc`), the Linear sync, Paperless notes, and the shared `generateHTML` (`@carbon/react`), which reads a JSON string scalar an older API stored instead of crashing on it |
| `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` |
diff --git a/packages/files/src/index.ts b/packages/files/src/index.ts
index 0d60662887..431766f631 100644
--- a/packages/files/src/index.ts
+++ b/packages/files/src/index.ts
@@ -16,3 +16,4 @@ export {
MEDIA_CONTENT_TYPES
} from "./media/media";
export * from "./storage";
+export * from "./stored-document";
diff --git a/packages/files/src/stored-document.test.ts b/packages/files/src/stored-document.test.ts
new file mode 100644
index 0000000000..6d7811f51b
--- /dev/null
+++ b/packages/files/src/stored-document.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// 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 { describe, expect, it } from "vitest";
+import { isStoredDocumentPdf, storedDocumentPdfName } from "./stored-document";
+
+describe("storedDocumentPdfName", () => {
+ it("names a stored PDF by display id and the UTC second", () => {
+ expect(
+ storedDocumentPdfName("PO000148-1", "2026-10-22T14:03:22.123Z")
+ ).toBe("PO000148-1 - 2026-10-22T14:03:22.pdf");
+ });
+
+ it("drops characters a storage key cannot hold", () => {
+ expect(storedDocumentPdfName("SO#12?", "2026-10-22T14:03:22.123Z")).toBe(
+ "SO12 - 2026-10-22T14:03:22.pdf"
+ );
+ });
+});
+
+describe("isStoredDocumentPdf", () => {
+ // Two orders converted from one supplier quote share the interaction folder.
+ const orders = ["PO000146", "PO000148"];
+ const stored = (displayId: string) =>
+ storedDocumentPdfName(displayId, "2026-10-22T14:03:22.123Z");
+
+ it("matches every document's stored PDF, at any revision", () => {
+ expect(isStoredDocumentPdf(stored("PO000146"), orders)).toBe(true);
+ expect(isStoredDocumentPdf(stored("PO000148"), orders)).toBe(true);
+ expect(isStoredDocumentPdf(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(isStoredDocumentPdf(name, orders)).toBe(false);
+ }
+ });
+
+ it("leaves another document's PDF alone when only the id prefix matches", () => {
+ expect(isStoredDocumentPdf(stored("PO0001480"), orders)).toBe(false);
+ expect(isStoredDocumentPdf(stored("PO000146"), ["PO00014"])).toBe(false);
+ });
+
+ it("matches nothing without document ids", () => {
+ expect(isStoredDocumentPdf(stored("PO000146"), [])).toBe(false);
+ expect(isStoredDocumentPdf(stored("PO000146"), [""])).toBe(false);
+ });
+});
diff --git a/packages/files/src/stored-document.ts b/packages/files/src/stored-document.ts
new file mode 100644
index 0000000000..61da246cec
--- /dev/null
+++ b/packages/files/src/stored-document.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// 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 { stripSpecialCharacters } from "@carbon/utils";
+
+/**
+ * The name a document's PDF is stored under when it is finalized, sent or
+ * posted: `<display id> - <UTC time to the second>.pdf`, such as
+ * `PO000123-1 - 2026-10-22T14:03:22.pdf`. `timestamp` is an ISO instant
+ * (`datetime.timestamp()`).
+ */
+export function storedDocumentPdfName(displayId: string, timestamp: string) {
+ return stripSpecialCharacters(`${displayId} - ${timestamp.slice(0, 19)}.pdf`);
+}
+
+// What follows the document id: an optional revision (`-2`), then the time.
+const STORED_PDF_SUFFIX =
+ /^(-\d+)? - \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.pdf$/;
+
+/**
+ * Whether `fileName` is a PDF stored (`storedDocumentPdfName`) for one of
+ * `documentIds`, at any revision. Documents that share a folder (purchase
+ * orders converted from one supplier quote, the quote, order, invoice and
+ * shipments of one opportunity) use it to tell their stored PDFs from the
+ * files a person added.
+ */
+export function isStoredDocumentPdf(fileName: string, documentIds: string[]) {
+ return documentIds.some((documentId) => {
+ const prefix = stripSpecialCharacters(documentId);
+ return (
+ prefix.length > 0 &&
+ fileName.startsWith(prefix) &&
+ STORED_PDF_SUFFIX.test(fileName.slice(prefix.length))
+ );
+ });
+}