@happyvertical/smrt-commerce 0.66.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Post issued invoices into the tenant's settlement chart, and sweep up the
3
+ * ones that were never posted.
4
+ *
5
+ * `Invoice.recognizeRevenue` posts one balanced journal per frozen invoice
6
+ * snapshot and links it as `arJournalId`, so everything here is idempotent.
7
+ * {@link postInvoiceRevenueToSettlementChart} wires it to the chart from
8
+ * `ensureTenantSettlementAccounts`; {@link postPendingInvoiceRevenue} is the
9
+ * repair for invoices issued before posting existed or whose post failed.
10
+ *
11
+ * Both open their own money transaction: call them outside a model
12
+ * transaction, as `ensureTenantSettlementAccounts`.
13
+ */
14
+ import type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';
15
+ export interface PostInvoiceRevenueResult {
16
+ /** True when this call posted the journal. */
17
+ readonly posted: boolean;
18
+ /** The invoice's revenue journal, or null when it is not postable. */
19
+ readonly journalId: string | null;
20
+ }
21
+ /**
22
+ * Post one issued invoice's revenue journal (Dr receivables / Cr revenue / Cr
23
+ * tax) into the tenant's settlement chart for the invoice currency.
24
+ *
25
+ * Idempotent: an invoice that already links a journal returns it unchanged.
26
+ * Drafts, cancelled and written-off invoices are skipped. If a cancellation
27
+ * commits between the read and the post, the new journal is reversed so a
28
+ * cancelled invoice never keeps receivables.
29
+ */
30
+ export declare function postInvoiceRevenueToSettlementChart(db: DatabaseInterface, tenantId: string, invoiceId: string): Promise<PostInvoiceRevenueResult>;
31
+ /**
32
+ * One page of unposted, issued invoice ids after `after`, ordered by id.
33
+ *
34
+ * Raw SQL, because an unposted invoice stores either NULL or '' in
35
+ * `ar_journal_id` and the collection filter cannot match both. Id columns are
36
+ * cast to text so the same statement runs on PostgreSQL (UUID columns) and
37
+ * SQLite (text).
38
+ *
39
+ * @internal exported for the PostgreSQL-dialect test.
40
+ */
41
+ export declare function selectUnpostedInvoiceIds(db: DatabaseInterface, tenantId: string, after: string | null, limit: number): Promise<{
42
+ id: string;
43
+ }[]>;
44
+ /**
45
+ * One page of cancelled invoices that still carry a revenue journal but no
46
+ * reversal, after `after`, ordered by id. Same casts as
47
+ * {@link selectUnpostedInvoiceIds}.
48
+ *
49
+ * @internal exported for the PostgreSQL-dialect test.
50
+ */
51
+ export declare function selectCancelledUnreversedInvoiceIds(db: DatabaseInterface, tenantId: string, after: string | null, limit: number): Promise<{
52
+ id: string;
53
+ }[]>;
54
+ /**
55
+ * Reverse the revenue journal of a cancelled invoice that still carries one.
56
+ * Idempotent: the reversal is a deterministic journal, and an invoice that is
57
+ * not cancelled, has no journal, or is already reversed is left alone.
58
+ */
59
+ export declare function reverseCancelledInvoiceRevenue(db: DatabaseInterface, tenantId: string, invoiceId: string): Promise<{
60
+ reversed: boolean;
61
+ }>;
62
+ export interface PostPendingInvoiceRevenueOptions {
63
+ /** Invoices per page (1-200, default 50). */
64
+ readonly limit?: number;
65
+ /** Pages per call (default 20). A larger backlog returns `nextCursor`. */
66
+ readonly maxPages?: number;
67
+ /** Resume from a previous call's `nextCursor`. */
68
+ readonly cursor?: string | null;
69
+ /** Called with the invoice id and error when one invoice fails. */
70
+ readonly onError?: (invoiceId: string, error: unknown) => void;
71
+ }
72
+ export interface PostPendingInvoiceRevenueResult {
73
+ /** Invoices posted by this call. */
74
+ readonly posted: number;
75
+ /** Cancelled invoices whose revenue journal this call reversed. */
76
+ readonly reversed: number;
77
+ /** Invoices whose post or reversal threw; the rest of the batch still ran. */
78
+ readonly failed: number;
79
+ /**
80
+ * Pass back as `options.cursor` to continue past this call's page budget, so
81
+ * invoices that fail every run cannot starve the ones after them. Null when
82
+ * the scan finished.
83
+ */
84
+ readonly nextCursor: string | null;
85
+ }
86
+ /**
87
+ * Repair: bring the tenant's books in line with its invoices.
88
+ *
89
+ * Two phases, each filtered in the query before paging so settled invoices
90
+ * never consume the scan: (1) cancelled invoices that still carry a revenue
91
+ * journal get it reversed (a cancel that raced a post, or a reversal that
92
+ * failed); (2) issued, non-cancelled, non-written-off invoices with no journal
93
+ * get posted. A paid invoice whose payment settled before posting existed is
94
+ * balanced by its new journal. Safe to repeat and to run concurrently: posting
95
+ * and reversal are keyed on the invoice and its snapshot.
96
+ *
97
+ * One call scans up to `maxPages` pages. If it stops there, `nextCursor`
98
+ * resumes where it left off; an invoice that fails stays unposted but the
99
+ * cursor moves past it, so it cannot starve later ones.
100
+ */
101
+ export declare function postPendingInvoiceRevenue(db: DatabaseInterface, tenantId: string, options?: PostPendingInvoiceRevenueOptions): Promise<PostPendingInvoiceRevenueResult>;
102
+ //# sourceMappingURL=invoice-revenue-sweep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoice-revenue-sweep.d.ts","sourceRoot":"","sources":["../src/invoice-revenue-sweep.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAmB7E,MAAM,WAAW,wBAAwB;IACvC,8CAA8C;IAC9C,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,sEAAsE;IACtE,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED;;;;;;;;GAQG;AACH,wBAAsB,mCAAmC,CACvD,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,wBAAwB,CAAC,CAmCnC;AAED;;;;;;;;;GASG;AACH,wBAAsB,wBAAwB,CAC5C,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,CAe3B;AAED;;;;;;GAMG;AACH,wBAAsB,mCAAmC,CACvD,EAAE,EAAE,iBAAiB,EACrB,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",
5
- "packageVersion": "0.66.0",
5
+ "packageVersion": "0.67.0",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-commerce:Payout": {
8
8
  "name": "payout",
