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
fix(sequences): keep document counters ahead of numbers saved through MCP, the API or a typed ID
aashub091e313b656
diff --git a/.claude/rules/authz-manifest.md b/.claude/rules/authz-manifest.mdindex c333825075..c297719d1f 100644--- a/.claude/rules/authz-manifest.md+++ b/.claude/rules/authz-manifest.md@@ -25,7 +25,7 @@ owns that table and its RLS switch, so sync and the generated migration never ru`ENABLE ROW LEVEL SECURITY` on it — sync fails instead if the switch is off. To add anotherexternal table, extend `ExternalTable` in `rules.ts` and `MANIFEST_SCHEMAS` in the check.-The same machinery owns the event system's 41 functions, its 64 table handlers and the event triggers — see+The same machinery owns the event system's 45 functions, its 65 table handlers and the event triggers — see[Event-system functions](#event-system-functions) below.| File | What it is |@@ -86,7 +86,7 @@ or `baseline.json` by hand.`packages/database/src/event-system/functions/` holds one file per function for dispatch,subscriptions, the queue wake-up, the audit log, the search index, embeddings and the-realtime broadcast triggers (41: 35 in `public`, 6 in `util`). They are loaded, synced, shipped and guarded exactly like the+realtime broadcast triggers and the document-number pattern (45: 37 in `public`, 8 in `util`). They are loaded, synced, shipped and guarded exactly like theRLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries its `schema`.- **File name is the function**: `dispatch_event_batch.sql` defines@@ -107,7 +107,7 @@ RLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries i`DROP FUNCTION` (sync refuses a file that would create an overload); the new definitiongoes in the file.- **Table handlers are managed too**: `../event-system/handlers/<name>.sql` holds every- function a table attaches — the 63 interceptors (`sync_*`, `prevent_*`, `set_shelf_life_*`,+ function a table attaches — the 64 interceptors (`sync_*`, `prevent_*`, `set_shelf_life_*`,`storage_unit_*`) and the statement handler `apply_item_stock_quantities`. Same format,same sync, same shipping; checked from `20261004194527` (`ATTACHMENTS_SINCE`). A newinterceptor is a new file there, never a function in a migration.diff --git a/.claude/rules/conventions-services.md b/.claude/rules/conventions-services.mdindex 2fdfa1e191..357dfe50d0 100644--- a/.claude/rules/conventions-services.md+++ b/.claude/rules/conventions-services.md@@ -201,6 +201,9 @@ route-wiring example is in [database-patterns.md](database-patterns.md#transacti(`~/modules/settings`) calls the `get_next_sequence` RPC and returns `{ data, error }`like any other service call — await and check `error` before using `data`. Note the argorder: `(client, table, companyId)`.+ A caller-supplied number (custom ID, API, MCP) needs no counter code: the+ `sync_advance_document_sequence` interceptor moves the sequence past any number saved+ in its format.- **RPCs**: heavy/aggregate logic is `client.rpc("fn_name", { ... })`; the function isdefined in a migration. See database-patterns.md.diff --git a/.claude/rules/customer-supplier-database-schema.md b/.claude/rules/customer-supplier-database-schema.mdindex 681f8f6c62..306a19b35e 100644--- a/.claude/rules/customer-supplier-database-schema.md+++ b/.claude/rules/customer-supplier-database-schema.md@@ -14,7 +14,7 @@ Customer and supplier data live in PostgreSQL (Supabase). The two families are *### `customer` / `supplier` (main entities)Key columns (both, unless noted):- `id` TEXT PK (default `uuid_generate_v4()`)-- `readableId` TEXT NOT NULL — human-readable id (`CUS`/`SUP` prefix, size 6), per-company unique (`<entity>_readableId_companyId_unique`). Auto-filled by a BEFORE INSERT trigger via `get_next_sequence(...)` only when blank, so explicit values (CSV import) win.+- `readableId` TEXT NOT NULL — human-readable id (`CUS`/`SUP` prefix, size 6), per-company unique (`<entity>_readableId_companyId_unique`). Auto-filled by a BEFORE INSERT trigger via `get_next_sequence(...)` only when blank, so explicit values (CSV import) win — and an explicit value in the sequence's format moves the counter past it (`sync_advance_document_sequence`).- `name` TEXT NOT NULL — unique per company (`<entity>_name_unique`)- `customerTypeId` / `supplierTypeId` TEXT → `customerType`/`supplierType`- **Status differs by entity (asymmetric):**diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.tsindex 7eda3edecf..05682e41c2 100644--- a/packages/database/src/event-system/attachments.ts+++ b/packages/database/src/event-system/attachments.ts@@ -36,7 +36,10 @@ export const attachments = {ability: { statement: ["broadcast_reference_changes"] },address: { before: ["sync_address_to_parent"], events: true },assemblyPlanJob: { statement: ["broadcast_table_changes"] },- changeOrder: { statement: ["broadcast_table_changes"] },+ changeOrder: {+ after: ["sync_advance_document_sequence"],+ statement: ["broadcast_table_changes"]+ },charge: { events: true },company: { after: ["sync_insert_company_related_records"] },companyIntegration: { before: ["sync_verify_integration"], events: true },@@ -44,7 +47,11 @@ export const attachments = {customField: { statement: ["broadcast_table_changes"] },customer: {before: ["sync_update_customer_type_group"],- after: ["sync_create_customer_entries", "sync_create_customer_org_group"],+ after: [+ "sync_create_customer_entries",+ "sync_create_customer_org_group",+ "sync_advance_document_sequence"+ ],events: true,statement: ["broadcast_table_changes", "log_table_changes"]},@@ -53,6 +60,7 @@ export const attachments = {events: true},customerContact: { statement: ["broadcast_reference_changes"] },+ customerContract: { after: ["sync_advance_document_sequence"] },customerItemPriceOverride: { events: true },customerItemPriceOverrideBreak: { events: true },customerLocation: { statement: ["broadcast_reference_changes"] },@@ -66,7 +74,7 @@ export const attachments = {events: true,statement: ["broadcast_reference_changes"]},- depreciationRun: { events: true },+ depreciationRun: { after: ["sync_advance_document_sequence"], events: true },depreciationRunLine: { events: true },document: {before: ["sync_edit_document_transaction"],@@ -87,8 +95,8 @@ export const attachments = {after: ["sync_create_employee_type_group"],events: true},- fixedAsset: { events: true },- gauge: { events: true },+ fixedAsset: { after: ["sync_advance_document_sequence"], events: true },+ gauge: { after: ["sync_advance_document_sequence"], events: true },gaugeCalibrationRecord: { events: true },implementationCheckState: { statement: ["broadcast_table_changes"] },implementationFieldValue: { statement: ["broadcast_table_changes"] },@@ -96,7 +104,11 @@ export const attachments = {implementationRow: { statement: ["broadcast_table_changes"] },inspection: { statement: ["broadcast_table_changes"] },inspectionSample: { statement: ["broadcast_table_changes"] },- inventoryCount: { events: true, statement: ["broadcast_table_changes"] },+ inventoryCount: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },inventoryCountLine: { events: true, statement: ["broadcast_table_changes"] },invite: { events: true },invoiceSettlement: { events: true, statement: ["broadcast_table_changes"] },@@ -128,7 +140,11 @@ export const attachments = {itemUnitSalePrice: { events: true },job: {before: ["sync_job_complete_or_canceled"],- after: ["sync_insert_job_make_method", "sync_job_recompute_service_line"],+ after: [+ "sync_insert_job_make_method",+ "sync_job_recompute_service_line",+ "sync_advance_document_sequence"+ ],events: true,statement: ["broadcast_table_changes"]},@@ -165,7 +181,11 @@ export const attachments = {jobOperationNote: { statement: ["broadcast_table_changes"] },jobOperationStep: { statement: ["broadcast_table_changes"] },jobOperationStepRecord: { statement: ["broadcast_table_changes"] },- journal: { events: true, statement: ["broadcast_table_changes"] },+ journal: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },journalLine: { events: true },location: {after: ["sync_create_location_related_records"],@@ -173,7 +193,10 @@ export const attachments = {statement: ["broadcast_reference_changes"]},maintenanceDispatch: {- after: ["sync_on_maintenance_dispatch_complete"],+ after: [+ "sync_on_maintenance_dispatch_complete",+ "sync_advance_document_sequence"+ ],events: true,statement: ["broadcast_table_changes"]},@@ -185,13 +208,17 @@ export const attachments = {materialForm: { statement: ["broadcast_table_changes"] },materialSubstance: { statement: ["broadcast_table_changes"] },materialType: { statement: ["broadcast_reference_changes"] },- memo: { events: true },+ memo: { after: ["sync_advance_document_sequence"], events: true },methodMaterial: {before: ["sync_check_method_material_self_reference"],events: true},modelUpload: { statement: ["broadcast_table_changes", "log_table_changes"] },- nonConformance: { events: true, statement: ["broadcast_table_changes"] },+ nonConformance: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },nonConformanceActionTask: {events: true,statement: ["broadcast_table_changes"]@@ -209,9 +236,17 @@ export const attachments = {nonConformanceType: { statement: ["broadcast_reference_changes"] },notification: { statement: ["broadcast_user_changes"] },part: { statement: ["broadcast_table_changes"] },- payment: { events: true, statement: ["broadcast_table_changes"] },+ payment: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },paymentTerm: { statement: ["broadcast_reference_changes"] },- pickingList: { events: true, statement: ["broadcast_table_changes"] },+ pickingList: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },pickingListLine: { events: true, statement: ["broadcast_table_changes"] },printJob: { statement: ["broadcast_table_changes"] },procedure: {@@ -232,6 +267,7 @@ export const attachments = {},purchaseInvoice: {before: ["prevent_posted_purchase_invoice_deletion"],+ after: ["sync_advance_document_sequence"],events: true,statement: ["broadcast_table_changes"]},@@ -240,13 +276,23 @@ export const attachments = {events: true,statement: ["broadcast_table_changes"]},- purchaseOrder: { events: true, statement: ["broadcast_table_changes"] },+ purchaseOrder: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },purchaseOrderDelivery: { events: true },purchaseOrderLine: { events: true, statement: ["broadcast_table_changes"] },purchaseOrderPayment: { events: true },- purchaseReturnOrder: { statement: ["broadcast_table_changes"] },+ purchaseReturnOrder: {+ after: ["sync_advance_document_sequence"],+ statement: ["broadcast_table_changes"]+ },purchaseReturnOrderLine: { statement: ["broadcast_table_changes"] },- purchasingRfq: { statement: ["broadcast_table_changes"] },+ purchasingRfq: {+ after: ["sync_advance_document_sequence"],+ statement: ["broadcast_table_changes"]+ },purchasingRfqLine: { statement: ["broadcast_table_changes"] },qualityDocument: {before: ["sync_archive_other_quality_documents"],@@ -255,6 +301,7 @@ export const attachments = {},quote: {before: ["sync_update_quote_exchange_rate"],+ after: ["sync_advance_document_sequence"],events: true,statement: ["broadcast_table_changes"]},@@ -273,14 +320,20 @@ export const attachments = {statement: ["broadcast_table_changes"]},quoteOperation: { statement: ["broadcast_table_changes"] },- receipt: { events: true, statement: ["broadcast_table_changes"] },+ receipt: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },receiptLine: { events: true, statement: ["broadcast_table_changes"] },reimbursement: { events: true },reimbursementLine: { events: true },+ rentalAgreement: { after: ["sync_advance_document_sequence"] },revenueRecognitionRun: { events: true },revenueRecognitionRunLine: { events: true },salesInvoice: {before: ["prevent_posted_sales_invoice_deletion"],+ after: ["sync_advance_document_sequence"],events: true,statement: ["broadcast_table_changes"]},@@ -288,20 +341,36 @@ export const attachments = {salesInvoiceShipment: { events: true },salesOrder: {before: ["sync_update_sales_order_exchange_rate"],+ after: ["sync_advance_document_sequence"],events: true,statement: ["broadcast_table_changes"]},salesOrderLine: { events: true, statement: ["broadcast_table_changes"] },salesOrderPayment: { events: true },salesOrderShipment: { events: true },- salesReturnOrder: { statement: ["broadcast_table_changes"] },+ salesReturnOrder: {+ after: ["sync_advance_document_sequence"],+ statement: ["broadcast_table_changes"]+ },salesReturnOrderLine: { statement: ["broadcast_table_changes"] },- salesRfq: { events: true, statement: ["broadcast_table_changes"] },+ salesRfq: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },salesRfqLine: { statement: ["broadcast_table_changes"] },- shipment: { events: true, statement: ["broadcast_table_changes"] },+ shipment: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },shipmentLine: { events: true, statement: ["broadcast_table_changes"] },shippingMethod: { statement: ["broadcast_reference_changes"] },- stockTransfer: { events: true, statement: ["broadcast_table_changes"] },+ stockTransfer: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },stockTransferLine: {after: ["sync_update_stock_transfer_status"],events: true,@@ -318,7 +387,11 @@ export const attachments = {},supplier: {before: ["sync_update_supplier_type_group"],- after: ["sync_create_supplier_entries", "sync_create_supplier_org_group"],+ after: [+ "sync_create_supplier_entries",+ "sync_create_supplier_org_group",+ "sync_advance_document_sequence"+ ],events: true,statement: ["broadcast_table_changes", "log_table_changes"]},@@ -331,7 +404,11 @@ export const attachments = {supplierPart: { events: true },supplierPayment: { events: true },supplierProcess: { statement: ["broadcast_reference_changes"] },- supplierQuote: { events: true, statement: ["broadcast_table_changes"] },+ supplierQuote: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },supplierQuoteLine: { events: true, statement: ["broadcast_table_changes"] },supplierShipping: { events: true },supplierTax: { events: true },@@ -352,7 +429,11 @@ export const attachments = {],statement: ["log_user_changes"]},- warehouseTransfer: { events: true, statement: ["broadcast_table_changes"] },+ warehouseTransfer: {+ after: ["sync_advance_document_sequence"],+ events: true,+ statement: ["broadcast_table_changes"]+ },warehouseTransferLine: {events: true,statement: ["broadcast_table_changes"]diff --git a/packages/database/src/event-system/functions/util.document_sequence_number.sql b/packages/database/src/event-system/functions/util.document_sequence_number.sqlnew file mode 100644index 0000000000..6481f87f3c--- /dev/null+++ b/packages/database/src/event-system/functions/util.document_sequence_number.sql@@ -0,0 +1,19 @@+CREATE OR REPLACE FUNCTION util.document_sequence_number(p_value text, p_prefix text, p_suffix text, p_size integer)+ RETURNS bigint+ LANGUAGE plpgsql+ IMMUTABLE+AS $function$+DECLARE+ v_digits text;+BEGIN+ -- The number get_next_sequence would have formatted as p_value, or NULL when+ -- p_value is not in the sequence's format (a custom id such as "ACME-1").+ v_digits := substring(p_value FROM util.document_sequence_pattern(p_prefix, p_suffix, p_size));++ IF v_digits IS NULL OR length(v_digits) > 18 THEN+ RETURN NULL;+ END IF;++ RETURN v_digits::bigint;+END;+$function$;diff --git a/packages/database/src/event-system/functions/util.document_sequence_pattern.sql b/packages/database/src/event-system/functions/util.document_sequence_pattern.sqlnew file mode 100644index 0000000000..e44eade921--- /dev/null+++ b/packages/database/src/event-system/functions/util.document_sequence_pattern.sql@@ -0,0 +1,35 @@+CREATE OR REPLACE FUNCTION util.document_sequence_pattern(p_prefix text, p_suffix text, p_size integer)+ RETURNS text+ LANGUAGE plpgsql+ IMMUTABLE+AS $function$+DECLARE+ v_prefix text;+ v_suffix text;+BEGIN+ -- A regular expression matching what get_next_sequence (and its TypeScript+ -- twin, getNextSequence in @carbon/database/sequence) formats for a+ -- sequence, capturing the number. Date tokens match any date: the counter+ -- does not reset per period. get_next_sequence pads to p_size, so a shorter+ -- number is never one it issues.+ v_prefix := regexp_replace(COALESCE(p_prefix, ''), '([.^$*+?()\[\]{}|\\])', '\\\1', 'g');+ v_prefix := replace(v_prefix, '%\{yyyy\}', '[0-9]{4}');+ v_prefix := replace(v_prefix, '%\{yy\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{mm\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{ww\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{dd\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{hh\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{ss\}', '[0-9]{2}');++ v_suffix := regexp_replace(COALESCE(p_suffix, ''), '([.^$*+?()\[\]{}|\\])', '\\\1', 'g');+ v_suffix := replace(v_suffix, '%\{yyyy\}', '[0-9]{4}');+ v_suffix := replace(v_suffix, '%\{yy\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{mm\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{ww\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{dd\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{hh\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{ss\}', '[0-9]{2}');++ RETURN '^' || v_prefix || '([0-9]{' || COALESCE(p_size, 4) || ',})' || v_suffix || '$';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_advance_document_sequence.sql b/packages/database/src/event-system/handlers/sync_advance_document_sequence.sqlnew file mode 100644index 0000000000..11d40af634--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_advance_document_sequence.sql@@ -0,0 +1,79 @@+CREATE OR REPLACE FUNCTION public.sync_advance_document_sequence(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_column text;+ v_sequence text;+ v_value text;+BEGIN+ -- A document saved with a number in its sequence's format (typed by hand,+ -- sent through the API or MCP, imported) moves the counter past it, so+ -- get_next_sequence never hands that number out again.+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ -- A new numbered table is added here and attached in attachments.ts.+ v_column := CASE p_table+ WHEN 'changeOrder' THEN 'changeOrderId'+ WHEN 'customer' THEN 'readableId'+ WHEN 'customerContract' THEN 'customerContractId'+ WHEN 'depreciationRun' THEN 'depreciationRunId'+ WHEN 'fixedAsset' THEN 'fixedAssetId'+ WHEN 'gauge' THEN 'gaugeId'+ WHEN 'inventoryCount' THEN 'inventoryCountId'+ WHEN 'job' THEN 'jobId'+ WHEN 'journal' THEN 'journalEntryId'+ WHEN 'maintenanceDispatch' THEN 'maintenanceDispatchId'+ WHEN 'memo' THEN 'memoId'+ WHEN 'nonConformance' THEN 'nonConformanceId'+ WHEN 'payment' THEN 'paymentId'+ WHEN 'pickingList' THEN 'pickingListId'+ WHEN 'purchaseInvoice' THEN 'invoiceId'+ WHEN 'purchaseOrder' THEN 'purchaseOrderId'+ WHEN 'purchaseReturnOrder' THEN 'purchaseReturnOrderId'+ WHEN 'purchasingRfq' THEN 'rfqId'+ WHEN 'quote' THEN 'quoteId'+ WHEN 'receipt' THEN 'receiptId'+ WHEN 'rentalAgreement' THEN 'rentalAgreementId'+ WHEN 'salesInvoice' THEN 'invoiceId'+ WHEN 'salesOrder' THEN 'salesOrderId'+ WHEN 'salesReturnOrder' THEN 'salesReturnOrderId'+ WHEN 'salesRfq' THEN 'rfqId'+ WHEN 'shipment' THEN 'shipmentId'+ WHEN 'stockTransfer' THEN 'stockTransferId'+ WHEN 'supplier' THEN 'readableId'+ WHEN 'supplierQuote' THEN 'supplierQuoteId'+ WHEN 'warehouseTransfer' THEN 'transferId'+ END;++ IF v_column IS NULL THEN+ RETURN;+ END IF;++ v_value := p_new->>v_column;+ IF v_value IS NULL+ OR (p_operation = 'UPDATE' AND v_value IS NOT DISTINCT FROM p_old->>v_column)+ THEN+ RETURN;+ END IF;++ -- The sequence is named after its table, except these.+ v_sequence := CASE+ WHEN p_table = 'journal' THEN 'journalEntry'+ WHEN p_table = 'memo' AND p_new->>'direction' = 'Debit' THEN 'debitMemo'+ WHEN p_table = 'memo' THEN 'creditMemo'+ ELSE p_table+ END;++ UPDATE "sequence"+ SET "next" = util.document_sequence_number(v_value, "prefix", "suffix", "size")::integer,+ "updatedBy" = 'system'+ WHERE "table" = v_sequence+ AND "companyId" = p_new->>'companyId'+ AND util.document_sequence_number(v_value, "prefix", "suffix", "size")+ BETWEEN "next"::bigint + 1 AND 2147483647;+END;+$function$;diff --git a/packages/database/src/sequence.ts b/packages/database/src/sequence.tsindex 1abc415e50..25da9fb614 100644--- a/packages/database/src/sequence.ts+++ b/packages/database/src/sequence.ts@@ -23,7 +23,9 @@ const isoWeekFromYmd = (year: number, month: number, day: number): number => {// Date tokens derive in the company's business timezone so document prefixes// roll over at the company's midnight, not the process's. The ERP's live// preview (`interpolateSequenceDate` in apps/erp/app/utils/string.ts) mirrors-// this — keep the two in sync.+// this — keep the two in sync, along with get_next_sequence (SQL) and+// util.document_sequence_pattern (src/event-system/functions), which reads a+// saved number back to keep the counter ahead of it.const interpolateSequenceDate = (value?: string | null, timezone = "UTC") => {if (!value) return "";let result = value;diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 8a81d9eb40..a33510a6a0 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -91910,6 +91910,10 @@ export type Database = {}Returns: undefined}+ sync_advance_document_sequence: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_archive_other_procedures: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefineddiff --git a/packages/database/supabase/migrations/20261009171423_advance-document-sequence.sql b/packages/database/supabase/migrations/20261009171423_advance-document-sequence.sqlnew file mode 100644index 0000000000..1d5f06fb4e--- /dev/null+++ b/packages/database/supabase/migrations/20261009171423_advance-document-sequence.sql@@ -0,0 +1,173 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION util.document_sequence_number(p_value text, p_prefix text, p_suffix text, p_size integer)+ RETURNS bigint+ LANGUAGE plpgsql+ IMMUTABLE+AS $function$+DECLARE+ v_digits text;+BEGIN+ -- The number get_next_sequence would have formatted as p_value, or NULL when+ -- p_value is not in the sequence's format (a custom id such as "ACME-1").+ v_digits := substring(p_value FROM util.document_sequence_pattern(p_prefix, p_suffix, p_size));++ IF v_digits IS NULL OR length(v_digits) > 18 THEN+ RETURN NULL;+ END IF;++ RETURN v_digits::bigint;+END;+$function$;++CREATE OR REPLACE FUNCTION util.document_sequence_pattern(p_prefix text, p_suffix text, p_size integer)+ RETURNS text+ LANGUAGE plpgsql+ IMMUTABLE+AS $function$+DECLARE+ v_prefix text;+ v_suffix text;+BEGIN+ -- A regular expression matching what get_next_sequence (and its TypeScript+ -- twin, getNextSequence in @carbon/database/sequence) formats for a+ -- sequence, capturing the number. Date tokens match any date: the counter+ -- does not reset per period. get_next_sequence pads to p_size, so a shorter+ -- number is never one it issues.+ v_prefix := regexp_replace(COALESCE(p_prefix, ''), '([.^$*+?()\[\]{}|\\])', '\\\1', 'g');+ v_prefix := replace(v_prefix, '%\{yyyy\}', '[0-9]{4}');+ v_prefix := replace(v_prefix, '%\{yy\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{mm\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{ww\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{dd\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{hh\}', '[0-9]{2}');+ v_prefix := replace(v_prefix, '%\{ss\}', '[0-9]{2}');++ v_suffix := regexp_replace(COALESCE(p_suffix, ''), '([.^$*+?()\[\]{}|\\])', '\\\1', 'g');+ v_suffix := replace(v_suffix, '%\{yyyy\}', '[0-9]{4}');+ v_suffix := replace(v_suffix, '%\{yy\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{mm\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{ww\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{dd\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{hh\}', '[0-9]{2}');+ v_suffix := replace(v_suffix, '%\{ss\}', '[0-9]{2}');++ RETURN '^' || v_prefix || '([0-9]{' || COALESCE(p_size, 4) || ',})' || v_suffix || '$';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_advance_document_sequence(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_column text;+ v_sequence text;+ v_value text;+BEGIN+ -- A document saved with a number in its sequence's format (typed by hand,+ -- sent through the API or MCP, imported) moves the counter past it, so+ -- get_next_sequence never hands that number out again.+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ -- A new numbered table is added here and attached in attachments.ts.+ v_column := CASE p_table+ WHEN 'changeOrder' THEN 'changeOrderId'+ WHEN 'customer' THEN 'readableId'+ WHEN 'customerContract' THEN 'customerContractId'+ WHEN 'depreciationRun' THEN 'depreciationRunId'+ WHEN 'fixedAsset' THEN 'fixedAssetId'+ WHEN 'gauge' THEN 'gaugeId'+ WHEN 'inventoryCount' THEN 'inventoryCountId'+ WHEN 'job' THEN 'jobId'+ WHEN 'journal' THEN 'journalEntryId'+ WHEN 'maintenanceDispatch' THEN 'maintenanceDispatchId'+ WHEN 'memo' THEN 'memoId'+ WHEN 'nonConformance' THEN 'nonConformanceId'+ WHEN 'payment' THEN 'paymentId'+ WHEN 'pickingList' THEN 'pickingListId'+ WHEN 'purchaseInvoice' THEN 'invoiceId'+ WHEN 'purchaseOrder' THEN 'purchaseOrderId'+ WHEN 'purchaseReturnOrder' THEN 'purchaseReturnOrderId'+ WHEN 'purchasingRfq' THEN 'rfqId'+ WHEN 'quote' THEN 'quoteId'+ WHEN 'receipt' THEN 'receiptId'+ WHEN 'rentalAgreement' THEN 'rentalAgreementId'+ WHEN 'salesInvoice' THEN 'invoiceId'+ WHEN 'salesOrder' THEN 'salesOrderId'+ WHEN 'salesReturnOrder' THEN 'salesReturnOrderId'+ WHEN 'salesRfq' THEN 'rfqId'+ WHEN 'shipment' THEN 'shipmentId'+ WHEN 'stockTransfer' THEN 'stockTransferId'+ WHEN 'supplier' THEN 'readableId'+ WHEN 'supplierQuote' THEN 'supplierQuoteId'+ WHEN 'warehouseTransfer' THEN 'transferId'+ END;++ IF v_column IS NULL THEN+ RETURN;+ END IF;++ v_value := p_new->>v_column;+ IF v_value IS NULL+ OR (p_operation = 'UPDATE' AND v_value IS NOT DISTINCT FROM p_old->>v_column)+ THEN+ RETURN;+ END IF;++ -- The sequence is named after its table, except these.+ v_sequence := CASE+ WHEN p_table = 'journal' THEN 'journalEntry'+ WHEN p_table = 'memo' AND p_new->>'direction' = 'Debit' THEN 'debitMemo'+ WHEN p_table = 'memo' THEN 'creditMemo'+ ELSE p_table+ END;++ UPDATE "sequence"+ SET "next" = util.document_sequence_number(v_value, "prefix", "suffix", "size")::integer,+ "updatedBy" = 'system'+ WHERE "table" = v_sequence+ AND "companyId" = p_new->>'companyId'+ AND util.document_sequence_number(v_value, "prefix", "suffix", "size")+ BETWEEN "next"::bigint + 1 AND 2147483647;+END;+$function$;++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('changeOrder', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('customer', ARRAY['sync_update_customer_type_group']::text[], ARRAY['sync_create_customer_entries', 'sync_create_customer_org_group', 'sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('customerContract', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY[]::text[]);+SELECT set_event_triggers('depreciationRun', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('fixedAsset', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('gauge', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('inventoryCount', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('job', ARRAY['sync_job_complete_or_canceled']::text[], ARRAY['sync_insert_job_make_method', 'sync_job_recompute_service_line', 'sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('journal', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('maintenanceDispatch', ARRAY[]::text[], ARRAY['sync_on_maintenance_dispatch_complete', 'sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('memo', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('nonConformance', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('payment', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('pickingList', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseInvoice', ARRAY['prevent_posted_purchase_invoice_deletion']::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseOrder', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseReturnOrder', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchasingRfq', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('quote', ARRAY['sync_update_quote_exchange_rate']::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('receipt', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('rentalAgreement', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY[]::text[]);+SELECT set_event_triggers('salesInvoice', ARRAY['prevent_posted_sales_invoice_deletion']::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesOrder', ARRAY['sync_update_sales_order_exchange_rate']::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesReturnOrder', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesRfq', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('shipment', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('stockTransfer', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('supplier', ARRAY['sync_update_supplier_type_group']::text[], ARRAY['sync_create_supplier_entries', 'sync_create_supplier_org_group', 'sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('supplierQuote', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('warehouseTransfer', ARRAY[]::text[], ARRAY['sync_advance_document_sequence']::text[], true, ARRAY['broadcast_table_changes']::text[]);+RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261009171429_get-next-sequence-no-truncate.sql b/packages/database/supabase/migrations/20261009171429_get-next-sequence-no-truncate.sqlnew file mode 100644index 0000000000..90c7295daf--- /dev/null+++ b/packages/database/supabase/migrations/20261009171429_get-next-sequence-no-truncate.sql@@ -0,0 +1,73 @@+-- get_next_sequence truncated a number longer than the sequence's size+-- (lpad('1000000', 6) is '100000'), so a counter past 10^size handed out a+-- shorter, often already-used number. getNextSequence (@carbon/database/sequence)+-- pads with padStart and never truncates; this makes the two agree. A counter+-- can now pass 10^size because a saved document number moves it+-- (sync_advance_document_sequence). Only the padding line differs from+-- 20260925121735_rpc-function-guards.sql.+CREATE OR REPLACE FUNCTION public.get_next_sequence(sequence_name text, company_id text)+ RETURNS text+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public'+AS $function$+DECLARE+ v_prefix text;+ v_suffix text;+ v_next_value integer;+ v_size integer;+ v_next_sequence text;+ v_derived_prefix text;+ v_derived_suffix text;+ v_now timestamp;+BEGIN+ PERFORM assert_company_access(company_id);++ UPDATE sequence+ SET next = next + step,+ "updatedBy" = 'system'+ WHERE "table" = sequence_name+ AND "companyId" = company_id+ RETURNING next, prefix, suffix, size+ INTO v_next_value, v_prefix, v_suffix, v_size;++ IF NOT FOUND THEN+ RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;+ END IF;++ -- Format sequence number+ v_next_sequence := CASE+ WHEN length(v_next_value::text) >= COALESCE(v_size, 4) THEN v_next_value::text+ ELSE lpad(v_next_value::text, COALESCE(v_size, 4), '0')+ END;++ -- Wall-clock in the company's timezone: document prefixes must roll over at+ -- the company's midnight, not the database's. Matches the TypeScript twin+ -- interpolateSequenceDate(value, companyTimezone).+ v_now := now() AT TIME ZONE COALESCE(+ (SELECT "timezone" FROM "company" WHERE "id" = company_id),+ 'UTC'+ );++ -- Interpolate date variables in prefix/suffix+ v_derived_prefix := COALESCE(v_prefix, '');+ v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(v_now, 'YYYY'));+ v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(v_now, 'YY'));+ v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(v_now, 'MM'));+ v_derived_prefix := replace(v_derived_prefix, '%{ww}', to_char(v_now, 'IW'));+ v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(v_now, 'DD'));+ v_derived_prefix := replace(v_derived_prefix, '%{hh}', to_char(v_now, 'HH24'));+ v_derived_prefix := replace(v_derived_prefix, '%{ss}', to_char(v_now, 'SS'));++ v_derived_suffix := COALESCE(v_suffix, '');+ v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(v_now, 'YYYY'));+ v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(v_now, 'YY'));+ v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(v_now, 'MM'));+ v_derived_suffix := replace(v_derived_suffix, '%{ww}', to_char(v_now, 'IW'));+ v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(v_now, 'DD'));+ v_derived_suffix := replace(v_derived_suffix, '%{hh}', to_char(v_now, 'HH24'));+ v_derived_suffix := replace(v_derived_suffix, '%{ss}', to_char(v_now, 'SS'));++ RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;+END;+$function$;diff --git a/packages/database/supabase/migrations/20261009171437_backfill-document-sequences.sql b/packages/database/supabase/migrations/20261009171437_backfill-document-sequences.sqlnew file mode 100644index 0000000000..a868f830a2--- /dev/null+++ b/packages/database/supabase/migrations/20261009171437_backfill-document-sequences.sql@@ -0,0 +1,57 @@+-- Documents saved with a number chosen by the caller (typed by hand, or sent+-- through the API or MCP) never moved their sequence, so get_next_sequence later+-- handed out a number that was already taken and the insert failed on the+-- unique constraint. sync_advance_document_sequence keeps the counter ahead from+-- now on; this moves every counter that is already behind past the highest+-- number in its format.+UPDATE "sequence" s+SET "next" = m."maxNumber"::integer,+ "updatedBy" = 'system'+FROM (+ SELECT n."table", n."companyId",+ max(CASE WHEN length(n."digits") <= 18 THEN n."digits"::bigint END) AS "maxNumber"+ FROM (+ SELECT d."table", d."companyId", substring(d."value" FROM seq."pattern") AS "digits"+ FROM (+ SELECT 'customer' AS "table", "companyId", "readableId" AS "value" FROM "customer"+ UNION ALL SELECT CASE WHEN "direction" = 'Debit' THEN 'debitMemo' ELSE 'creditMemo' END, "companyId", "memoId" FROM "memo"+ UNION ALL SELECT 'changeOrder', "companyId", "changeOrderId" FROM "changeOrder"+ UNION ALL SELECT 'customerContract', "companyId", "customerContractId" FROM "customerContract"+ UNION ALL SELECT 'depreciationRun', "companyId", "depreciationRunId" FROM "depreciationRun"+ UNION ALL SELECT 'fixedAsset', "companyId", "fixedAssetId" FROM "fixedAsset"+ UNION ALL SELECT 'gauge', "companyId", "gaugeId" FROM "gauge"+ UNION ALL SELECT 'inventoryCount', "companyId", "inventoryCountId" FROM "inventoryCount"+ UNION ALL SELECT 'job', "companyId", "jobId" FROM "job"+ UNION ALL SELECT 'journalEntry', "companyId", "journalEntryId" FROM "journal"+ UNION ALL SELECT 'maintenanceDispatch', "companyId", "maintenanceDispatchId" FROM "maintenanceDispatch"+ UNION ALL SELECT 'nonConformance', "companyId", "nonConformanceId" FROM "nonConformance"+ UNION ALL SELECT 'payment', "companyId", "paymentId" FROM "payment"+ UNION ALL SELECT 'pickingList', "companyId", "pickingListId" FROM "pickingList"+ UNION ALL SELECT 'purchaseInvoice', "companyId", "invoiceId" FROM "purchaseInvoice"+ UNION ALL SELECT 'purchaseOrder', "companyId", "purchaseOrderId" FROM "purchaseOrder"+ UNION ALL SELECT 'purchaseReturnOrder', "companyId", "purchaseReturnOrderId" FROM "purchaseReturnOrder"+ UNION ALL SELECT 'purchasingRfq', "companyId", "rfqId" FROM "purchasingRfq"+ UNION ALL SELECT 'quote', "companyId", "quoteId" FROM "quote"+ UNION ALL SELECT 'receipt', "companyId", "receiptId" FROM "receipt"+ UNION ALL SELECT 'rentalAgreement', "companyId", "rentalAgreementId" FROM "rentalAgreement"+ UNION ALL SELECT 'salesInvoice', "companyId", "invoiceId" FROM "salesInvoice"+ UNION ALL SELECT 'salesOrder', "companyId", "salesOrderId" FROM "salesOrder"+ UNION ALL SELECT 'salesReturnOrder', "companyId", "salesReturnOrderId" FROM "salesReturnOrder"+ UNION ALL SELECT 'salesRfq', "companyId", "rfqId" FROM "salesRfq"+ UNION ALL SELECT 'shipment', "companyId", "shipmentId" FROM "shipment"+ UNION ALL SELECT 'stockTransfer', "companyId", "stockTransferId" FROM "stockTransfer"+ UNION ALL SELECT 'supplier', "companyId", "readableId" FROM "supplier"+ UNION ALL SELECT 'supplierQuote', "companyId", "supplierQuoteId" FROM "supplierQuote"+ UNION ALL SELECT 'warehouseTransfer', "companyId", "transferId" FROM "warehouseTransfer"+ ) d+ -- Each sequence's pattern is built once, not once per document.+ JOIN (+ SELECT "table", "companyId", util.document_sequence_pattern("prefix", "suffix", "size") AS "pattern"+ FROM "sequence"+ ) seq ON seq."table" = d."table" AND seq."companyId" = d."companyId"+ ) n+ GROUP BY n."table", n."companyId"+) m+WHERE s."table" = m."table"+ AND s."companyId" = m."companyId"+ AND m."maxNumber" BETWEEN s."next"::bigint + 1 AND 2147483647;diff --git a/packages/database/supabase/tests/document-sequence.test.sql b/packages/database/supabase/tests/document-sequence.test.sqlnew file mode 100644index 0000000000..e9388ba6ca--- /dev/null+++ b/packages/database/supabase/tests/document-sequence.test.sql@@ -0,0 +1,98 @@+-- A document saved with a number it was given (typed by hand, sent through the+-- API or MCP) moves its sequence past that number, so get_next_sequence never+-- hands it out again (sync_advance_document_sequence + util.document_sequence_number).+-- Run from the repository root against an existing local database that has at+-- least one company with a sales order:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/document-sequence.test.sql+-- Everything is confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '30s';++CREATE FUNCTION pg_temp.expect(label text, expected anyelement, actual anyelement)+RETURNS void LANGUAGE plpgsql AS $fn$+BEGIN+ IF actual IS DISTINCT FROM expected THEN+ RAISE EXCEPTION '%: expected %, got %', label, expected, actual;+ END IF;+END;+$fn$;++-- Parsing: only a number in the sequence's own format counts.+SELECT pg_temp.expect('plain number', 116::bigint, util.document_sequence_number('SO000116', 'SO', NULL, 6));+SELECT pg_temp.expect('longer than size', 1234567::bigint, util.document_sequence_number('SO1234567', 'SO', NULL, 6));+SELECT pg_temp.expect('shorter than size', NULL::bigint, util.document_sequence_number('SO1', 'SO', NULL, 6));+SELECT pg_temp.expect('custom id', NULL::bigint, util.document_sequence_number('ACME-1', 'SO', NULL, 6));+SELECT pg_temp.expect('text before prefix', NULL::bigint, util.document_sequence_number('XSO000116', 'SO', NULL, 6));+SELECT pg_temp.expect('date tokens', 123::bigint, util.document_sequence_number('JE-2026-10-000123', 'JE-%{yyyy}-%{mm}-', NULL, 6));+SELECT pg_temp.expect('week, hour and second tokens', 7::bigint, util.document_sequence_number('W41-13-05-000007', 'W%{ww}-%{hh}-%{ss}-', NULL, 6));+SELECT pg_temp.expect('wrong date width', NULL::bigint, util.document_sequence_number('JE-26-10-000123', 'JE-%{yyyy}-%{mm}-', NULL, 6));+SELECT pg_temp.expect('regex characters in prefix and suffix', 42::bigint, util.document_sequence_number('Q.(0042)-26', 'Q.(', ')-%{yy}', 4));+SELECT pg_temp.expect('regex character is literal', NULL::bigint, util.document_sequence_number('QX(0042)-26', 'Q.(', ')-%{yy}', 4));+SELECT pg_temp.expect('too long for bigint', NULL::bigint, util.document_sequence_number('SO99999999999999999999', 'SO', NULL, 6));++-- Saving a sales order moves its company's counter.+CREATE TEMP TABLE picked AS+SELECT "id", "companyId" FROM "salesOrder" ORDER BY "createdAt" LIMIT 1;++UPDATE "sequence" SET "prefix" = 'SO', "suffix" = NULL, "size" = 6, "next" = 10+WHERE "table" = 'salesOrder' AND "companyId" = (SELECT "companyId" FROM picked);++CREATE FUNCTION pg_temp.next_of(sequence_table text) RETURNS integer LANGUAGE sql AS $fn$+ SELECT "next" FROM "sequence"+ WHERE "table" = sequence_table AND "companyId" = (SELECT "companyId" FROM picked)+$fn$;++UPDATE "salesOrder" SET "salesOrderId" = 'SO000500' WHERE "id" = (SELECT "id" FROM picked);+SELECT pg_temp.expect('a higher number moves the counter', 500, pg_temp.next_of('salesOrder'));++UPDATE "salesOrder" SET "salesOrderId" = 'ACME-77' WHERE "id" = (SELECT "id" FROM picked);+SELECT pg_temp.expect('a custom id leaves it', 500, pg_temp.next_of('salesOrder'));++UPDATE "salesOrder" SET "salesOrderId" = 'SO000300' WHERE "id" = (SELECT "id" FROM picked);+SELECT pg_temp.expect('a lower number leaves it', 500, pg_temp.next_of('salesOrder'));++SELECT pg_temp.expect(+ 'the next number issued is past it',+ 'SO000501',+ get_next_sequence('salesOrder', (SELECT "companyId" FROM picked))+);++-- A counter past its size is issued in full, not truncated to the size.+UPDATE "sequence" SET "next" = 999999+WHERE "table" = 'salesOrder' AND "companyId" = (SELECT "companyId" FROM picked);+SELECT pg_temp.expect(+ 'a number longer than the size is not truncated',+ 'SO1000000',+ get_next_sequence('salesOrder', (SELECT "companyId" FROM picked))+);+UPDATE "sequence" SET "next" = 501+WHERE "table" = 'salesOrder' AND "companyId" = (SELECT "companyId" FROM picked);++-- A memo's direction picks its sequence.+UPDATE "sequence" SET "prefix" = 'CM', "suffix" = NULL, "size" = 6, "next" = 1+WHERE "table" = 'creditMemo' AND "companyId" = (SELECT "companyId" FROM picked);+UPDATE "sequence" SET "prefix" = 'DM', "suffix" = NULL, "size" = 6, "next" = 1+WHERE "table" = 'debitMemo' AND "companyId" = (SELECT "companyId" FROM picked);++SELECT sync_advance_document_sequence('memo', 'INSERT',+ jsonb_build_object('companyId', (SELECT "companyId" FROM picked), 'memoId', 'DM000040', 'direction', 'Debit'), NULL);+SELECT sync_advance_document_sequence('memo', 'INSERT',+ jsonb_build_object('companyId', (SELECT "companyId" FROM picked), 'memoId', 'CM000020', 'direction', 'Credit'), NULL);+SELECT pg_temp.expect('a debit memo moves debitMemo', 40, pg_temp.next_of('debitMemo'));+SELECT pg_temp.expect('a credit memo moves creditMemo', 20, pg_temp.next_of('creditMemo'));++-- A journal's counter is journalEntry, not journal.+UPDATE "sequence" SET "prefix" = 'JE-%{yyyy}-%{mm}-', "suffix" = NULL, "size" = 6, "next" = 1+WHERE "table" = 'journalEntry' AND "companyId" = (SELECT "companyId" FROM picked);+SELECT sync_advance_document_sequence('journal', 'INSERT',+ jsonb_build_object('companyId', (SELECT "companyId" FROM picked), 'journalEntryId', 'JE-2026-10-000077'), NULL);+SELECT pg_temp.expect('a journal moves journalEntry', 77, pg_temp.next_of('journalEntry'));++-- A delete never moves a counter.+SELECT sync_advance_document_sequence('salesOrder', 'DELETE', NULL,+ jsonb_build_object('companyId', (SELECT "companyId" FROM picked), 'salesOrderId', 'SO009999'));+SELECT pg_temp.expect('a delete leaves it', 501, pg_temp.next_of('salesOrder'));++\echo 'document-sequence: all checks passed'+ROLLBACK;