@@ -4420,7 +4420,7 @@
4420
4420
  ],
4421
4421
  "schema": {
4422
4422
  "tableName": "accounting_payment_syncs",
4423
- "ddl": "CREATE TABLE IF NOT EXISTS \"accounting_payment_syncs\" (\n \"_sync_origin_device_id\" TEXT,\n \"_sync_revision\" INTEGER,\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"tenant_id\" UUID NOT NULL,\n \"provider\" TEXT DEFAULT 'quickbooks',\n \"realm_id\" TEXT DEFAULT '',\n \"environment\" TEXT DEFAULT 'sandbox',\n \"payment_id\" TEXT DEFAULT '',\n \"status\" TEXT DEFAULT 'in_flight',\n \"request_id\" TEXT DEFAULT '',\n \"attempt_id\" TEXT DEFAULT '',\n \"payload_hash\" TEXT DEFAULT '',\n \"request_json\" TEXT,\n \"external_id\" TEXT DEFAULT '',\n \"synced_at\" TIMESTAMP,\n \"started_at\" TIMESTAMP,\n \"last_error\" TEXT DEFAULT ''\n);",
4423
+ "ddl": "CREATE TABLE IF NOT EXISTS \"accounting_payment_syncs\" (\n \"_sync_origin_device_id\" TEXT,\n \"_sync_revision\" INTEGER,\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"tenant_id\" UUID NOT NULL,\n \"provider\" TEXT DEFAULT 'quickbooks',\n \"realm_id\" TEXT DEFAULT '',\n \"environment\" TEXT DEFAULT 'sandbox',\n \"payment_id\" TEXT DEFAULT '',\n \"status\" TEXT DEFAULT 'in_flight',\n \"request_id\" TEXT DEFAULT '',\n \"attempt_id\" TEXT DEFAULT '',\n \"payload_hash\" TEXT DEFAULT '',\n \"request_json\" TEXT,\n \"external_id\" TEXT DEFAULT '',\n \"synced_at\" TIMESTAMP,\n \"started_at\" TIMESTAMP,\n \"last_error\" TEXT DEFAULT '',\n \"pinned_request_id\" TEXT DEFAULT ''\n);",
4424
4424
  "columns": {
4425
4425
  "_sync_origin_device_id": {
4426
4426
  "type": "TEXT"
@@ -4533,6 +4533,12 @@
4533
4533
  "notNull": false,
4534
4534
  "unique": false,
4535
4535
  "default": ""
4536
+ },
4537
+ "pinned_request_id": {
4538
+ "type": "TEXT",
4539
+ "notNull": false,
4540
+ "unique": false,
4541
+ "default": ""
4536
4542
  }
4537
4543
  },
4538
4544
  "indexes": [
@@ -4564,7 +4570,7 @@
4564
4570
  ]
4565
4571
  }
4566
4572
  ],
4567
- "version": "72bbd03c"
4573
+ "version": "8000dcd4"
4568
4574
  },
4569
4575
  "importPath": "@happyvertical/smrt-commerce"
4570
4576
  },
@@ -13356,6 +13362,16 @@
13356
13362
  },
13357
13363
  "required": false,
13358
13364
  "default": ""
13365
+ },
13366
+ "pinnedRequestId": {
13367
+ "type": "text",
13368
+ "_meta": {
13369
+ "__statedOptions": [
13370
+ "default"
13371
+ ]
13372
+ },
13373
+ "required": false,
13374
+ "default": ""
13359
13375
  }
13360
13376
  },
13361
13377
  "methods": {
@@ -13437,7 +13453,7 @@
13437
13453
  "validationRules": [],
13438
13454
  "schema": {
13439
13455
  "tableName": "accounting_payment_syncs",
13440
- "ddl": "CREATE TABLE IF NOT EXISTS \"accounting_payment_syncs\" (\n \"_sync_origin_device_id\" TEXT,\n \"_sync_revision\" INTEGER,\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"tenant_id\" UUID NOT NULL,\n \"provider\" TEXT DEFAULT 'quickbooks',\n \"realm_id\" TEXT DEFAULT '',\n \"environment\" TEXT DEFAULT 'sandbox',\n \"payment_id\" TEXT DEFAULT '',\n \"status\" TEXT DEFAULT 'in_flight',\n \"request_id\" TEXT DEFAULT '',\n \"attempt_id\" TEXT DEFAULT '',\n \"payload_hash\" TEXT DEFAULT '',\n \"request_json\" TEXT,\n \"external_id\" TEXT DEFAULT '',\n \"synced_at\" TIMESTAMP,\n \"started_at\" TIMESTAMP,\n \"last_error\" TEXT DEFAULT ''\n);",
13456
+ "ddl": "CREATE TABLE IF NOT EXISTS \"accounting_payment_syncs\" (\n \"_sync_origin_device_id\" TEXT,\n \"_sync_revision\" INTEGER,\n \"id\" UUID PRIMARY KEY NOT NULL,\n \"slug\" TEXT NOT NULL,\n \"context\" TEXT NOT NULL DEFAULT '',\n \"created_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"updated_at\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\n \"tenant_id\" UUID NOT NULL,\n \"provider\" TEXT DEFAULT 'quickbooks',\n \"realm_id\" TEXT DEFAULT '',\n \"environment\" TEXT DEFAULT 'sandbox',\n \"payment_id\" TEXT DEFAULT '',\n \"status\" TEXT DEFAULT 'in_flight',\n \"request_id\" TEXT DEFAULT '',\n \"attempt_id\" TEXT DEFAULT '',\n \"payload_hash\" TEXT DEFAULT '',\n \"request_json\" TEXT,\n \"external_id\" TEXT DEFAULT '',\n \"synced_at\" TIMESTAMP,\n \"started_at\" TIMESTAMP,\n \"last_error\" TEXT DEFAULT '',\n \"pinned_request_id\" TEXT DEFAULT ''\n);",
13441
13457
  "columns": {
13442
13458
  "_sync_origin_device_id": {
13443
13459
  "type": "TEXT"
@@ -13550,6 +13566,12 @@
13550
13566
  "notNull": false,
13551
13567
  "unique": false,
13552
13568
  "default": ""
13569
+ },
13570
+ "pinned_request_id": {
13571
+ "type": "TEXT",
13572
+ "notNull": false,
13573
+ "unique": false,
13574
+ "default": ""
13553
13575
  }
13554
13576
  },
13555
13577
  "indexes": [
@@ -13581,7 +13603,7 @@
13581
13603
  ]
13582
13604
  }
13583
13605
  ],
13584
- "version": "72bbd03c"
13606
+ "version": "8000dcd4"
13585
13607
  },
13586
13608
  "importPath": "@happyvertical/smrt-commerce"
13587
13609
  },
@@ -36532,6 +36554,6 @@
36532
36554
  "@happyvertical/smrt-users"
36533
36555
  ]
36534
36556
  },
36535
- "schemaFingerprint": "f7b02174c7dfd9492d3e257fd672533ab962689fb2bb24fc34b1275528c6a5e4",
36557
+ "schemaFingerprint": "c7e31fa2261b32bb06af57e62d00821743a412882ca1a69216dbc31f1b7c9564",
36536
36558
  "stampsConstructors": true
36537
36559
  }
@@ -58,6 +58,12 @@ export declare class AccountingPaymentSync extends SmrtObject {
58
58
  startedAt: Date | null;
59
59
  /** Short error code of the last failure (never provider text). */
60
60
  lastError: string;
61
+ /**
62
+ * Request id of a push that was `unknown` and then released as absent at the
63
+ * provider. Never cleared: every later attempt must reuse it, because the
64
+ * provider dedups on it and the original may still land late.
65
+ */
66
+ pinnedRequestId: string;
61
67
  /** Refuses writes outside the commands and any change of key. */
62
68
  save(options?: SmrtSaveOptions): Promise<this>;
63
69
  /** Never deleted: it is the exactly-once record. */
@@ -1 +1 @@
1
- {"version":3,"file":"AccountingSyncRecords.d.ts","sourceRoot":"","sources":["../../src/models/AccountingSyncRecords.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAEL,KAAK,iBAAiB,EACtB,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EACV,+BAA+B,EAC/B,4BAA4B,EAC7B,MAAM,2BAA2B,CAAC;AAEnC;;;;GAIG;AACH,MAAM,MAAM,2BAA2B,GACnC,WAAW,GACX,SAAS,GACT,UAAU,GACV,QAAQ,CAAC;AAEb;;;;;;;;GAQG;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AO,EAAE,MAAM,CAAM;IAErB,0BAA0B;IAC1B,WAAW,EAAE,+BAA+B,CAAa;IAEzD,gCAAgC;IAChC,UAAU,EAAE,MAAM,CAAM;IAExB,qDAAqD;IACrD,MAAM,EAAE,wBAAwB,CAA0B;IAE1D,qFAAqF;IAErF,cAAc,EAAE,MAAM,CAAM;IAE5B,iEAAiE;IACjE,cAAc,EAAE,MAAM,CAAK;IAE3B,2FAA2F;IAE3F,gBAAgB,EAAE,MAAM,CAAM;IAE9B,kCAAkC;IAElC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAQ;IAE/B,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAM;IAEvB,2CAA2C;IAC5B,IAAI,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAU7D,qBAAqB;IACN,MAAM,CAAC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;CAGnE"}
@@ -3,12 +3,12 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-commerce",
6
- "packageVersion": "0.66.0",
6
+ "packageVersion": "0.67.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "0880d63c907e367e6e33743b4d49988ae60e43f2635ac235301052347d29d1c3",
11
- "packageJson": "605ac4a5a84172c21c638dcab7133e5f536891a2b275aa6138d77aaf1e3a52b5",
10
+ "manifest": "eac0725d5bac5fc5aafc090b146f232c85e7e1eba4334bde40425dc9648800ff",
11
+ "packageJson": "64c4460827ffe29e4873ac83561b3e940b900efcfc713b98a308b97f7f448627",
12
12
  "agents": "4891a1eb6aa2be45b8374d9bacdcda357bab45e184d9d756596985381f6de442",
13
13
  "moduleDoc:agents/customer-vendor-ui.md": "ee8cbe9b6c4334cb9d53c87258d20a6ec8abd042011135be75cb03d2198796cc",
14
14
  "moduleDoc:README.md": "06668f73dad1198089b4eef19a9a6ab8421825615c581cf66c593da32754f359",
@@ -17,7 +17,7 @@
17
17
  "moduleDoc:agents/accounting-connection.md": "f51b65f3995ed1173a4768ec6f03df7e5bca338d3a2e842770627690e6e51f0e",
18
18
  "moduleDoc:agents/accounting-mapping.md": "351e9ce6913a8ff9c5a90ccb76ac84c9022fcee574deeedcd2f7a08b959c8a41",
19
19
  "moduleDoc:agents/accounting-live-gate.md": "b2b27912d4154aa339272c3c0ffa3284ef9c4e35ec17fe2fe0925a18e359d288",
20
- "moduleDoc:agents/accounting-payment-sync.md": "ed7e1671be6da8ecf3972a52ab8d9bff778f828c5a996514d098833d5015a413",
20
+ "moduleDoc:agents/accounting-payment-sync.md": "08cb7f2d70864ba3a94213f6857c8bbc5ef63034376d56a1a1e600ff0cda91b3",
21
21
  "moduleDoc:agents/historical-sales.md": "d7e68bb3a93495c91449b7406a5eefdcddb54fafea83d14d5ba8e2c8d6168de4",
22
22
  "moduleDoc:agents/payment-allocations.md": "679894f603f62522515bce338741bafda3f10d16ef0b817b105dc2e732471fdb",
23
23
  "moduleDoc:agents/settlement-accounts.md": "a3ecc28f41d019f842d80ea752c503ebbe12418b809f2f85f9ff7f76ac48d976",
@@ -6666,6 +6666,13 @@
6666
6666
  "required": false,
6667
6667
  "columnType": "TEXT",
6668
6668
  "default": ""
6669
+ },
6670
+ {
6671
+ "name": "pinnedRequestId",
6672
+ "type": "text",
6673
+ "required": false,
6674
+ "columnType": "TEXT",
6675
+ "default": ""
6669
6676
  }
6670
6677
  ],
6671
6678
  "relationships": [],
@@ -23670,7 +23677,7 @@
23670
23677
  {
23671
23678
  "path": "agents/accounting-payment-sync.md",
23672
23679
  "module": "accounting-payment-sync",
23673
- "content": "# Payment sync, readback and batches (#5139)\n\nSource: `src/accounting-payment-sync.ts`, `src/models/AccountingSyncRecords.ts`.\n\n## Payment push\n\n`syncPaymentToAccounting({ db, tenantId, paymentId, payments, provider? })` (run\ninside the tenant context) pushes one recorded payment to the connected company,\napplied to its synced invoice(s) and deposited to the mapped clearing account\n(`deposit_account:default`). It requires:\n\n- a `completed`, non-refund `Payment` fully applied (`PaymentAllocation`s sum to\n the amount) to invoices that are **synced to the same company and\n environment** (`INVOICE_NOT_SYNCED` otherwise), one customer, one currency;\n- the `customer` and `deposit_account:default` mappings (`MAPPING_INCOMPLETE`\n lists what is missing);\n- live mode in production (see [live-mode gate](accounting-live-gate.md)).\n\nExactly once, same shape as the invoice path: `AccountingPaymentSync` is unique\nper `(tenant, provider, realm, environment, payment)`. The request id\n(`smrt_pay_<hash of the exact facts>`) and the request JSON are persisted as\n`in_flight` **before** the provider call. A definite rejection\n(`error.outcome === 'rejected'`) or a dead grant (`REAUTH_REQUIRED`: nothing was\nsent) becomes `rejected` and may be retried (an atomic conditional takeover, so\ntwo retries cannot both push). Any other failure is `unknown`: retry throws\n`RECONCILIATION_REQUIRED` until `reconcileAccountingPaymentSync` is given the\nprovider's authoritative lookup of that request (`found` completes it,\n`absent` makes it retryable; an interrupted `in_flight` row also needs\n`confirmInterruptedOwnerStopped`). Two concurrent calls: one pushes, the other\ngets `SYNC_IN_PROGRESS`. A synced payment returns `unchanged`.\n\nThe local `Payment` row is not edited; `AccountingPaymentSync.externalId` is the\nprovider id. Payments cannot be un-applied by this module: if allocations change\nafter the push, readback reports drift.\n\n### SDK seam (sdk#1540)\n\n`AccountingPaymentPort.create(request)` is the provider call; the host adapts\nthe SDK's payment creation to it (`requestId` is the idempotency key; throw an\nerror with `outcome: 'rejected'` on a definite refusal). smrt tests use fakes.\n\n## Readback\n\n`readbackInvoice({ db, tenantId, invoiceId, reader })` reads the provider\ndocument (and linked transactions) through `AccountingInvoiceReader`, projects\nit with the pilot's `projectQuickBooksPilotEvidence` (balance, paid, credited,\nrefunded, state, transactions) and stores it in `AccountingInvoiceReadback`\n(unique per invoice) with a status:\n\n| status | when |\n|---|---|\n| `in_step` | provider paid amount equals Commerce's (completed allocations), no provider-only payment |\n| `drift` | `PAID_AMOUNT_DIFFERS`, `PROVIDER_ONLY_PAYMENT` (a payment recorded only in the provider; ids in `providerOnlyJson`), or `VOIDED_IN_PROVIDER` |\n| `needs_reconciliation` | evidence incomplete or inconsistent, scope or total mismatch, or the read failed |\n\nReads only; it never writes to the provider and never creates a Work payment\nfrom a provider-only one (Epic J decision J-e).\n\n## Batches\n\nBoth are bounded (`limit` default 25, max 100) and resumable (`cursor` in,\n`nextCursor` out; `null` at the end), so a job only schedules and locks:\n\n- `syncPending({ db, tenantId, provider, payments, limit?, cursor?, customers? })`:\n pushes pending frozen invoices and credit notes (built with\n `buildFrozenInvoiceMapping`), then payments whose invoices are synced. Items\n report `synced | unchanged | skipped | failed` with a code. A missing mapping\n or unsynced source skips the item; a closed live gate or dead connection stops\n the batch. `customers` (directory + describe) resolves missing customer\n mappings; an ambiguous match is skipped, never created.\n- `readbackDue({ db, tenantId, reader, limit?, olderThan?, cursor?, now? })`:\n reads synced invoices never read or last read before `olderThan` (default 15\n minutes).\n\nInvoices with retention or ordinary-accounting state keep their own commands and\nare not picked up by `syncPending`.\n\n## Provider adapters (#5154)\n\n`src/accounting-provider-adapters.ts` adapts the provider that\n`withTenantQuickBooksProvider` hands you to the injected ports, typed\nstructurally against the SDK operations (no SDK bump needed):\n`paymentPortFromProvider(provider)` (sdk#1540: minor to major units, `requestId`\nforwarded as the QuickBooks `requestid`, unknown currency refused, write errors\npass through), `invoiceReaderFromProvider(provider, tenantId)` (sdk#1548) and\n`customerDirectoryFromProvider(provider)` (sdk#1539; `create` never creates over\na match and throws `CUSTOMER_NEEDS_CONFIRMATION`). A provider without the\noperation fails the call with a plain error.\n"
23680
+ "content": "# Payment sync, readback and batches (#5139)\n\nSource: `src/accounting-payment-sync.ts`, `src/models/AccountingSyncRecords.ts`.\n\n## Payment push\n\n`syncPaymentToAccounting({ db, tenantId, paymentId, payments, provider? })` (run\ninside the tenant context) pushes one recorded payment to the connected company,\napplied to its synced invoice(s) and deposited to the mapped clearing account\n(`deposit_account:default`). It requires:\n\n- a `completed`, non-refund `Payment` fully applied (`PaymentAllocation`s sum to\n the amount) to invoices that are **synced to the same company and\n environment** (`INVOICE_NOT_SYNCED` otherwise), one customer, one currency;\n- the `customer` and `deposit_account:default` mappings (`MAPPING_INCOMPLETE`\n lists what is missing);\n- live mode in production (see [live-mode gate](accounting-live-gate.md)).\n\nExactly once, same shape as the invoice path: `AccountingPaymentSync` is unique\nper `(tenant, provider, realm, environment, payment)`. The request id\n(`smrt_pay_<hash of the exact facts>`) and the request JSON are persisted as\n`in_flight` **before** the provider call. A definite rejection\n(`error.outcome === 'rejected'`) or a dead grant (`REAUTH_REQUIRED`: nothing was\nsent) becomes `rejected` and may be retried (an atomic conditional takeover, so\ntwo retries cannot both push). Any other failure is `unknown`: retry throws\n`RECONCILIATION_REQUIRED` until `reconcileAccountingPaymentSync` is given the\nprovider's authoritative lookup of that request (`found` completes it,\n`absent` makes it retryable; an interrupted `in_flight` row also needs\n`confirmInterruptedOwnerStopped`). Two concurrent calls: one pushes, the other\ngets `SYNC_IN_PROGRESS`. A synced payment returns `unchanged`.\n\nA failure before anything reached the provider (the facts cannot form a valid\nprovider request, or the provider has no payment creation) is a known non-send:\nthrow `AccountingPaymentNotSentError(reason, message)` from the port and the row\nbecomes a retryable `rejected` whose `lastError` is that stable code\n(`INVALID_PROVIDER_REQUEST`, `PROVIDER_UNSUPPORTED`; the batch item reports it as\n`reason`). Only a failure after the provider may have received the request is\n`unknown`.\n\n`resolveUnknownPaymentSync({ db, tenantId, paymentId, reader })` recovers an\n`unknown` row without hand-written SQL: it reads every applied invoice through\nthe `AccountingInvoiceReader`; none with a provider payment means the push never\nlanded, so it applies `reconcileAccountingPaymentSync` `absent` and returns\n`retryable` (the next `syncPending` pushes it, with the same `requestid`); any\nprovider payment (other than ones this tenant already synced) returns\n`ambiguous` with their ids and leaves the row `unknown` for a person (a provider\npayment cannot be attributed to this push from the document). Absence is proven\nonly by a complete read of this company's invoice: a partial read or one for\nanother realm, tenant or invoice returns `inconclusive`. A failed read throws\nand changes nothing. A released push keeps its request id for good\n(`pinnedRequestId`, set by the release and never cleared, enforced in the\natomic takeover) so the provider's dedup still covers a slow original; if the\nfacts changed since, every later retry throws `RECONCILIATION_REQUIRED` and\nsends nothing.\n\nThe local `Payment` row is not edited; `AccountingPaymentSync.externalId` is the\nprovider id. Payments cannot be un-applied by this module: if allocations change\nafter the push, readback reports drift.\n\n### SDK seam (sdk#1540)\n\n`AccountingPaymentPort.create(request)` is the provider call; the host adapts\nthe SDK's payment creation to it (`requestId` is the idempotency key; throw an\nerror with `outcome: 'rejected'` on a definite refusal). The optional\n`prepare(request)` returns the provider's own `payloadHash`, persisted before the\npush: QuickBooks verifies it against the exact mapped payload, which only the\nprovider can compute (`paymentPortFromProvider` implements it with\n`prepareQuickBooksPaymentRequest`; without it the SDK throws \"payload mismatch\"\nbefore any network call, #5420). `accounting-payment-sync.test.ts` runs commerce\nthrough the real SDK payment operations.\n\n## Readback\n\n`readbackInvoice({ db, tenantId, invoiceId, reader })` reads the provider\ndocument (and linked transactions) through `AccountingInvoiceReader`, projects\nit with the pilot's `projectQuickBooksPilotEvidence` (balance, paid, credited,\nrefunded, state, transactions) and stores it in `AccountingInvoiceReadback`\n(unique per invoice) with a status:\n\n| status | when |\n|---|---|\n| `in_step` | provider paid amount equals Commerce's (completed allocations), no provider-only payment |\n| `drift` | `PAID_AMOUNT_DIFFERS`, `PROVIDER_ONLY_PAYMENT` (a payment recorded only in the provider; ids in `providerOnlyJson`), or `VOIDED_IN_PROVIDER` |\n| `needs_reconciliation` | evidence incomplete or inconsistent, scope or total mismatch, or the read failed |\n\nReads only; it never writes to the provider and never creates a Work payment\nfrom a provider-only one (Epic J decision J-e).\n\n## Batches\n\nBoth are bounded (`limit` default 25, max 100) and resumable (`cursor` in,\n`nextCursor` out; `null` at the end), so a job only schedules and locks:\n\n- `syncPending({ db, tenantId, provider, payments, limit?, cursor?, customers? })`:\n pushes pending frozen invoices and credit notes (built with\n `buildFrozenInvoiceMapping`), then payments whose invoices are synced. Items\n report `synced | unchanged | skipped | failed` with a code. A missing mapping\n or unsynced source skips the item; a closed live gate or dead connection stops\n the batch. `customers` (directory + describe) resolves missing customer\n mappings; an ambiguous match is skipped, never created.\n- `readbackDue({ db, tenantId, reader, limit?, olderThan?, cursor?, now? })`:\n reads synced invoices never read or last read before `olderThan` (default 15\n minutes).\n\nInvoices with retention or ordinary-accounting state keep their own commands and\nare not picked up by `syncPending`.\n\n## Provider adapters (#5154)\n\n`src/accounting-provider-adapters.ts` adapts the provider that\n`withTenantQuickBooksProvider` hands you to the injected ports, typed\nstructurally against the SDK operations (no SDK bump needed):\n`paymentPortFromProvider(provider)` (sdk#1540: minor to major units, `requestId`\nforwarded as the QuickBooks `requestid`, unknown currency refused, write errors\npass through), `invoiceReaderFromProvider(provider, tenantId)` (sdk#1548) and\n`customerDirectoryFromProvider(provider)` (sdk#1539; `create` never creates over\na match and throws `CUSTOMER_NEEDS_CONFIRMATION`). A provider without the\noperation fails the call with a plain error.\n"
23674
23681
  },
23675
23682
  {
23676
23683
  "path": "agents/historical-sales.md",
@@ -5,10 +5,10 @@ description: "Commerce models for the SMRT framework - contracts, fulfillments,
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-21T00:43:48Z"
8
+ at: "2026-11-21T06:49:11Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:0c9262d63468ada343193a6e373998110623b9d92009cda17296c9b1cc814f27"
11
+ source_revision: "sha256:2d523446d14971894b4edb4658d95b87fe4289fe597e1c25c50f0cbcf47e3c09"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/commerce/package.json"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-commerce",
3
- "version": "0.66.0",
3
+ "version": "0.67.0",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Commerce models for the SMRT framework - contracts, fulfillments, payments",
6
6
  "type": "module",
@@ -65,18 +65,18 @@
65
65
  "dependencies": {
66
66
  "@happyvertical/accounting": "^0.116.6",
67
67
  "@happyvertical/payments": "^0.116.6",
68
- "@happyvertical/smrt-agents": "0.66.0",
69
- "@happyvertical/smrt-core": "0.66.0",
70
- "@happyvertical/smrt-jobs": "0.66.0",
71
- "@happyvertical/smrt-ledgers": "0.66.0",
72
- "@happyvertical/smrt-products": "0.66.0",
73
- "@happyvertical/smrt-profiles": "0.66.0",
74
- "@happyvertical/smrt-reports": "0.66.0",
75
- "@happyvertical/smrt-subscriptions": "0.66.0",
76
- "@happyvertical/smrt-svelte": "0.66.0",
77
- "@happyvertical/smrt-tenancy": "0.66.0",
78
- "@happyvertical/smrt-types": "0.66.0",
79
- "@happyvertical/smrt-ui": "0.66.0",
68
+ "@happyvertical/smrt-agents": "0.67.0",
69
+ "@happyvertical/smrt-core": "0.67.0",
70
+ "@happyvertical/smrt-jobs": "0.67.0",
71
+ "@happyvertical/smrt-ledgers": "0.67.0",
72
+ "@happyvertical/smrt-products": "0.67.0",
73
+ "@happyvertical/smrt-profiles": "0.67.0",
74
+ "@happyvertical/smrt-reports": "0.67.0",
75
+ "@happyvertical/smrt-subscriptions": "0.67.0",
76
+ "@happyvertical/smrt-svelte": "0.67.0",
77
+ "@happyvertical/smrt-tenancy": "0.67.0",
78
+ "@happyvertical/smrt-types": "0.67.0",
79
+ "@happyvertical/smrt-ui": "0.67.0",
80
80
  "@happyvertical/sql": "^0.116.6"
81
81
  },
82
82
  "peerDependencies": {
@@ -88,7 +88,7 @@
88
88
  }
89
89
  },
90
90
  "devDependencies": {
91
- "@happyvertical/smrt-vitest": "0.66.0",
91
+ "@happyvertical/smrt-vitest": "0.67.0",
92
92
  "@sveltejs/package": "^2.5.8",
93
93
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
94
94
  "@testing-library/jest-dom": "^7.0.1",