@happyvertical/smrt-commerce 0.56.0 → 0.56.2

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.
Files changed (213) hide show
  1. package/AGENTS.md +9 -8
  2. package/README.md +98 -4
  3. package/agents/accounting-snapshot-mapper.md +111 -0
  4. package/agents/contract-money.md +24 -0
  5. package/agents/cost-billing.md +7 -2
  6. package/agents/customer-vendor-ui.md +7 -1
  7. package/agents/document-money.md +127 -0
  8. package/agents/invoice-calculations.md +14 -2
  9. package/agents/line-amount-migration.md +50 -0
  10. package/agents/minor-unit-migration.md +20 -0
  11. package/agents/money-calculator.md +45 -0
  12. package/agents/money-model.md +113 -0
  13. package/agents/revenue-journal.md +23 -0
  14. package/agents/tax-codes.md +48 -0
  15. package/agents/tax-summary.md +128 -0
  16. package/dist/accounting-snapshot.d.ts +79 -0
  17. package/dist/accounting-snapshot.d.ts.map +1 -0
  18. package/dist/billing/runtime.d.ts +2 -0
  19. package/dist/billing/runtime.d.ts.map +1 -1
  20. package/dist/chunks/ContractLineItemCollection--BrGMtNz.js +265 -0
  21. package/dist/chunks/ContractLineItemCollection--BrGMtNz.js.map +1 -0
  22. package/dist/chunks/CustomerCollection-CjGaZSpf.js +99 -0
  23. package/dist/chunks/CustomerCollection-CjGaZSpf.js.map +1 -0
  24. package/dist/chunks/DocumentTaxCollection-KOkaQT2M.js +1659 -0
  25. package/dist/chunks/DocumentTaxCollection-KOkaQT2M.js.map +1 -0
  26. package/dist/chunks/InvoiceCollection-BUe_8FT1.js +1047 -0
  27. package/dist/chunks/InvoiceCollection-BUe_8FT1.js.map +1 -0
  28. package/dist/chunks/InvoiceLineItemCollection-CPQGghyd.js +468 -0
  29. package/dist/chunks/InvoiceLineItemCollection-CPQGghyd.js.map +1 -0
  30. package/dist/chunks/TaxCodeCollection-DF2eaJed.js +149 -0
  31. package/dist/chunks/TaxCodeCollection-DF2eaJed.js.map +1 -0
  32. package/dist/chunks/TaxComponentCollection-3x24xSNh.js +129 -0
  33. package/dist/chunks/TaxComponentCollection-3x24xSNh.js.map +1 -0
  34. package/dist/chunks/TaxSettingsCollection-DYYF-In-.js +319 -0
  35. package/dist/chunks/TaxSettingsCollection-DYYF-In-.js.map +1 -0
  36. package/dist/chunks/{money-DfrRxrel.js → allocation-integrity-Cq0g6CfO.js} +7 -12
  37. package/dist/chunks/allocation-integrity-Cq0g6CfO.js.map +1 -0
  38. package/dist/chunks/{calculations-Bz7RB3qK.js → calculations-DaHR17il.js} +134 -54
  39. package/dist/chunks/calculations-DaHR17il.js.map +1 -0
  40. package/dist/chunks/credit-allocation-yspz0Lab.js +121 -0
  41. package/dist/chunks/credit-allocation-yspz0Lab.js.map +1 -0
  42. package/dist/chunks/document-money-oUDvdjOf.js +860 -0
  43. package/dist/chunks/document-money-oUDvdjOf.js.map +1 -0
  44. package/dist/chunks/invoice-posting-CF3fE_Ec.js +229 -0
  45. package/dist/chunks/invoice-posting-CF3fE_Ec.js.map +1 -0
  46. package/dist/chunks/money-rational-CcW7gzG5.js +64 -0
  47. package/dist/chunks/money-rational-CcW7gzG5.js.map +1 -0
  48. package/dist/chunks/revenue-journal-DY9fro8E.js +140 -0
  49. package/dist/chunks/revenue-journal-DY9fro8E.js.map +1 -0
  50. package/dist/chunks/rolldown-runtime-D7D4PA-g.js +13 -0
  51. package/dist/chunks/tenant-money-barrier-y6EAa6vY.js +135 -0
  52. package/dist/chunks/tenant-money-barrier-y6EAa6vY.js.map +1 -0
  53. package/dist/chunks/{types-zVnIjSOk.js → types-Bbm0Xflc.js} +4 -14
  54. package/dist/chunks/types-Bbm0Xflc.js.map +1 -0
  55. package/dist/chunks/{units-BpZ0_Dpk.js → units-CNcjH_eE.js} +2 -2
  56. package/dist/chunks/{units-BpZ0_Dpk.js.map → units-CNcjH_eE.js.map} +1 -1
  57. package/dist/collections/ContractCollection.d.ts +35 -1
  58. package/dist/collections/ContractCollection.d.ts.map +1 -1
  59. package/dist/collections/ContractLineItemCollection.d.ts +26 -1
  60. package/dist/collections/ContractLineItemCollection.d.ts.map +1 -1
  61. package/dist/collections/DocumentTaxCollection.d.ts +75 -0
  62. package/dist/collections/DocumentTaxCollection.d.ts.map +1 -0
  63. package/dist/collections/InvoiceCollection.d.ts +26 -1
  64. package/dist/collections/InvoiceCollection.d.ts.map +1 -1
  65. package/dist/collections/InvoiceLineItemCollection.d.ts +26 -1
  66. package/dist/collections/InvoiceLineItemCollection.d.ts.map +1 -1
  67. package/dist/collections/MoneyMigrationDocumentCollection.d.ts +12 -0
  68. package/dist/collections/MoneyMigrationDocumentCollection.d.ts.map +1 -0
  69. package/dist/collections/PaymentAllocationCollection.d.ts +2 -0
  70. package/dist/collections/PaymentAllocationCollection.d.ts.map +1 -1
  71. package/dist/collections/TaxCodeCollection.d.ts +7 -0
  72. package/dist/collections/TaxCodeCollection.d.ts.map +1 -0
  73. package/dist/collections/TaxComponentCollection.d.ts +6 -0
  74. package/dist/collections/TaxComponentCollection.d.ts.map +1 -0
  75. package/dist/collections/TaxSettingsCollection.d.ts +16 -0
  76. package/dist/collections/TaxSettingsCollection.d.ts.map +1 -0
  77. package/dist/collections/TaxSummaryReportCollection.d.ts +151 -0
  78. package/dist/collections/TaxSummaryReportCollection.d.ts.map +1 -0
  79. package/dist/collections/index.d.ts +6 -0
  80. package/dist/collections/index.d.ts.map +1 -1
  81. package/dist/commerce-money-tools.d.ts +9 -0
  82. package/dist/commerce-money-tools.d.ts.map +1 -0
  83. package/dist/contract-money.d.ts +27 -0
  84. package/dist/contract-money.d.ts.map +1 -0
  85. package/dist/cost-billing.d.ts +0 -1
  86. package/dist/cost-billing.d.ts.map +1 -1
  87. package/dist/cost-billing.js +10 -15
  88. package/dist/cost-billing.js.map +1 -1
  89. package/dist/credit-allocation.d.ts +48 -0
  90. package/dist/credit-allocation.d.ts.map +1 -0
  91. package/dist/document-money-internal.d.ts +44 -0
  92. package/dist/document-money-internal.d.ts.map +1 -0
  93. package/dist/document-money.d.ts +85 -0
  94. package/dist/document-money.d.ts.map +1 -0
  95. package/dist/index.d.ts +15 -4
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +5411 -4249
  98. package/dist/index.js.map +1 -1
  99. package/dist/invoice-accounting-sync.d.ts +96 -0
  100. package/dist/invoice-accounting-sync.d.ts.map +1 -0
  101. package/dist/invoice-mcp.d.ts +16 -0
  102. package/dist/invoice-mcp.d.ts.map +1 -0
  103. package/dist/invoice-posting.d.ts +9 -0
  104. package/dist/invoice-posting.d.ts.map +1 -0
  105. package/dist/invoice-record-screen.d.ts +60 -0
  106. package/dist/invoice-record-screen.d.ts.map +1 -0
  107. package/dist/invoices.d.ts +2 -0
  108. package/dist/invoices.d.ts.map +1 -1
  109. package/dist/invoices.js +3 -2
  110. package/dist/manifest.json +12804 -6095
  111. package/dist/migrations/commerceLineAmounts.d.ts +84 -0
  112. package/dist/migrations/commerceLineAmounts.d.ts.map +1 -0
  113. package/dist/migrations/partyLinks.d.ts.map +1 -1
  114. package/dist/models/Contract.d.ts +34 -4
  115. package/dist/models/Contract.d.ts.map +1 -1
  116. package/dist/models/ContractLineItem.d.ts +43 -6
  117. package/dist/models/ContractLineItem.d.ts.map +1 -1
  118. package/dist/models/Customer.d.ts +7 -0
  119. package/dist/models/Customer.d.ts.map +1 -1
  120. package/dist/models/DocumentTax.d.ts +50 -0
  121. package/dist/models/DocumentTax.d.ts.map +1 -0
  122. package/dist/models/Invoice.d.ts +46 -2
  123. package/dist/models/Invoice.d.ts.map +1 -1
  124. package/dist/models/InvoiceLineItem.d.ts +46 -5
  125. package/dist/models/InvoiceLineItem.d.ts.map +1 -1
  126. package/dist/models/MoneyMigrationDocument.d.ts +28 -0
  127. package/dist/models/MoneyMigrationDocument.d.ts.map +1 -0
  128. package/dist/models/Payment.d.ts +5 -1
  129. package/dist/models/Payment.d.ts.map +1 -1
  130. package/dist/models/PaymentAllocation.d.ts.map +1 -1
  131. package/dist/models/TaxCode.d.ts +22 -0
  132. package/dist/models/TaxCode.d.ts.map +1 -0
  133. package/dist/models/TaxComponent.d.ts +21 -0
  134. package/dist/models/TaxComponent.d.ts.map +1 -0
  135. package/dist/models/TaxSettings.d.ts +33 -0
  136. package/dist/models/TaxSettings.d.ts.map +1 -0
  137. package/dist/models/TaxSummaryReport.d.ts +35 -0
  138. package/dist/models/TaxSummaryReport.d.ts.map +1 -0
  139. package/dist/models/Vendor.d.ts +9 -0
  140. package/dist/models/Vendor.d.ts.map +1 -1
  141. package/dist/models/index.d.ts +7 -1
  142. package/dist/models/index.d.ts.map +1 -1
  143. package/dist/money-rational.d.ts +15 -0
  144. package/dist/money-rational.d.ts.map +1 -0
  145. package/dist/money.d.ts +106 -25
  146. package/dist/money.d.ts.map +1 -1
  147. package/dist/money.js +274 -0
  148. package/dist/money.js.map +1 -0
  149. package/dist/recipes.d.ts +15 -15
  150. package/dist/revenue-journal.d.ts +61 -0
  151. package/dist/revenue-journal.d.ts.map +1 -0
  152. package/dist/smrt-knowledge.json +9621 -7592
  153. package/dist/svelte/components/InvoiceActions.svelte +12 -0
  154. package/dist/svelte/components/InvoiceActions.svelte.d.ts +5 -0
  155. package/dist/svelte/components/InvoiceActions.svelte.d.ts.map +1 -1
  156. package/dist/svelte/components/InvoiceEditor.svelte +15 -1
  157. package/dist/svelte/components/InvoiceEditor.svelte.d.ts.map +1 -1
  158. package/dist/svelte/components/InvoiceLineItems.svelte +3 -3
  159. package/dist/svelte/components/InvoiceRecordScreen.svelte +94 -0
  160. package/dist/svelte/components/InvoiceRecordScreen.svelte.d.ts +21 -0
  161. package/dist/svelte/components/InvoiceRecordScreen.svelte.d.ts.map +1 -0
  162. package/dist/svelte/components/InvoiceTotals.svelte +2 -2
  163. package/dist/svelte/components/MoneyInvoiceEditor.svelte +282 -0
  164. package/dist/svelte/components/MoneyInvoiceEditor.svelte.d.ts +31 -0
  165. package/dist/svelte/components/MoneyInvoiceEditor.svelte.d.ts.map +1 -0
  166. package/dist/svelte/components/PurchaseOrderEditor.svelte +53 -1
  167. package/dist/svelte/components/PurchaseOrderEditor.svelte.d.ts +5 -0
  168. package/dist/svelte/components/PurchaseOrderEditor.svelte.d.ts.map +1 -1
  169. package/dist/svelte/components/QuoteEditor.svelte +54 -1
  170. package/dist/svelte/components/QuoteEditor.svelte.d.ts +5 -0
  171. package/dist/svelte/components/QuoteEditor.svelte.d.ts.map +1 -1
  172. package/dist/svelte/i18n.d.ts +16 -0
  173. package/dist/svelte/i18n.d.ts.map +1 -1
  174. package/dist/svelte/i18n.js +16 -0
  175. package/dist/svelte/index.d.ts +7 -2
  176. package/dist/svelte/index.d.ts.map +1 -1
  177. package/dist/svelte/index.js +4 -1
  178. package/dist/svelte/invoices/calculations.d.ts +7 -2
  179. package/dist/svelte/invoices/calculations.d.ts.map +1 -1
  180. package/dist/svelte/invoices/calculations.js +141 -47
  181. package/dist/svelte/invoices/money-editor.d.ts +123 -0
  182. package/dist/svelte/invoices/money-editor.d.ts.map +1 -0
  183. package/dist/svelte/invoices/money-editor.js +101 -0
  184. package/dist/svelte/invoices/types.d.ts +5 -1
  185. package/dist/svelte/invoices/types.d.ts.map +1 -1
  186. package/dist/svelte/purchasing-i18n.d.ts +5 -0
  187. package/dist/svelte/purchasing-i18n.d.ts.map +1 -1
  188. package/dist/svelte/purchasing-i18n.js +5 -0
  189. package/dist/svelte/quote-i18n.d.ts +5 -0
  190. package/dist/svelte/quote-i18n.d.ts.map +1 -1
  191. package/dist/svelte/quote-i18n.js +5 -0
  192. package/dist/tax/cookbook.d.ts +22 -0
  193. package/dist/tax/cookbook.d.ts.map +1 -0
  194. package/dist/tax/example-pack.d.ts +25 -0
  195. package/dist/tax/example-pack.d.ts.map +1 -0
  196. package/dist/tax/identity.d.ts +5 -0
  197. package/dist/tax/identity.d.ts.map +1 -0
  198. package/dist/tax/index.d.ts +4 -0
  199. package/dist/tax/index.d.ts.map +1 -0
  200. package/dist/tax/legacy.d.ts +48 -0
  201. package/dist/tax/legacy.d.ts.map +1 -0
  202. package/dist/tax-summary-report-adapter.d.ts +37 -0
  203. package/dist/tax-summary-report-adapter.d.ts.map +1 -0
  204. package/dist/tax-summary.d.ts +129 -0
  205. package/dist/tax-summary.d.ts.map +1 -0
  206. package/dist/tenant-money-barrier.d.ts +66 -0
  207. package/dist/tenant-money-barrier.d.ts.map +1 -0
  208. package/dist/types/index.d.ts +138 -1
  209. package/dist/types/index.d.ts.map +1 -1
  210. package/package.json +19 -11
  211. package/dist/chunks/calculations-Bz7RB3qK.js.map +0 -1
  212. package/dist/chunks/money-DfrRxrel.js.map +0 -1
  213. package/dist/chunks/types-zVnIjSOk.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DocumentTaxCollection-KOkaQT2M.js","names":[],"sources":["../../src/party-contacts.ts","../../src/models/Customer.ts","../../src/models/Vendor.ts","../../src/models/Contract.ts","../../src/collections/PurchaseContractCollection.ts","../../src/collections/SalesContractCollection.ts","../../src/collections/ContractCollection.ts","../../src/models/DocumentTax.ts","../../src/collections/DocumentTaxCollection.ts"],"sourcesContent":["/**\n * Contact rows for customers and vendors (#3501).\n *\n * `CustomerForm` and `VendorForm` (`./svelte`) post contacts as repeated\n * field names in DOM order, one value per row for each of `contactId`,\n * `contactName`, `contactLabel`, `contactEmail`, `contactPhone`, and\n * `contactAddress` (all overridable through the forms' `fieldNames`). The\n * helpers here read that payload, apply the native add/remove intents, and\n * write the rows to `Customer.contacts` / `Vendor.contacts`.\n *\n * @packageDocumentation\n */\n\nimport type { CustomerCollection } from './collections/CustomerCollection.js';\nimport type { VendorCollection } from './collections/VendorCollection.js';\nimport type { Customer } from './models/Customer.js';\nimport type { Vendor } from './models/Vendor.js';\nimport type { PartyContact } from './types/index.js';\n\n/** One submitted contact row, exactly as posted (untrimmed strings). */\nexport type PartyContactInput = Partial<PartyContact>;\n\n/** The text fields of a contact, which are also its error keys. */\nexport type PartyContactField = Exclude<keyof PartyContact, 'id'>;\n\n/** HTML names of the repeated contact fields; defaults match the forms. */\nexport interface PartyContactFieldNames {\n contactId: string;\n contactName: string;\n contactLabel: string;\n contactEmail: string;\n contactPhone: string;\n contactAddress: string;\n /** Hidden presence marker: the number of contact rows the form rendered. */\n contactCount: string;\n}\n\n/** Default contact field names, matching `DEFAULT_PARTY_FIELD_NAMES` in `./svelte`. */\nexport const DEFAULT_PARTY_CONTACT_FIELD_NAMES: PartyContactFieldNames = {\n contactId: 'contactId',\n contactName: 'contactName',\n contactLabel: 'contactLabel',\n contactEmail: 'contactEmail',\n contactPhone: 'contactPhone',\n contactAddress: 'contactAddress',\n contactCount: 'contactCount',\n};\n\n/** Maximum lengths, matching the form controls' `maxlength`. */\nexport const PARTY_CONTACT_MAX_LENGTHS: Readonly<\n Record<PartyContactField, number>\n> = {\n name: 160,\n label: 80,\n email: 320,\n phone: 80,\n address: 500,\n};\n\n/**\n * Per-row validation error codes, keyed by field. `unknown_contact` (on\n * `id`) means the posted id is not one of the party's saved contacts — a\n * stale or altered form; reload the party and show its current rows.\n */\nexport type PartyContactErrorCode =\n | 'too_long'\n | 'invalid_email'\n | 'unknown_contact';\n\n/** Errors for one submitted row; indexes match the submitted rows. */\nexport type PartyContactRowErrors = Partial<\n Record<PartyContactField | 'id', PartyContactErrorCode>\n>;\n\nconst FIELDS: readonly PartyContactField[] = [\n 'name',\n 'label',\n 'email',\n 'phone',\n 'address',\n];\n\n/** Thrown by {@link savePartyContacts} when any row is invalid; nothing is written. */\nexport class PartyContactValidationError extends Error {\n /** Errors aligned with the submitted rows; `undefined` for a valid row. */\n readonly errors: Array<PartyContactRowErrors | undefined>;\n\n constructor(errors: Array<PartyContactRowErrors | undefined>) {\n super('One or more contact rows are invalid');\n this.name = 'PartyContactValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Thrown by {@link readPartyContactRows} (and so {@link savePartyContacts}\n * given a form) when the posted contact payload cannot be trusted:\n * `missing` — no `contactCount` marker, so the editable contact block did\n * not render or was posted under other field names (treating that as \"no\n * contacts\" would delete them all); `misaligned` — the repeated fields or\n * the marker disagree on the row count. Nothing is written.\n */\nexport class PartyContactPayloadError extends Error {\n readonly reason: 'missing' | 'misaligned';\n\n constructor(reason: 'missing' | 'misaligned', message: string) {\n super(message);\n this.name = 'PartyContactPayloadError';\n this.reason = reason;\n }\n}\n\n/** Thrown by {@link savePartyContacts} when the party is not visible in the current tenant. */\nexport class PartyContactPartyNotFoundError extends Error {\n constructor(partyId: string) {\n super(`Customer or vendor ${partyId} was not found`);\n this.name = 'PartyContactPartyNotFoundError';\n }\n}\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Normalize stored contacts (an array, a JSON string, or nothing) into\n * well-formed {@link PartyContact} rows. Non-object entries and non-string\n * values are dropped; a row without an id is given one.\n */\nexport function normalizePartyContacts(value: unknown): PartyContact[] {\n let input = value;\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n return [];\n }\n }\n if (!Array.isArray(input)) return [];\n const contacts: PartyContact[] = [];\n for (const entry of input) {\n if (!entry || typeof entry !== 'object') continue;\n const row = entry as Record<string, unknown>;\n contacts.push({\n id: text(row.id) || globalThis.crypto.randomUUID(),\n name: text(row.name),\n label: text(row.label),\n email: text(row.email),\n phone: text(row.phone),\n address: text(row.address),\n });\n }\n return contacts;\n}\n\n/** Minimal form-data reader; `FormData` and `URLSearchParams` both satisfy it. */\nexport interface PartyContactFormSource {\n getAll(name: string): unknown[];\n}\n\n/**\n * Read the contact rows a party form posted, in DOM order. The editable\n * contact block always posts a `contactCount` marker with its row count, and\n * every row renders all six fields. A missing marker (the block did not\n * render, or `fieldNames` differ from the form's) or any disagreeing count\n * throws {@link PartyContactPayloadError}, so zero rows is only ever read\n * when the form really posted an empty contact list.\n */\nexport function readPartyContactRows(\n form: PartyContactFormSource,\n fieldNames: Partial<PartyContactFieldNames> = {},\n): PartyContactInput[] {\n const names = { ...DEFAULT_PARTY_CONTACT_FIELD_NAMES, ...fieldNames };\n const column = (name: string) => form.getAll(name).map(text);\n const columns = {\n id: column(names.contactId),\n name: column(names.contactName),\n label: column(names.contactLabel),\n email: column(names.contactEmail),\n phone: column(names.contactPhone),\n address: column(names.contactAddress),\n };\n const markers = column(names.contactCount);\n if (markers.length !== 1)\n throw new PartyContactPayloadError(\n markers.length === 0 ? 'missing' : 'misaligned',\n markers.length === 0\n ? `Contact payload has no ${names.contactCount} marker; the contact fields were not posted under these names`\n : `Contact payload has ${markers.length} ${names.contactCount} markers`,\n );\n const count = columns.id.length;\n if (markers[0] !== String(count))\n throw new PartyContactPayloadError(\n 'misaligned',\n `Contact payload is misaligned: ${names.contactCount} is ${markers[0]} but ${count} contact ids were posted`,\n );\n for (const [key, values] of Object.entries(columns)) {\n if (values.length !== count)\n throw new PartyContactPayloadError(\n 'misaligned',\n `Contact payload is misaligned: ${count} contact ids but ${values.length} ${key} values`,\n );\n }\n return columns.id.map((id, index) => ({\n id,\n name: columns.name[index],\n label: columns.label[index],\n email: columns.email[index],\n phone: columns.phone[index],\n address: columns.address[index],\n }));\n}\n\n/** Submitter values for the forms' native contact row actions. */\nexport interface PartyContactIntents {\n /** Defaults to the forms' `addContact`. */\n addIntent?: string;\n /** Parses a remove submitter into a row index; defaults to `removeContact:<index>`. */\n parseRemoveIntent?: (intent: string) => number | undefined;\n}\n\nfunction defaultParseRemoveIntent(intent: string): number | undefined {\n const match = /^removeContact:(\\d+)$/.exec(intent);\n return match ? Number(match[1]) : undefined;\n}\n\n/**\n * Apply an add or remove submitter to the posted rows and return the rows\n * to render back into the form. Nothing is persisted: a row action is a\n * round trip, and only the save intent writes. `handled` is `false` for any\n * other intent (including save), with the rows unchanged; when it is `true`,\n * render the returned rows and do not save.\n */\nexport function applyPartyContactIntent(\n rows: readonly PartyContactInput[],\n intent: string,\n intents: PartyContactIntents = {},\n): { contacts: PartyContactInput[]; handled: boolean } {\n if (intent === (intents.addIntent ?? 'addContact'))\n return { contacts: [...rows, {}], handled: true };\n const index = (intents.parseRemoveIntent ?? defaultParseRemoveIntent)(intent);\n // A stale index (the row is already gone) is still a remove: it must not\n // fall through to a save.\n if (index !== undefined)\n return {\n contacts: rows.filter((_, position) => position !== index),\n handled: true,\n };\n return { contacts: [...rows], handled: false };\n}\n\n// Deliberately permissive: one \"@\" with text on both sides and no spaces.\n// Deliverability is the caller's concern.\nconst EMAIL = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * Validate posted rows without persisting them. Returns the trimmed rows\n * that would be written (blank rows dropped) and, when any row is invalid,\n * errors aligned with the submitted rows. Ids are checked against the\n * party's saved contacts only by {@link savePartyContacts}.\n */\nexport function validatePartyContactRows(rows: readonly PartyContactInput[]): {\n contacts: PartyContactInput[];\n errors?: Array<PartyContactRowErrors | undefined>;\n} {\n const contacts: PartyContactInput[] = [];\n const errors: Array<PartyContactRowErrors | undefined> = [];\n let invalid = false;\n rows.forEach((row, index) => {\n const trimmed: PartyContactInput = { id: text(row.id).trim() };\n let rowErrors: PartyContactRowErrors | undefined;\n for (const field of FIELDS) {\n const value = text(row[field]).trim();\n trimmed[field] = value;\n if (value.length > PARTY_CONTACT_MAX_LENGTHS[field])\n rowErrors = { ...rowErrors, [field]: 'too_long' };\n }\n if (trimmed.email && !rowErrors?.email && !EMAIL.test(trimmed.email))\n rowErrors = { ...rowErrors, email: 'invalid_email' };\n errors[index] = rowErrors;\n if (rowErrors) invalid = true;\n if (FIELDS.some((field) => trimmed[field])) contacts.push(trimmed);\n });\n return invalid ? { contacts, errors } : { contacts };\n}\n\n/** Options for {@link savePartyContacts}. */\nexport interface SavePartyContactsOptions {\n /** Field names used to read a posted form; must match the form's `fieldNames`. */\n fieldNames?: Partial<PartyContactFieldNames>;\n /**\n * When set, the party must belong to this tenant. Use it to bind a form's\n * posted tenant to the loaded row in addition to the active tenant\n * context, which already scopes the lookup.\n */\n expectedTenantId?: string | null;\n}\n\n/**\n * Replace a customer's or vendor's contacts with the rows its form posted.\n *\n * Pass the posted `FormData` (with `options.fieldNames` when the form\n * overrides them): it is read with {@link readPartyContactRows}, so a payload\n * without the contact block's presence marker throws\n * {@link PartyContactPayloadError} instead of removing every contact. An\n * array is taken as rows the caller already read through that function.\n *\n * The party is loaded through `collection.get()`, so the active tenant\n * context scopes it: a party in another tenant is not found. Rows are\n * validated ({@link validatePartyContactRows}), blank rows dropped, kept\n * rows matched to saved contacts by id (new rows get a fresh id), and rows\n * that were not posted are removed. A posted id the party does not have is\n * an `unknown_contact` error. On any error nothing is written and a\n * {@link PartyContactValidationError} is thrown.\n *\n * This is a read-modify-write of one row: concurrent saves of the same party\n * are last-writer-wins, like any other field edit.\n *\n * @returns The saved contacts, in submitted order.\n */\nexport async function savePartyContacts(\n collection: CustomerCollection | VendorCollection,\n partyId: string,\n posted: PartyContactFormSource | readonly PartyContactInput[],\n options: SavePartyContactsOptions = {},\n): Promise<PartyContact[]> {\n // Reading the form here (rather than trusting a caller's array) keeps the\n // presence-marker check on the write path.\n const rows = Array.isArray(posted)\n ? (posted as readonly PartyContactInput[])\n : readPartyContactRows(\n posted as PartyContactFormSource,\n options.fieldNames,\n );\n const party: Customer | Vendor | null = await collection.get({\n id: partyId,\n });\n if (\n !party ||\n (options.expectedTenantId !== undefined &&\n party.tenantId !== options.expectedTenantId)\n )\n throw new PartyContactPartyNotFoundError(partyId);\n\n const validation = validatePartyContactRows(rows);\n const { contacts } = validation;\n const errors = validation.errors ?? rows.map(() => undefined);\n const saved = new Set(\n normalizePartyContacts(party.contacts).map((c) => c.id),\n );\n let invalid = validation.errors !== undefined;\n rows.forEach((row, index) => {\n const id = text(row.id).trim();\n if (id && !saved.has(id)) {\n errors[index] = { ...errors[index], id: 'unknown_contact' };\n invalid = true;\n }\n });\n if (invalid) throw new PartyContactValidationError(errors);\n\n const seen = new Set<string>();\n party.contacts = contacts.map((row) => {\n // A duplicated posted id (two rows claiming one contact) keeps the id\n // on the first row only, so stored ids stay unique.\n const id =\n row.id && !seen.has(row.id) ? row.id : globalThis.crypto.randomUUID();\n seen.add(id);\n return {\n id,\n name: row.name ?? '',\n label: row.label ?? '',\n email: row.email ?? '',\n phone: row.phone ?? '',\n address: row.address ?? '',\n };\n });\n await party.save();\n return party.contacts;\n}\n","/**\n * Customer model - links to Profile with customer-specific data\n * @packageDocumentation\n */\n\nimport {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport { normalizePartyContacts } from '../party-contacts.js';\nimport {\n type Address,\n type CustomerOptions,\n CustomerStatus,\n CustomerType,\n type PartyContact,\n} from '../types/index.js';\n\n/**\n * Customer represents the customer role for a Profile.\n *\n * One Profile can have multiple Customer records (e.g., different business contexts).\n * Customer stores customer-specific data like credit limits and payment terms.\n *\n * @example\n * ```typescript\n * const customer = await customers.create({\n * profileId: 'profile-uuid',\n * creditLimit: 10000,\n * paymentTerms: 'Net 30'\n * });\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'update'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Customer extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n /**\n * Tenant ID for multi-tenant isolation\n * Nullable to support both tenant-scoped and global customers\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Reference to smrt-profiles Profile\n * Plain string for cross-package reference\n */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', {\n description:\n 'Links this customer to their profile record, where their name and contact details are kept.',\n })\n profileId: string = '';\n\n /**\n * Maximum credit extended to this customer, in **integer minor units**\n * (cents, satoshis).\n *\n * Converts with the rest of commerce because\n * {@link Customer.hasAvailableCredit} compares it directly against a money\n * amount; a dollars-vs-cents split there would approve every request off by\n * a factor of 100 (#2401).\n */\n @field({\n description:\n 'The most this customer may owe you at one time. Leave it at zero if you do not set limits.',\n ui: { format: 'money' },\n })\n creditLimit: number = 0;\n\n /**\n * Payment terms (e.g., \"Net 30\", \"Due on receipt\", \"2/10 Net 30\")\n */\n @field({\n description:\n 'How long the customer has to pay, written the way you would say it, for example \"Net 30\".',\n })\n paymentTerms: string = '';\n\n /**\n * Whether customer is exempt from tax\n */\n @field({\n description: 'Turn this on if you do not charge this customer sales tax.',\n })\n taxExempt: boolean = false;\n\n /**\n * Tax identification number\n *\n * Sensitive (#1540): PII excluded from generated API/MCP responses and\n * rejected as a `where` filter key.\n */\n @field({\n sensitive: true,\n description:\n 'The tax or VAT number of the customer, kept on file for tax-exempt sales.',\n })\n taxId: string = '';\n\n /**\n * Tax code normally used for this customer's sales.\n *\n * An exempt customer always resolves to the tenant's exempt code before\n * this preference is considered.\n */\n @foreignKey('TaxCode', {\n description: 'The tax code normally used when selling to this customer.',\n })\n defaultTaxCodeId: string = '';\n\n /**\n * Default shipping address\n */\n @field({\n description:\n 'Where you usually send goods to this customer, so you do not retype it on every order.',\n })\n defaultShippingAddress: Address = {};\n\n /**\n * Default billing address\n */\n @field({ description: 'Where you send invoices to this customer.' })\n defaultBillingAddress: Address = {};\n\n /**\n * Customer status\n */\n @field({\n description:\n 'Whether you are still dealing with this customer: active, inactive or suspended.',\n })\n status: CustomerStatus = CustomerStatus.ACTIVE;\n\n /**\n * Customer classification — DTC, wholesale, or retail.\n *\n * Drives channel access (wholesale portal vs. storefront vs. POS), default\n * price tier, and credit terms. Defaults to DTC for backwards compatibility.\n */\n @field({\n description:\n 'The kind of customer: a direct shopper, a wholesale buyer or a retail customer.',\n })\n customerType: CustomerType = CustomerType.DTC;\n\n /**\n * Internal notes about this customer\n */\n @field({\n description: 'Anything worth remembering about this customer.',\n ui: { widget: 'textarea' },\n })\n notes: string = '';\n\n /**\n * People to reach at this customer, stored as a JSON column (#3501). Write\n * form rows through `savePartyContacts()`; every save normalizes the shape.\n */\n @field({\n description:\n 'The people you deal with at this customer, with their role and how to reach them.',\n })\n contacts: PartyContact[] = [];\n\n constructor(options: CustomerOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n if (options.creditLimit !== undefined)\n this.creditLimit = options.creditLimit;\n if (options.paymentTerms !== undefined)\n this.paymentTerms = options.paymentTerms;\n if (options.taxExempt !== undefined) this.taxExempt = options.taxExempt;\n if (options.taxId !== undefined) this.taxId = options.taxId;\n if (options.defaultTaxCodeId !== undefined)\n this.defaultTaxCodeId = options.defaultTaxCodeId;\n if (options.defaultShippingAddress !== undefined)\n this.defaultShippingAddress = options.defaultShippingAddress;\n if (options.defaultBillingAddress !== undefined)\n this.defaultBillingAddress = options.defaultBillingAddress;\n if (options.status !== undefined) this.status = options.status;\n // Treat `null` the same as `undefined` here. Customers loaded from\n // rows written before the `customer_type` column existed will\n // hydrate with the field as SQL `NULL`; without this guard the\n // SmrtObject loader would overwrite the `CustomerType.DTC`\n // initializer with `null`, breaking the documented\n // backwards-compatible default. Explicit string values (including\n // any future custom flavour) still take precedence.\n if (options.customerType !== undefined && options.customerType !== null) {\n this.customerType = options.customerType;\n }\n if (options.notes !== undefined) this.notes = options.notes;\n if (options.contacts !== undefined)\n this.contacts = normalizePartyContacts(options.contacts);\n }\n\n /**\n * Re-normalize contacts after the framework's option-override pass, which\n * re-applies raw option values (including a stored JSON string).\n */\n override async initialize(): Promise<this> {\n await super.initialize();\n this.contacts = normalizePartyContacts(this.contacts);\n return this;\n }\n\n /** Save with a final contacts normalization against direct assignment. */\n override async save(): Promise<this> {\n this.contacts = normalizePartyContacts(this.contacts);\n return super.save() as Promise<this>;\n }\n\n /**\n * Convenience predicate: is this a wholesale customer?\n */\n isWholesale(): boolean {\n return this.customerType === CustomerType.WHOLESALE;\n }\n\n /**\n * Check if customer is active\n */\n isActive(): boolean {\n return this.status === CustomerStatus.ACTIVE;\n }\n\n /**\n * Check if customer has available credit\n */\n hasAvailableCredit(amount: number): boolean {\n // In a full implementation, this would check against outstanding balances\n return this.creditLimit >= amount;\n }\n\n /**\n * Get the profile ID for external lookup.\n *\n * To get the actual Profile object, use the ProfileCollection from smrt-profiles:\n * ```typescript\n * const profiles = await ProfileCollection.create(options);\n * const profile = await profiles.get({ id: customer.profileId });\n * ```\n *\n * @returns The profile ID or empty string if not set\n */\n getProfileId(): string {\n return this.profileId;\n }\n}\n\nexport default Customer;\n","/**\n * Vendor model - links to Profile with vendor-specific data\n * @packageDocumentation\n */\n\nimport {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport { normalizePartyContacts } from '../party-contacts.js';\nimport {\n type PartyContact,\n type VendorOptions,\n VendorStatus,\n} from '../types/index.js';\n\n/**\n * Vendor represents the vendor/supplier role for a Profile.\n *\n * One Profile can have both Customer and Vendor records - e.g., a company\n * you both buy from and sell to.\n *\n * @example\n * ```typescript\n * const vendor = await vendors.create({\n * profileId: 'profile-uuid',\n * leadTimeDays: 14,\n * minimumOrderAmount: 500,\n * paymentTerms: 'Net 60'\n * });\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'update'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Vendor extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n /**\n * Tenant ID for multi-tenant isolation\n * Nullable to support both tenant-scoped and global vendors\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Reference to smrt-profiles Profile\n * Plain string for cross-package reference\n */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', {\n description:\n 'Links this vendor to their profile record, where their name and contact details are kept.',\n })\n profileId: string = '';\n\n /**\n * Typical lead time in days for orders\n */\n @field({\n description:\n 'How many days the vendor usually takes between your order and delivery.',\n })\n leadTimeDays: number = 0;\n\n /**\n * Minimum order amount required, in **integer minor units** (cents,\n * satoshis). Compared against `Contract.totalAmount`, which is also minor\n * units (#2401).\n */\n @field({\n description: 'The smallest order the vendor will accept.',\n ui: { format: 'money' },\n })\n minimumOrderAmount: number = 0;\n\n /**\n * Payment terms for this vendor (e.g., \"Net 60\")\n */\n @field({\n description:\n 'How long you have to pay this vendor, written the way you would say it, for example \"Net 30\".',\n })\n paymentTerms: string = '';\n\n /**\n * Default currency for transactions with this vendor\n */\n @field({\n description: 'The currency this vendor bills you in.',\n ui: { widget: 'currency' },\n })\n currency: string = 'USD';\n\n /**\n * Supplier registration number.\n *\n * Sensitive for the same reason as a customer's tax ID: it is identifying\n * business information and must not enter generated list/search surfaces.\n */\n @field({\n sensitive: true,\n description: 'The vendor tax or VAT registration number kept on file.',\n })\n taxId: string = '';\n\n /** Tax code normally used for purchases from this vendor. */\n @foreignKey('TaxCode', {\n description: 'The tax code normally used when buying from this vendor.',\n })\n defaultTaxCodeId: string = '';\n\n /**\n * Default contact email for orders\n */\n @field({\n description: 'The email address you normally use to reach this vendor.',\n ui: { widget: 'email' },\n })\n defaultContactEmail: string = '';\n\n /**\n * Default contact phone for orders\n */\n @field({\n description: 'The phone number you normally use to reach this vendor.',\n ui: { widget: 'phone' },\n })\n defaultContactPhone: string = '';\n\n /**\n * Vendor status\n */\n @field({\n description:\n 'Whether you still buy from this vendor: active, inactive or suspended.',\n })\n status: VendorStatus = VendorStatus.ACTIVE;\n\n /**\n * Internal notes about this vendor\n */\n @field({\n description: 'Anything worth remembering about this vendor.',\n ui: { widget: 'textarea' },\n })\n notes: string = '';\n\n /**\n * Per-currency payout destinations for this vendor.\n *\n * Stored as a JSON column. Keys are payout-rail-qualified currency codes —\n * the code must encode both the asset and the rail (e.g. `USDC-base`,\n * `USDC-solana`, `BTC`, `USD-stripe`, `USD-wire`). Values are whatever the\n * receiving rail needs as a destination (EVM address, BTC address, Stripe\n * Connect account id, IBAN, etc.).\n *\n * MVP shape: a flat map on the vendor row. A vendor with no entry for a\n * given currency cannot be paid in that currency — filtering is the\n * consumer's responsibility (the upstream `PaymentIntent` builder filters\n * `paymentOptions` at quote time against this map).\n *\n * Use {@link getPayoutAddress} for a `Map.get`-style lookup that returns\n * `undefined` for missing entries; direct property access is also fine.\n *\n * Sensitive (#1540): payout destinations are excluded from generated API/MCP\n * responses and rejected as a `where` filter key.\n */\n @field({\n sensitive: true,\n description: 'Where payments to this vendor should be sent.',\n })\n payoutAddresses: Record<string, string> = {};\n\n /**\n * People to reach at this vendor, stored as a JSON column (#3501). Write\n * form rows through `savePartyContacts()`; every save normalizes the shape.\n */\n @field({\n description:\n 'The people you deal with at this vendor, with their role and how to reach them.',\n })\n contacts: PartyContact[] = [];\n\n constructor(options: VendorOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n if (options.leadTimeDays !== undefined)\n this.leadTimeDays = options.leadTimeDays;\n if (options.minimumOrderAmount !== undefined)\n this.minimumOrderAmount = options.minimumOrderAmount;\n if (options.paymentTerms !== undefined)\n this.paymentTerms = options.paymentTerms;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.taxId !== undefined) this.taxId = options.taxId;\n if (options.defaultTaxCodeId !== undefined)\n this.defaultTaxCodeId = options.defaultTaxCodeId;\n if (options.defaultContactEmail !== undefined)\n this.defaultContactEmail = options.defaultContactEmail;\n if (options.defaultContactPhone !== undefined)\n this.defaultContactPhone = options.defaultContactPhone;\n if (options.status !== undefined) this.status = options.status;\n if (options.notes !== undefined) this.notes = options.notes;\n if (options.payoutAddresses !== undefined) {\n this.payoutAddresses = Vendor.normalizePayoutAddresses(\n options.payoutAddresses,\n );\n }\n if (options.contacts !== undefined)\n this.contacts = normalizePartyContacts(options.contacts);\n }\n\n /**\n * The framework's {@link SmrtObject.initialize} re-applies `options` keys on\n * top of constructor-set values so option data always wins over field\n * initializers. That means our constructor's normalization runs *before*\n * `initializePropertiesFromOptions` overwrites `payoutAddresses` with the\n * raw cloned value. Re-normalize once super has finished so consumers\n * who pass a string, a partially-typed map, or `null` end up with a\n * clean `Record<string, string>` before any save / read happens.\n */\n override async initialize(): Promise<this> {\n await super.initialize();\n this.payoutAddresses = Vendor.normalizePayoutAddresses(\n this.payoutAddresses as unknown,\n );\n this.contacts = normalizePartyContacts(this.contacts);\n return this;\n }\n\n /**\n * Save with a final normalization pass so direct field assignments\n * (`vendor.payoutAddresses = somethingFunny`) can't smuggle non-string\n * values into the persisted row.\n */\n override async save(): Promise<this> {\n this.payoutAddresses = Vendor.normalizePayoutAddresses(\n this.payoutAddresses as unknown,\n );\n this.contacts = normalizePartyContacts(this.contacts);\n return super.save() as Promise<this>;\n }\n\n /**\n * Check if vendor is active\n */\n isActive(): boolean {\n return this.status === VendorStatus.ACTIVE;\n }\n\n /**\n * Check if order meets minimum requirements\n */\n meetsMinimumOrder(amount: number): boolean {\n return amount >= this.minimumOrderAmount;\n }\n\n /**\n * Get the profile ID for external lookup.\n *\n * To get the actual Profile object, use the ProfileCollection from smrt-profiles:\n * ```typescript\n * const profiles = await ProfileCollection.create(options);\n * const profile = await profiles.get({ id: vendor.profileId });\n * ```\n *\n * @returns The profile ID or empty string if not set\n */\n getProfileId(): string {\n return this.profileId;\n }\n\n /**\n * Look up the payout destination for a single currency. Returns\n * `undefined` if the vendor has no entry for that currency — caller's\n * job to decide whether that means \"skip the option\" or \"raise a\n * configuration error\". The lookup is case-sensitive; the contract is\n * that the currency code passed in matches exactly what was stored\n * (`USDC-base`, not `usdc-base`).\n */\n getPayoutAddress(currency: string): string | undefined {\n const map = this.payoutAddresses;\n if (!map || typeof map !== 'object') return undefined;\n const value = (map as Record<string, unknown>)[currency];\n return typeof value === 'string' ? value : undefined;\n }\n\n /**\n * Set the payout destination for a single currency. Mutates the live\n * map and returns `this` for chaining. Use {@link clearPayoutAddress}\n * to remove a single entry.\n */\n setPayoutAddress(currency: string, destination: string): this {\n this.payoutAddresses = {\n ...(this.payoutAddresses ?? {}),\n [currency]: destination,\n };\n return this;\n }\n\n /**\n * Remove a single currency entry from the payout map. No-op if the\n * currency was already absent.\n */\n clearPayoutAddress(currency: string): this {\n if (!this.payoutAddresses || !(currency in this.payoutAddresses)) {\n return this;\n }\n const next = { ...this.payoutAddresses };\n delete next[currency];\n this.payoutAddresses = next;\n return this;\n }\n\n /**\n * Normalize an input value (object, pre-serialized JSON string, or\n * `null`/`undefined`) into a plain `Record<string, string>`. Used by\n * the constructor so consumers can pass either shape into\n * `VendorCollection.create({ payoutAddresses: ... })`.\n *\n * Non-string values inside an input object are silently dropped — a\n * `Record<string, string>` invariant is what consumers downstream\n * (`PaymentIntent` builders, payout SDK adapters) rely on.\n */\n private static normalizePayoutAddresses(\n value: unknown,\n ): Record<string, string> {\n if (value == null) return {};\n let parsed: unknown = value;\n if (typeof value === 'string') {\n try {\n parsed = JSON.parse(value);\n } catch {\n return {};\n }\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return {};\n }\n const out: Record<string, string> = {};\n for (const [key, v] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof v === 'string') out[key] = v;\n }\n return out;\n }\n}\n\nexport default Vendor;\n","/**\n * Contract model with STI for different contract types\n * @packageDocumentation\n */\n\nimport {\n field,\n foreignKey,\n type Meta,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n DOCUMENT_MONEY_READ_REBIND,\n DOCUMENT_MONEY_WRITE,\n type DocumentMoneyReadRebindCapability,\n type DocumentMoneyWriteCapability,\n} from '../document-money-internal.js';\nimport { assertIntegerMinorUnits } from '../money.js';\nimport {\n type ContractOptions,\n ContractStatus,\n ContractType,\n type LicenseSaleOptions,\n type PurchaseContractOptions,\n type PurchaseOrderOptions,\n type SalesContractOptions,\n type TaxRegistrationOptions,\n} from '../types/index.js';\nimport { Customer } from './Customer.js';\nimport { Vendor } from './Vendor.js';\n\n/**\n * Legal status transitions for a Contract (and all its STI subtypes), keyed by\n * the prior persisted status. A status re-saved unchanged (no-op) and a\n * brand-new row are always permitted; this map governs *changes* only.\n *\n * Flow: DRAFT → SENT → (ACCEPTED | DECLINED); ACCEPTED → (COMPLETED |\n * CANCELLED). An estimate/order may also be cancelled directly from DRAFT/SENT.\n * DECLINED / COMPLETED / CANCELLED are terminal. This guards against raw\n * mass-assignment forcing, e.g., a DECLINED contract back to ACCEPTED or a\n * COMPLETED one back to DRAFT. See S5 audit #1390.\n */\nconst CONTRACT_STATUS_TRANSITIONS: Record<ContractStatus, ContractStatus[]> = {\n [ContractStatus.DRAFT]: [\n ContractStatus.SENT,\n ContractStatus.ACCEPTED,\n ContractStatus.DECLINED,\n ContractStatus.CANCELLED,\n ],\n [ContractStatus.SENT]: [\n ContractStatus.ACCEPTED,\n ContractStatus.DECLINED,\n ContractStatus.CANCELLED,\n ],\n [ContractStatus.ACCEPTED]: [\n ContractStatus.COMPLETED,\n ContractStatus.CANCELLED,\n ],\n [ContractStatus.DECLINED]: [],\n [ContractStatus.COMPLETED]: [],\n [ContractStatus.CANCELLED]: [],\n};\n\n/**\n * Module-scoped record of the status each Contract instance was loaded with,\n * for the save-time transition guard. WeakMap keeps it out of the schema and\n * GCs with the instance — same pattern as the other commerce models.\n */\nconst loadedContractStatus = new WeakMap<Contract, ContractStatus>();\n\n/** Whether a Contract belongs to the purchase STI branch, including descendants. */\nexport function classifyContractPurchase(contract: Contract): boolean {\n return 'vendorId' in contract;\n}\n\n/** Frozen snapshots are reportable except cancelled contracts and supplier quotes. */\nexport function isContractSnapshotReportEligible(contract: Contract): boolean {\n return (\n !(contract instanceof SupplierQuote) &&\n contract.status !== ContractStatus.DRAFT &&\n contract.status !== ContractStatus.CANCELLED\n );\n}\n\n/**\n * Contract is the base class for all commercial agreements.\n *\n * Uses Single Table Inheritance (STI) for ten leaf types. SalesContract owns\n * the customer link for Estimate, Order, WholesaleOrder, Cart, Lease,\n * Agreement, and LicenseSale. PurchaseContract owns the vendor link for\n * SupplierQuote, PurchaseOrder and ProductionOrder. Both branches share `contracts`.\n *\n * @example\n * ```typescript\n * // Create a customer order\n * const order = await contracts.create({\n * _meta_type: 'Order',\n * customerId: customer.id,\n * totalAmount: 150000, // $1,500.00 in cents\n * status: ContractStatus.DRAFT\n * });\n *\n * // Create a purchase order to vendor\n * const po = await contracts.create({\n * _meta_type: 'PurchaseOrder',\n * vendorId: vendor.id,\n * totalAmount: 500000, // $5,000.00 in cents\n * reference: 'PO-2024-001'\n * });\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create', 'update'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Contract extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n /** @internal Collection read guard returns this snapshot on its root DB. */\n rebindMoneyRead(\n capability: DocumentMoneyReadRebindCapability,\n db: DatabaseInterface,\n ): this {\n if (capability !== DOCUMENT_MONEY_READ_REBIND)\n throw new Error('Contract read rebinding requires the owning capability');\n this._db = db;\n this.options.db = db;\n return this;\n }\n\n /**\n * Tenant ID for multi-tenant isolation\n * Nullable to support both tenant-scoped and global contracts\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Contract type discriminator (STI)\n */\n @field({\n description:\n 'The kind of contract: order, estimate, lease, agreement and so on.',\n })\n contractType: ContractType = ContractType.ORDER;\n\n /**\n * Current status of the contract\n */\n @field({\n description:\n 'Where the order or agreement stands, for example draft, sent, accepted or completed.',\n })\n status: ContractStatus = ContractStatus.DRAFT;\n\n /**\n * Subtotal before tax, in **integer minor units** (cents, satoshis).\n *\n * The `= 0` initializer is load-bearing: SMRT maps an integer literal to\n * INTEGER and a decimal literal to DECIMAL. Money is exact, so it is stored\n * as minor units and never as a float — `$19.99` is `1999`, not `19.99`\n * (#2401).\n */\n @field({ description: 'The amount before tax.', ui: { format: 'money' } })\n subtotal: number = 0;\n\n /** Informational sum of resolved line discounts, in integer minor units. */\n @field({ ui: { format: 'money' } })\n discountTotal: number = 0;\n\n /**\n * Tax amount, in integer minor units (#2401).\n */\n @field({ description: 'The tax charged.', ui: { format: 'money' } })\n taxAmount: number = 0;\n\n /**\n * Total amount including tax, in integer minor units (#2401).\n */\n @field({\n description: 'The full amount, tax included.',\n ui: { format: 'money' },\n })\n totalAmount: number = 0;\n\n /**\n * Currency code (ISO 4217)\n */\n @field({\n description: 'The currency of the amounts.',\n ui: { widget: 'currency' },\n })\n currency: string = 'USD';\n\n /** Pricing interpretation fixed before the Contract leaves draft. */\n lineAmountType: 'exclusive' | 'inclusive' | 'none' = 'exclusive';\n\n /** Component rounding scope fixed before the Contract leaves draft. */\n taxRoundingScope: 'line' | 'document' = 'line';\n\n /** Immutable seller registration snapshot once the Contract leaves draft. */\n sellerTaxRegistrationsJson = '[]';\n\n get sellerTaxRegistrations(): TaxRegistrationOptions[] {\n try {\n const value: unknown = JSON.parse(this.sellerTaxRegistrationsJson);\n if (!Array.isArray(value)) return [];\n return value.filter(\n (entry): entry is TaxRegistrationOptions =>\n !!entry &&\n typeof entry === 'object' &&\n typeof (entry as TaxRegistrationOptions).taxComponentId ===\n 'string' &&\n typeof (entry as TaxRegistrationOptions).number === 'string' &&\n typeof (entry as TaxRegistrationOptions).label === 'string',\n );\n } catch {\n return [];\n }\n }\n\n set sellerTaxRegistrations(value: TaxRegistrationOptions[]) {\n this.sellerTaxRegistrationsJson = JSON.stringify(value);\n }\n\n /** Immutable customer or vendor tax identifier snapshot after issue. */\n partyTaxId = '';\n\n /** Stable issue/freeze identity, independent of lifecycle updated_at. */\n moneySnapshotId = '';\n\n /**\n * Date contract was issued\n */\n @field({ description: 'The date it was issued or placed.' })\n issueDate: Date = new Date();\n\n /**\n * Payment due date\n */\n @field({ description: 'The date payment or delivery is due.' })\n dueDate: Date | null = null;\n\n /**\n * Expiry date (for estimates/quotes)\n */\n @field({ description: 'The last day the price or offer is good for.' })\n expiryDate: Date | null = null;\n\n /**\n * External reference number (PO number, quote number, etc.)\n */\n @field({\n description:\n 'Your own number or note for finding this later, such as a purchase order or quote number.',\n })\n reference: string = '';\n\n /**\n * Internal notes\n */\n @field({\n description: 'Anything worth remembering about this.',\n ui: { widget: 'textarea' },\n })\n notes: string = '';\n\n /**\n * Terms and conditions\n */\n @field({\n description:\n 'The conditions agreed, such as deposits, payment or delivery conditions.',\n ui: { widget: 'textarea' },\n })\n terms: string = '';\n\n /**\n * Sales channel that owns this contract.\n *\n * Plain string so consumers can model their own channels without an enum\n * change (e.g. `dtc-web`, `wholesale-b2b`, `pos-store-1`, `marketplace-faire`).\n * Empty string means \"unattributed / legacy\".\n */\n @field({\n description:\n 'Where it came from, for example your shop, a marketplace or a phone call.',\n })\n channelId: string = '';\n\n /**\n * STI discriminator field\n */\n static readonly _stiField = 'contractType';\n\n constructor(options: ContractOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.contractType !== undefined)\n this.contractType = options.contractType;\n if (options.status !== undefined) this.status = options.status;\n if (options.subtotal !== undefined) this.subtotal = options.subtotal;\n if (options.discountTotal !== undefined)\n this.discountTotal = options.discountTotal;\n if (options.taxAmount !== undefined) this.taxAmount = options.taxAmount;\n if (options.totalAmount !== undefined)\n this.totalAmount = options.totalAmount;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.lineAmountType !== undefined)\n this.lineAmountType = options.lineAmountType;\n if (options.taxRoundingScope !== undefined)\n this.taxRoundingScope = options.taxRoundingScope;\n if (options.sellerTaxRegistrationsJson !== undefined)\n this.sellerTaxRegistrationsJson = options.sellerTaxRegistrationsJson;\n if (options.sellerTaxRegistrations !== undefined)\n this.sellerTaxRegistrations = structuredClone(\n options.sellerTaxRegistrations,\n );\n if (options.partyTaxId !== undefined) this.partyTaxId = options.partyTaxId;\n if (options.moneySnapshotId !== undefined)\n this.moneySnapshotId = options.moneySnapshotId;\n if (options.issueDate !== undefined) this.issueDate = options.issueDate;\n if (options.dueDate !== undefined) this.dueDate = options.dueDate;\n if (options.expiryDate !== undefined) this.expiryDate = options.expiryDate;\n if (options.reference !== undefined) this.reference = options.reference;\n if (options.notes !== undefined) this.notes = options.notes;\n if (options.terms !== undefined) this.terms = options.terms;\n if (options.channelId !== undefined) this.channelId = options.channelId;\n }\n\n /**\n * Check if contract is in draft state\n */\n isDraft(): boolean {\n return this.status === ContractStatus.DRAFT;\n }\n\n /**\n * Check if contract is accepted\n */\n isAccepted(): boolean {\n return this.status === ContractStatus.ACCEPTED;\n }\n\n /**\n * Check if contract is completed\n */\n isCompleted(): boolean {\n return this.status === ContractStatus.COMPLETED;\n }\n\n /**\n * Check if contract is expired (for estimates)\n */\n isExpired(): boolean {\n if (!this.expiryDate) return false;\n return new Date() > this.expiryDate;\n }\n\n /**\n * Check if contract is overdue\n */\n isOverdue(): boolean {\n if (!this.dueDate) return false;\n if (this.status === ContractStatus.COMPLETED) return false;\n return new Date() > this.dueDate;\n }\n\n /**\n * Calculate and update totals from line items\n */\n async recalculateTotals(): Promise<void> {\n const { recalculateContractTotals } = await import('../contract-money.js');\n await recalculateContractTotals(this);\n }\n\n /**\n * Capture the status the row was loaded with so the save-time transition\n * guard can reject illegal status flips made via raw field assignment\n * (mass-assignment on the generated update route, a stale caller, etc.).\n * Only persisted rows carry a prior status.\n */\n override async initialize(): Promise<this> {\n await super.initialize();\n if (await this.isSaved()) {\n loadedContractStatus.set(this, this.status);\n }\n return this;\n }\n\n /**\n * Validate the amounts and the status transition before persisting, then\n * save. Inherited by every STI subtype (Estimate/Order/Lease/.../LicenseSale),\n * so a forged `status` on any of them is caught here. LicenseSale layers its\n * own rights-immutability guard on top via `super.save()`. See S5 audit\n * #1390.\n *\n * `subtotal` / `taxAmount` / `totalAmount` are mass-assignable on the\n * generated create/update routes, so the minor-units check runs on every\n * write surface (#2401).\n */\n override async save(): Promise<this> {\n const { saveContract } = await import('../contract-money.js');\n return (await saveContract(this)) as this;\n }\n\n /** @internal Contract aggregate persistence only. */\n async saveDerived(capability: DocumentMoneyWriteCapability): Promise<this> {\n if (capability !== DOCUMENT_MONEY_WRITE)\n throw new Error('Contract money write capability is required');\n assertIntegerMinorUnits('Contract', this.reference || this.id || '<new>', [\n ['subtotal', this.subtotal],\n ['discountTotal', this.discountTotal],\n ['taxAmount', this.taxAmount],\n ['totalAmount', this.totalAmount],\n ]);\n const prior = await this.resolvePriorStatus();\n this.assertContractStatusTransition(prior);\n const result = (await super.save()) as this;\n loadedContractStatus.set(this, this.status);\n return result;\n }\n\n /**\n * Reject an illegal status flip done via raw assignment. No-op transitions\n * and brand-new rows are always allowed.\n */\n protected assertContractStatusTransition(\n prior: ContractStatus | undefined,\n ): void {\n if (prior === undefined) return; // new row — any starting status is fine\n if (prior === this.status) return; // no-op re-save\n const allowed = CONTRACT_STATUS_TRANSITIONS[prior] ?? [];\n if (!allowed.includes(this.status)) {\n throw new Error(\n `Contract ${this.reference || this.id}: illegal status transition ` +\n `'${prior}' → '${this.status}'.`,\n );\n }\n }\n\n /**\n * Resolve the AUTHORITATIVE prior status (S5 audit #1390 round 5, codex\n * MEDIUM#2). The WeakMap is only populated when {@link initialize} loaded the\n * row from the DB; it is empty for an instance built via\n * `collection.create({ id: <existing>, _skipLoad: true })` — the upsert path\n * that lets a caller write onto an existing row without hydrating it. Trusting\n * an empty WeakMap there would treat the write as a brand-new row and skip the\n * transition guard entirely (a poisonable prior-state). Mirrors the\n * authoritative-prior-load applied to Payment/PaymentIntent/Invoice/Payout.\n *\n * So when this instance carries an `id`, read the persisted row straight from\n * the database and treat its `status` as the prior — a create-onto-existing is\n * an update. Only when no row exists in the DB (truly new) do we fall back to\n * the WeakMap (which is also empty then), i.e. `undefined` = genuinely new.\n * The raw row's `status` column is single-word (no snake_case transform).\n */\n protected async resolvePriorStatus(): Promise<ContractStatus | undefined> {\n if (this.id) {\n try {\n const row = await this.db.get(this.tableName, { id: this.id });\n if (row && row.status != null) {\n return row.status as ContractStatus;\n }\n } catch {\n // DB not ready / table absent — fall through to the in-memory record.\n }\n }\n return loadedContractStatus.get(this);\n }\n}\n\n// Every STI child below MUST repeat the `@TenantScoped` decoration. The\n// tenancy registry keys off the concrete className passed by the\n// collection, not the inheritance chain — `OrderCollection.list()` sends\n// `'Order'` to the interceptor, which then misses the `'Contract'`\n// registration and skips tenant auto-filter/auto-populate. Without an\n// explicit `@TenantScoped` on each subclass, saves end up with\n// `tenantId: null` (the row becomes global / invisible to tenant-scoped\n// queries) and lists return rows across tenants.\n\n/** Customer-side contracts, including orders, estimates, and licenses. */\n@TenantScoped({ mode: 'optional' })\n@smrt({ abstract: true })\nexport abstract class SalesContract extends Contract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, {\n description: 'The customer a sales order or agreement is for.',\n })\n customerId: string | null = null;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/** Supplier-side contracts, including supplier quotes, purchase and production orders. */\n@TenantScoped({ mode: 'optional' })\n@smrt({ abstract: true })\nexport abstract class PurchaseContract extends Contract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Vendor, {\n description: 'The vendor supplying this quote or purchase contract.',\n })\n vendorId: string | null = null;\n\n constructor(options: PurchaseContractOptions = {}) {\n super(options);\n if (options.vendorId !== undefined) this.vendorId = options.vendorId;\n }\n}\n\n/**\n * Estimate - Quote or proposal for a customer\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class Estimate extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, { required: true })\n override customerId: string | null = null;\n override contractType = ContractType.ESTIMATE;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/**\n * Order - Customer purchase order\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class Order extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, { required: true })\n override customerId: string | null = null;\n override contractType = ContractType.ORDER;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/**\n * Lease - Rental or lease agreement\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class Lease extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, { required: true })\n override customerId: string | null = null;\n override contractType = ContractType.LEASE;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/**\n * Agreement - Service or maintenance agreement\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class Agreement extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, { required: true })\n override customerId: string | null = null;\n override contractType = ContractType.AGREEMENT;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/** Supplier quotation received from a vendor; acceptance does not create an order. */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class SupplierQuote extends PurchaseContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Vendor, { required: true })\n override vendorId: string | null = null;\n override contractType = ContractType.SUPPLIER_QUOTE;\n\n constructor(options: PurchaseContractOptions = {}) {\n super(options);\n if (options.vendorId !== undefined) this.vendorId = options.vendorId;\n }\n}\n\n/**\n * PurchaseOrder - Order sent to vendor/supplier\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class PurchaseOrder extends PurchaseContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Vendor, { required: true })\n override vendorId: string | null = null;\n override contractType = ContractType.PURCHASE_ORDER;\n\n /** Expected delivery calendar date (YYYY-MM-DD), or empty when unspecified. */\n @field({\n description:\n 'The date you expect the delivery, as YYYY-MM-DD. Leave blank if it is not known.',\n })\n expectedDate: Meta<string> = '';\n\n /** Delivery address/instructions snapshot, independent of the vendor address. */\n @field({\n description:\n 'Where this order should be delivered, including any delivery instructions.',\n })\n shipTo: Meta<string> = '';\n\n /** Construct a purchase order with its optional delivery header. */\n constructor(options: PurchaseOrderOptions = {}) {\n super(options);\n if (options.vendorId !== undefined) this.vendorId = options.vendorId;\n if (options.expectedDate !== undefined)\n this.expectedDate = options.expectedDate;\n if (options.shipTo !== undefined) this.shipTo = options.shipTo;\n }\n}\n\n/**\n * WholesaleOrder - B2B order placed by a wholesale customer.\n *\n * Behaves like an Order but is conventionally created against a customer with\n * `customerType: 'wholesale'`, uses NET-30/60 payment terms, and is delivered\n * via the wholesale-portal channel rather than retail checkout.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class WholesaleOrder extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @foreignKey(Customer, { required: true })\n override customerId: string | null = null;\n override contractType = ContractType.WHOLESALE_ORDER;\n\n constructor(options: SalesContractOptions = {}) {\n super(options);\n if (options.customerId !== undefined) this.customerId = options.customerId;\n }\n}\n\n/**\n * ProductionOrder - instruction to commission goods from an internal or\n * external factory.\n *\n * The manufacturing equivalent of a {@link PurchaseOrder} — but instead of\n * buying finished inventory, you're paying to *make* it. A ProductionOrder\n * consumes raw materials per a Bill of Materials (see\n * `@happyvertical/smrt-manufacturing`) and produces finished SKU stock when\n * posted (see `@happyvertical/smrt-inventory`).\n *\n * Carries two STI-meta fields that `ProductionService.consumeMaterials` /\n * `runProduction` read from the loaded row to resolve which BOM to walk:\n *\n * - `productId` — plain string ref to the upstream `Product` (or any\n * STI subtype, e.g. apparel `Style`). Used to look up the *active*\n * BOM via `BomService.findActiveForProduct` when no explicit\n * revision was pinned at the time the order was placed.\n * - `bomId` — optional pin to a specific BOM revision. When set, the\n * manufacturing service consumes against that exact revision even\n * if a newer BOM has become active in the meantime (keeps a\n * posted run from silently switching recipes mid-flight).\n *\n * Both fields are `Meta<string>` so the scanner routes them into the\n * shared `_meta_data` JSON column on the Contract STI table instead of\n * widening the base schema with manufacturing-specific columns.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class ProductionOrder extends PurchaseContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n override contractType = ContractType.PRODUCTION_ORDER;\n\n /**\n * Plain string reference to the upstream product the order is asked\n * to make. Cross-package id; never `@foreignKey()`. Required by\n * `ProductionService.consumeMaterials` unless `bomId` is supplied.\n */\n productId: Meta<string> = '';\n\n /**\n * Optional explicit BOM revision the order locked to at posting\n * time. When set, manufacturing uses this exact row even if the\n * product's active BOM has since changed. When empty, falls back\n * to the active BOM for `productId`.\n */\n bomId: Meta<string> = '';\n}\n\n/**\n * Cart - transient order-in-progress for a shopper.\n *\n * Persisted as a Contract so it can hold the same line items, totals, and\n * customer reference as a real Order, then convert in place (the application\n * promotes the row from `_meta_type: Cart` to `_meta_type: Order` at checkout\n * rather than copying data between tables).\n *\n * A Cart starts in {@link ContractStatus.DRAFT} via the base `Contract.status`\n * default — the subclass doesn't need its own override. Application code\n * is responsible for assigning the appropriate Order status at checkout;\n * the framework doesn't enforce a state machine on the cart → order transition.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class Cart extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n override contractType = ContractType.CART;\n}\n\n/**\n * Snapshot of the rights granted by a {@link LicenseSale}. The fields are\n * intentionally typed (not a generic JSON blob) so they survive schema\n * migrations and downstream consumers (PDF templating, hash-registry\n * publishers) can rely on the shape without re-parsing.\n *\n * Each field is opaque text — the values that make sense vary by\n * industry. A stock-media marketplace might use:\n *\n * - `medium`: `web,print,social`\n * - `distributionScope`: `worldwide` / `territorial`\n * - `exclusivity`: `exclusive` / `non-exclusive`\n * - `duration`: `perpetual` / `12-months` / `event-only`\n * - `territory`: ISO-3166 list or `worldwide`\n *\n * Booleans (`sublicensing`, `derivatives`) are typed as such; everything\n * else is a string so the model doesn't dictate vocabulary.\n */\nexport interface LicenseRightsSnapshot {\n medium: string;\n distributionScope: string;\n exclusivity: string;\n duration: string;\n territory: string;\n sublicensing: boolean;\n derivatives: boolean;\n}\n\n/**\n * Module-scoped WeakMap of \"rights snapshot the row was loaded with\".\n *\n * Used by {@link LicenseSale}'s immutability guard. We can't store the\n * captured snapshot as an instance field because the AST scanner would\n * pick it up as a persisted column; we can't store it as a `Meta<T>`\n * because then it'd round-trip with the row and the comparison would\n * always tautologically succeed. A WeakMap keyed by the instance is\n * the cleanest scope: no schema interaction, garbage-collected with\n * the instance.\n */\nconst issuedRightsSnapshot = new WeakMap<LicenseSale, string>();\n\n/**\n * LicenseSale — industry-neutral licensing primitive.\n *\n * Sits alongside the other Contract STI subtypes (Estimate, Order,\n * Lease, Agreement, PurchaseOrder, WholesaleOrder, ProductionOrder,\n * Cart) and represents a single sale of rights for a fee. A\n * stock-media marketplace selling a one-time license, a music-\n * licensing platform issuing a sync license, a code-asset marketplace\n * granting a redistribution right — all use the same primitive.\n *\n * Immutability invariant: once a `LicenseSale` is saved with\n * {@link ContractStatus.ACCEPTED}, its rights snapshot becomes\n * frozen. Re-saving with mutated rights throws. The only legal\n * transition out of ACCEPTED is `revoke()` (which moves status to\n * CANCELLED without changing the rights). If a different snapshot\n * is genuinely needed, the operator's contract is to issue a *new*\n * LicenseSale row and let the old one stand as historical record.\n *\n * All subtype-specific fields are declared as `Meta<T>` so the\n * scanner routes them into the shared `_meta_data` JSON column on\n * the `contracts` STI table — no migration of the base schema needed\n * to land this subtype.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt()\nexport class LicenseSale extends SalesContract { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n override contractType = ContractType.LICENSE_SALE;\n\n /**\n * Plain string reference to the upstream `Sku` (from\n * `@happyvertical/smrt-products`) that this license was sold against.\n * Cross-package id; never `@foreignKey()`.\n */\n skuId: Meta<string> = '';\n\n /**\n * Plain string reference to the `Payment` that satisfied the\n * purchase. Cross-model reference matches the rest of the\n * package's convention.\n */\n paymentId: Meta<string> = '';\n\n /**\n * The licensee's email address — the primary identity carried\n * forward into PDF generation and any downstream hash-registry\n * publication. Required; without it, downstream rights cannot be\n * attributed.\n */\n licenseeEmail: Meta<string> = '';\n\n /**\n * Optional legal-entity name of the licensee for purchases that\n * warrant it (typically high-tier B2B licenses). Empty string for\n * individual-buyer licenses where the email *is* the legal identity.\n */\n licenseeLegalEntity: Meta<string> = '';\n\n /**\n * Optional ISO-3166 jurisdiction code of the licensee, captured for\n * tax / disclosure / governing-law purposes. Empty when not\n * required.\n */\n licenseeJurisdiction: Meta<string> = '';\n\n // -------- Rights snapshot (immutable once issued) --------\n\n /** Permitted media — `web,print,social`, `broadcast`, etc. */\n rightsMedium: Meta<string> = '';\n\n /** Distribution scope — `worldwide`, `territorial`, `private`, etc. */\n rightsDistributionScope: Meta<string> = '';\n\n /** Exclusivity — `exclusive` / `non-exclusive` / `co-exclusive`. */\n rightsExclusivity: Meta<string> = '';\n\n /** Duration — `perpetual` / `12-months` / `event-only`, etc. */\n rightsDuration: Meta<string> = '';\n\n /** Territory — ISO-3166 list, `worldwide`, region name, etc. */\n rightsTerritory: Meta<string> = '';\n\n /** Whether the licensee may sublicense the rights. */\n rightsSublicensing: Meta<boolean> = false;\n\n /** Whether the licensee may create derivative works. */\n rightsDerivatives: Meta<boolean> = false;\n\n // -------- Artefacts --------\n\n /** URL of the signed PDF (typically a cloud-storage public URL). */\n pdfUrl: Meta<string> = '';\n\n /**\n * SHA-256 of the signed PDF bytes (hex string, no `0x` prefix).\n * Lets downstream consumers verify the PDF the licensee holds is\n * the one this row was issued for, without re-fetching.\n */\n pdfHash: Meta<string> = '';\n\n /**\n * Optional reference to an on-chain hash-registry entry — set when\n * the LicenseSale's `pdfHash` has been anchored on a public chain\n * for tamper-evidence. Format is whatever the hash-registry\n * service emits (e.g. `chain:tx-hash:log-index`). Empty for\n * deployments that don't publish hashes on-chain.\n */\n onChainHashRegistryRef: Meta<string> = '';\n\n constructor(options: LicenseSaleOptions = {}) {\n super(options);\n if (options.skuId !== undefined) this.skuId = options.skuId;\n if (options.paymentId !== undefined) this.paymentId = options.paymentId;\n if (options.licenseeEmail !== undefined)\n this.licenseeEmail = options.licenseeEmail;\n if (options.licenseeLegalEntity !== undefined)\n this.licenseeLegalEntity = options.licenseeLegalEntity;\n if (options.licenseeJurisdiction !== undefined)\n this.licenseeJurisdiction = options.licenseeJurisdiction;\n if (options.rightsMedium !== undefined)\n this.rightsMedium = options.rightsMedium;\n if (options.rightsDistributionScope !== undefined)\n this.rightsDistributionScope = options.rightsDistributionScope;\n if (options.rightsExclusivity !== undefined)\n this.rightsExclusivity = options.rightsExclusivity;\n if (options.rightsDuration !== undefined)\n this.rightsDuration = options.rightsDuration;\n if (options.rightsTerritory !== undefined)\n this.rightsTerritory = options.rightsTerritory;\n if (options.rightsSublicensing !== undefined)\n this.rightsSublicensing = options.rightsSublicensing;\n if (options.rightsDerivatives !== undefined)\n this.rightsDerivatives = options.rightsDerivatives;\n if (options.pdfUrl !== undefined) this.pdfUrl = options.pdfUrl;\n if (options.pdfHash !== undefined) this.pdfHash = options.pdfHash;\n if (options.onChainHashRegistryRef !== undefined)\n this.onChainHashRegistryRef = options.onChainHashRegistryRef;\n }\n\n /**\n * Once `super.initialize()` has applied the framework's option-\n * override pass, capture the rights snapshot if (and only if) the\n * row arrived already issued. That's how the immutability guard\n * tells \"freshly drafting a license\" (snapshot still mutable) apart\n * from \"loaded an already-issued row\" (snapshot frozen).\n */\n override async initialize(): Promise<this> {\n await super.initialize();\n if (this.status === ContractStatus.ACCEPTED && (await this.isSaved())) {\n issuedRightsSnapshot.set(this, this.serializeRightsSnapshot());\n }\n return this;\n }\n\n /**\n * Return the current rights snapshot as a typed object. Read-only\n * for callers — mutation should go through assignment to the\n * individual `rights*` fields, gated by the issued-immutability\n * guard.\n */\n getRightsSnapshot(): LicenseRightsSnapshot {\n return {\n medium: this.rightsMedium,\n distributionScope: this.rightsDistributionScope,\n exclusivity: this.rightsExclusivity,\n duration: this.rightsDuration,\n territory: this.rightsTerritory,\n sublicensing: this.rightsSublicensing,\n derivatives: this.rightsDerivatives,\n };\n }\n\n /**\n * Revoke an issued license — moves status to `CANCELLED` without\n * touching the rights snapshot (which stays frozen). Throws if\n * called on a non-issued license; a draft license should be\n * deleted, not revoked.\n */\n revoke(): void {\n if (this.status !== ContractStatus.ACCEPTED) {\n throw new Error(\n `LicenseSale ${this.id ?? '<new>'}: cannot revoke from status '${this.status}' — only ACCEPTED licenses can be revoked`,\n );\n }\n this.status = ContractStatus.CANCELLED;\n }\n\n /**\n * Save with the immutability check: if the row was loaded with\n * `ACCEPTED` status, the rights snapshot at save time must match\n * the snapshot at load time. Anything else means an out-of-band\n * mutation crept in and we surface it instead of letting the row\n * drift silently.\n *\n * Newly-drafted licenses (where the row was constructed without\n * `ACCEPTED` status) capture their snapshot at the moment the\n * caller transitions to `ACCEPTED` and saves — `validateImmutable`\n * picks that up post-save on the next call.\n */\n override async save(): Promise<this> {\n this.validateImmutable();\n const result = (await super.save()) as this;\n // If this save transitioned the row to ACCEPTED, freeze the\n // snapshot for future saves.\n if (\n this.status === ContractStatus.ACCEPTED &&\n !issuedRightsSnapshot.has(this)\n ) {\n issuedRightsSnapshot.set(this, this.serializeRightsSnapshot());\n }\n return result;\n }\n\n /**\n * Compare the current rights against the captured snapshot\n * (populated either at load time by `initialize` or at first\n * issuance by `save`). Throws on mismatch.\n */\n private validateImmutable(): void {\n const captured = issuedRightsSnapshot.get(this);\n if (!captured) return;\n const current = this.serializeRightsSnapshot();\n if (captured !== current) {\n throw new Error(\n `LicenseSale ${this.id ?? '<new>'}: rights snapshot is immutable once issued (status=ACCEPTED). ` +\n 'Use revoke() to cancel the existing license and issue a new one with the updated rights.',\n );\n }\n }\n\n private serializeRightsSnapshot(): string {\n // Stable key ordering so a re-serialization after a no-op\n // assignment doesn't trip the equality check.\n return JSON.stringify({\n medium: this.rightsMedium,\n distributionScope: this.rightsDistributionScope,\n exclusivity: this.rightsExclusivity,\n duration: this.rightsDuration,\n territory: this.rightsTerritory,\n sublicensing: this.rightsSublicensing,\n derivatives: this.rightsDerivatives,\n });\n }\n}\n\nexport default Contract;\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { PurchaseContract } from '../models/Contract.js';\n\n/** Read supplier-side contracts across every purchase STI subtype. */\nexport class PurchaseContractCollection extends SmrtCollection<PurchaseContract> {\n static readonly _itemClass = PurchaseContract;\n\n async findByVendor(vendorId: string): Promise<PurchaseContract[]> {\n return this.list({\n where: { vendorId },\n orderBy: 'created_at DESC',\n });\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { SalesContract } from '../models/Contract.js';\n\n/** Read customer-side contracts across every sales STI subtype. */\nexport class SalesContractCollection extends SmrtCollection<SalesContract> {\n static readonly _itemClass = SalesContract;\n\n async findByCustomer(customerId: string): Promise<SalesContract[]> {\n return this.list({\n where: { customerId },\n orderBy: 'created_at DESC',\n });\n }\n}\n","/**\n * ContractCollection - Collection manager for Contract objects (STI)\n * @packageDocumentation\n */\n\nimport {\n SmrtCollection,\n type SmrtListOptions,\n type SmrtObject,\n type SmrtSelectedRow,\n type SmrtSelectField,\n type SmrtStiReadScope,\n type SmrtWhereClause,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n queryGlobal,\n queryWithGlobals,\n} from '@happyvertical/smrt-tenancy';\nimport { DOCUMENT_MONEY_READ_REBIND } from '../document-money-internal.js';\nimport {\n Contract,\n isContractSnapshotReportEligible,\n} from '../models/Contract.js';\nimport { withTenantMoneyCollectionRead } from '../tenant-money-barrier.js';\nimport { ContractStatus, ContractType } from '../types/index.js';\nimport { PurchaseContractCollection } from './PurchaseContractCollection.js';\nimport { SalesContractCollection } from './SalesContractCollection.js';\n\nexport class ContractCollection extends SmrtCollection<Contract> {\n static readonly _itemClass = Contract;\n\n private async withMoneyRead<T>(operation: () => Promise<T>): Promise<T> {\n const rootDb = this.db;\n const tenantId = getTenantId();\n if (!tenantId) return operation();\n const result = await withTenantMoneyCollectionRead(\n rootDb,\n tenantId,\n (boundDb) => this.withDatabase(boundDb, operation),\n );\n if (result instanceof Contract)\n result.rebindMoneyRead(DOCUMENT_MONEY_READ_REBIND, rootDb);\n else if (Array.isArray(result))\n for (const item of result)\n if (item instanceof Contract)\n item.rebindMoneyRead(DOCUMENT_MONEY_READ_REBIND, rootDb);\n return result;\n }\n\n override async get(\n filter: string | SmrtWhereClause<Contract>,\n options: Parameters<SmrtCollection<Contract>['get']>[1] = {},\n ): Promise<Contract | null> {\n return this.withMoneyRead(() => super.get(filter, options));\n }\n\n override async list<\n const Select extends readonly SmrtSelectField<Contract>[],\n >(\n options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {\n select: Select;\n include?: never;\n stiScope: SmrtStiReadScope;\n },\n ): Promise<Record<string, unknown>[]>;\n override async list<\n const Select extends readonly SmrtSelectField<Contract>[],\n >(\n options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {\n select: Select;\n include?: never;\n stiScope?: undefined;\n },\n ): Promise<SmrtSelectedRow<Contract, Select>[]>;\n override async list(\n options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {\n select?: undefined;\n stiScope: SmrtStiReadScope;\n },\n ): Promise<SmrtObject[]>;\n override async list(options?: undefined): Promise<Contract[]>;\n override async list(\n options: Omit<SmrtListOptions<Contract>, 'select' | 'stiScope'> & {\n select?: undefined;\n stiScope?: undefined;\n },\n ): Promise<Contract[]>;\n override async list(\n options:\n | (Omit<SmrtListOptions<Contract>, 'select'> & { select?: undefined })\n | undefined,\n ): Promise<SmrtObject[]>;\n override async list(\n options: SmrtListOptions<Contract> | undefined,\n ): Promise<SmrtObject[] | Record<string, unknown>[]>;\n override async list(\n options: SmrtListOptions<Contract> = {},\n ): Promise<SmrtObject[] | Record<string, unknown>[]> {\n return this.withMoneyRead(() => super.list(options));\n }\n\n /**\n * Find contracts by customer\n *\n * @param customerId - Customer ID\n * @returns Array of contracts\n * @deprecated Use SalesContractCollection.findByCustomer.\n */\n async findByCustomer(customerId: string): Promise<Contract[]> {\n const sales = await SalesContractCollection.create({\n ...this.options,\n db: this.db,\n });\n return sales.findByCustomer(customerId);\n }\n\n /**\n * Find contracts by vendor\n *\n * @param vendorId - Vendor ID\n * @returns Array of contracts\n * @deprecated Use PurchaseContractCollection.findByVendor.\n */\n async findByVendor(vendorId: string): Promise<Contract[]> {\n const purchases = await PurchaseContractCollection.create({\n ...this.options,\n db: this.db,\n });\n return purchases.findByVendor(vendorId);\n }\n\n /**\n * Hydrate a bounded tenant/date report candidate set once, retaining exact\n * STI descendants so callers can classify custom purchase types safely.\n */\n async listSnapshotReportContracts(options: {\n tenantId: string;\n from: Date;\n to: Date;\n }): Promise<Contract[]> {\n const contracts = await this.list({\n where: {\n tenantId: options.tenantId,\n 'issueDate >=': options.from.toISOString(),\n 'issueDate <=': options.to.toISOString(),\n },\n orderBy: 'issueDate ASC',\n });\n return contracts.filter(isContractSnapshotReportEligible);\n }\n\n /**\n * Find contracts by type (STI)\n *\n * @param contractType - Contract type\n * @returns Array of contracts\n */\n async findByType(contractType: ContractType): Promise<Contract[]> {\n return await this.list({\n where: { contractType },\n orderBy: 'created_at DESC',\n });\n }\n\n /**\n * Find contracts by status\n *\n * @param status - Contract status\n * @returns Array of contracts\n */\n async findByStatus(status: ContractStatus): Promise<Contract[]> {\n return await this.list({\n where: { status },\n orderBy: 'created_at DESC',\n });\n }\n\n /**\n * Find all draft contracts\n *\n * @returns Array of draft contracts\n */\n async findDrafts(): Promise<Contract[]> {\n return await this.findByStatus(ContractStatus.DRAFT);\n }\n\n /**\n * Find all accepted contracts\n *\n * @returns Array of accepted contracts\n */\n async findAccepted(): Promise<Contract[]> {\n return await this.findByStatus(ContractStatus.ACCEPTED);\n }\n\n /**\n * Find overdue contracts\n *\n * @returns Array of overdue contracts\n */\n async findOverdue(): Promise<Contract[]> {\n const now = new Date().toISOString();\n // Get all contracts past due date that aren't completed or cancelled\n const all = await this.list({\n where: {\n 'dueDate <': now,\n },\n orderBy: 'dueDate ASC',\n });\n return all.filter(\n (c) =>\n c.status !== ContractStatus.COMPLETED &&\n c.status !== ContractStatus.CANCELLED,\n );\n }\n\n /**\n * Find expired estimates/quotes\n *\n * @returns Array of expired estimates\n */\n async findExpired(): Promise<Contract[]> {\n const now = new Date().toISOString();\n // Get estimates past expiry date that aren't accepted, declined, or cancelled\n const estimates = await this.list({\n where: {\n contractType: ContractType.ESTIMATE,\n 'expiryDate <': now,\n },\n orderBy: 'expiryDate ASC',\n });\n return estimates.filter(\n (c) =>\n c.status !== ContractStatus.ACCEPTED &&\n c.status !== ContractStatus.DECLINED &&\n c.status !== ContractStatus.CANCELLED,\n );\n }\n\n /**\n * Find contracts in date range\n *\n * @param startDate - Start date\n * @param endDate - End date\n * @returns Array of contracts\n */\n async findByDateRange(startDate: Date, endDate: Date): Promise<Contract[]> {\n return await this.list({\n where: {\n 'issueDate >=': startDate.toISOString(),\n 'issueDate <=': endDate.toISOString(),\n },\n orderBy: 'issueDate DESC',\n });\n }\n\n // ============================================================================\n // Tenant Helper Methods\n // ============================================================================\n\n /**\n * Find all contracts belonging to a specific tenant\n *\n * @param tenantId - Tenant ID\n * @returns Array of contracts for the tenant\n */\n async findByTenant(tenantId: string): Promise<Contract[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global contracts (not associated with any tenant).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context (an explicit `tenant_id IS NULL` filter would be\n * flagged as an isolation violation). (#1600)\n *\n * @returns Array of global contracts\n */\n async findGlobal(): Promise<Contract[]> {\n return queryGlobal<Contract>(this);\n }\n\n /**\n * Find contracts for a tenant including global contracts.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID\n * @returns Array of tenant-specific and global contracts\n */\n async findWithGlobals(tenantId: string): Promise<Contract[]> {\n return queryWithGlobals<Contract>(\n this,\n tenantId,\n 'Contract.findWithGlobals',\n );\n }\n}\n","/** Persisted per-code/component tax totals for a commerce document. */\n\nimport {\n field,\n SmrtObject,\n type SmrtObjectOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport {\n DOCUMENT_MONEY_WRITE,\n type DocumentMoneyWriteCapability,\n} from '../document-money-internal.js';\nimport { MoneyValidationError, type TaxCodeKind } from '../money.js';\n\nexport type CommerceDocumentType = 'invoice' | 'contract' | 'credit_note';\n\nexport interface DocumentTaxOptions extends SmrtObjectOptions {\n tenantId?: string;\n documentType?: CommerceDocumentType;\n documentId?: string;\n currency?: string;\n taxCodeId?: string | null;\n taxCodeCode?: string | null;\n kind?: TaxCodeKind | null;\n taxComponentId?: string | null;\n taxComponentName?: string | null;\n percent?: string | null;\n liabilityAccountId?: string | null;\n taxableMinor?: number;\n taxMinor?: number;\n recoverableMinor?: number;\n}\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'document_taxes',\n conflictColumns: [\n 'document_type',\n 'document_id',\n 'tax_code_id',\n 'tax_component_id',\n ],\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class DocumentTax extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @tenantId()\n tenantId = '';\n\n @field({ required: true })\n documentType: CommerceDocumentType = 'invoice';\n\n @field({ required: true })\n documentId = '';\n\n @field({ required: true })\n currency = 'USD';\n\n @field({ nullable: true })\n taxCodeId: string | null = null;\n\n @field({ nullable: true })\n taxCodeCode: string | null = null;\n\n @field({ nullable: true })\n kind: TaxCodeKind | null = null;\n\n @field({ nullable: true })\n taxComponentId: string | null = null;\n\n @field({ nullable: true })\n taxComponentName: string | null = null;\n\n @field({ type: 'decimal', nullable: true })\n percent: string | null = null;\n\n @field({ nullable: true })\n liabilityAccountId: string | null = null;\n\n @field({\n description: 'Tax-exclusive base in integer minor units.',\n ui: { format: 'money' },\n })\n taxableMinor = 0;\n\n @field({\n description: 'Tax total in integer minor units.',\n ui: { format: 'money' },\n })\n taxMinor = 0;\n\n @field({\n description: 'Recoverable purchase tax in integer minor units.',\n ui: { format: 'money' },\n })\n recoverableMinor = 0;\n\n constructor(options: DocumentTaxOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.documentType !== undefined)\n this.documentType = options.documentType;\n if (options.documentId !== undefined) this.documentId = options.documentId;\n if (options.currency !== undefined) this.currency = options.currency;\n if (options.taxCodeId !== undefined) this.taxCodeId = options.taxCodeId;\n if (options.taxCodeCode !== undefined)\n this.taxCodeCode = options.taxCodeCode;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.taxComponentId !== undefined)\n this.taxComponentId = options.taxComponentId;\n if (options.taxComponentName !== undefined)\n this.taxComponentName = options.taxComponentName;\n if (options.percent !== undefined) this.percent = options.percent;\n if (options.liabilityAccountId !== undefined)\n this.liabilityAccountId = options.liabilityAccountId;\n if (options.taxableMinor !== undefined)\n this.taxableMinor = options.taxableMinor;\n if (options.taxMinor !== undefined) this.taxMinor = options.taxMinor;\n if (options.recoverableMinor !== undefined)\n this.recoverableMinor = options.recoverableMinor;\n }\n\n private assertValidDerivedRow(): void {\n if (!['invoice', 'contract', 'credit_note'].includes(this.documentType)) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `Unknown document tax type: ${this.documentType}`,\n );\n }\n for (const [label, value] of [\n ['tenantId', this.tenantId],\n ['documentId', this.documentId],\n ['currency', this.currency],\n ] as const) {\n if (!value || value.trim() !== value) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `DocumentTax ${label} must be a nonempty value`,\n );\n }\n }\n for (const [label, value] of [\n ['taxableMinor', this.taxableMinor],\n ['taxMinor', this.taxMinor],\n ['recoverableMinor', this.recoverableMinor],\n ] as const) {\n if (!Number.isSafeInteger(value)) {\n throw new MoneyValidationError(\n 'UNSAFE_MONEY',\n `DocumentTax ${label} must be safe integer minor units`,\n );\n }\n }\n if (this.taxCodeId === null) {\n if (\n this.taxComponentId !== null ||\n this.taxCodeCode !== null ||\n this.kind !== null ||\n this.taxComponentName !== null ||\n this.percent !== null ||\n this.liabilityAccountId !== null ||\n this.taxMinor !== 0 ||\n this.recoverableMinor !== 0\n ) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'An unassigned DocumentTax row cannot carry code/component snapshots or tax',\n );\n }\n return;\n }\n if (!this.taxCodeCode || !this.kind) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Assigned DocumentTax rows require code and kind snapshots',\n );\n }\n if (this.taxComponentId === null) {\n if (\n this.kind === 'taxable' ||\n this.taxComponentName !== null ||\n this.percent !== null ||\n this.liabilityAccountId !== null ||\n this.taxMinor !== 0 ||\n this.recoverableMinor !== 0\n ) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Component-less DocumentTax rows must be non-taxable zero-tax snapshots',\n );\n }\n return;\n }\n if (this.kind !== 'taxable' || !this.taxComponentName || !this.percent) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Component DocumentTax rows require taxable component snapshots',\n );\n }\n if (\n this.recoverableMinor !== 0 &&\n this.recoverableMinor !== this.taxMinor\n ) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'DocumentTax recoverableMinor must be zero or the component tax total',\n );\n }\n }\n\n override async save(): Promise<this> {\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'DocumentTax rows are derived and cannot be saved directly',\n );\n }\n\n override async delete(\n _options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'DocumentTax rows are derived and cannot be deleted directly',\n );\n }\n\n /** @internal Aggregate persistence only. */\n async saveDerived(capability: DocumentMoneyWriteCapability): Promise<this> {\n if (capability !== DOCUMENT_MONEY_WRITE) {\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'DocumentTax write capability is required',\n );\n }\n this.assertValidDerivedRow();\n return (await super.save()) as this;\n }\n\n /** @internal Aggregate persistence only. */\n async deleteDerived(\n capability: DocumentMoneyWriteCapability,\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n if (capability !== DOCUMENT_MONEY_WRITE) {\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'DocumentTax write capability is required',\n );\n }\n await super.delete(options);\n }\n}\n","/** Owning collection for derived document tax totals. */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { withTenant } from '@happyvertical/smrt-tenancy';\nimport {\n DOCUMENT_MONEY_WRITE,\n type DocumentMoneyWriteCapability,\n} from '../document-money-internal.js';\nimport { classifyContractPurchase } from '../models/Contract.js';\nimport {\n type CommerceDocumentType,\n DocumentTax,\n type DocumentTaxOptions,\n} from '../models/DocumentTax.js';\nimport { MoneyValidationError, type TaxCodeKind } from '../money.js';\nimport { ContractCollection } from './ContractCollection.js';\n\nexport type DocumentTaxWriteInput = Required<\n Pick<\n DocumentTaxOptions,\n | 'tenantId'\n | 'documentType'\n | 'documentId'\n | 'currency'\n | 'taxCodeId'\n | 'taxCodeCode'\n | 'kind'\n | 'taxComponentId'\n | 'taxComponentName'\n | 'percent'\n | 'liabilityAccountId'\n | 'taxableMinor'\n | 'taxMinor'\n | 'recoverableMinor'\n >\n>;\n\n/** Normalized immutable document-tax snapshots for tax-summary materialization. */\nexport interface DocumentTaxReportFact {\n tenantId: string;\n documentType: CommerceDocumentType;\n documentId: string;\n /** A document number/reference supplied to drilldown consumers. */\n documentNumber: string;\n /** Tenant-scoped party identity for a host to resolve as its party display. */\n partyId: string | null;\n /** Positive credit snapshots are negated once by the pure report aggregation. */\n documentKind: CommerceDocumentType;\n issueDate: string;\n status: string;\n direction: 'sales' | 'purchase';\n currency: string;\n taxCodeId: string | null;\n /** Null is an unassigned/unknown snapshot and must remain visible as a warning. */\n taxCodeKind: TaxCodeKind | null;\n taxableMinor: number;\n taxMinor: number;\n recoverableMinor: number;\n taxComponentId: string | null;\n componentName: string | null;\n liabilityAccountId: string | null;\n /** Purchase Contracts are the expense commitment identity; other documents are unlinked. */\n commitmentId: string | null;\n /** Document-tax snapshots are contract-level, so they retain no line allocation. */\n commitmentLineId: string | null;\n}\n\n/** @deprecated Use DocumentTaxReportFact. Kept for report-adapter compatibility. */\nexport type InvoiceTaxReportFact = DocumentTaxReportFact;\n\nexport interface DocumentTaxReportFactsOptions {\n tenantId: string;\n from: Date;\n to: Date;\n currency?: string;\n}\n\n/** @deprecated Use DocumentTaxReportFactsOptions. */\nexport type InvoiceTaxReportFactsOptions = DocumentTaxReportFactsOptions;\n\nconst TAX_CODE_KINDS = new Set<TaxCodeKind>([\n 'taxable',\n 'zero-rated',\n 'exempt',\n 'out-of-scope',\n]);\n\nfunction requiredText(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim())\n throw new Error(`Invoice tax report ${label} must be a nonempty string.`);\n return value;\n}\n\nfunction storedMinor(value: unknown, label: string): number {\n const parsed =\n typeof value === 'bigint'\n ? Number(value)\n : typeof value === 'number'\n ? value\n : typeof value === 'string' && /^-?\\d+$/.test(value)\n ? Number(value)\n : Number.NaN;\n if (!Number.isSafeInteger(parsed))\n throw new RangeError(\n `Invoice tax report ${label} must be a safe integer minor-unit value.`,\n );\n return parsed;\n}\n\nfunction reportDate(value: unknown, label: string): string {\n const date = new Date(String(value));\n if (Number.isNaN(date.getTime()))\n throw new Error(`Invoice tax report ${label} must be a valid date.`);\n return date.toISOString();\n}\n\nfunction invoiceDocumentType(value: unknown): 'invoice' | 'credit_note' {\n if (value === 'invoice' || value === 'credit_note') return value;\n throw new Error(\n 'Invoice tax report document type must be invoice or credit_note.',\n );\n}\n\nfunction invoiceKind(value: unknown): 'invoice' | 'credit_note' {\n if (value === 'invoice' || value === 'credit_note') return value;\n throw new Error('Invoice tax report kind must be invoice or credit_note.');\n}\n\nfunction contractDocumentType(value: unknown): 'contract' {\n if (value === 'contract') return value;\n throw new Error('Contract tax report document type must be contract.');\n}\n\nfunction taxCodeKind(value: unknown): TaxCodeKind | null {\n return typeof value === 'string' && TAX_CODE_KINDS.has(value as TaxCodeKind)\n ? (value as TaxCodeKind)\n : null;\n}\n\nfunction assertReportFactOptions(options: DocumentTaxReportFactsOptions): void {\n if (!options.tenantId?.trim())\n throw new Error('Invoice tax report facts require a tenant.');\n if (!(options.from instanceof Date) || Number.isNaN(options.from.getTime()))\n throw new Error('Invoice tax report facts require a valid start date.');\n if (!(options.to instanceof Date) || Number.isNaN(options.to.getTime()))\n throw new Error('Invoice tax report facts require a valid end date.');\n if (options.from > options.to)\n throw new Error('Invoice tax report facts require an ordered date range.');\n if (options.currency !== undefined && !options.currency.trim())\n throw new Error(\n 'Invoice tax report currency must be nonempty when supplied.',\n );\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction identity(\n row: Pick<DocumentTaxWriteInput, 'taxCodeId' | 'taxComponentId'>,\n): string {\n return `${row.taxCodeId === null ? '0:' : `1:${row.taxCodeId}`}\\u0000${\n row.taxComponentId === null ? '0:' : `1:${row.taxComponentId}`\n }`;\n}\n\nconst BUSINESS_FIELDS = [\n 'tenantId',\n 'documentType',\n 'documentId',\n 'currency',\n 'taxCodeId',\n 'taxCodeCode',\n 'kind',\n 'taxComponentId',\n 'taxComponentName',\n 'percent',\n 'liabilityAccountId',\n 'taxableMinor',\n 'taxMinor',\n 'recoverableMinor',\n] as const;\n\nfunction unchanged(row: DocumentTax, input: DocumentTaxWriteInput): boolean {\n return BUSINESS_FIELDS.every((field) => {\n const persisted = row[field];\n const proposed = input[field];\n if (field === 'percent' && persisted !== null && proposed !== null) {\n return String(persisted) === String(proposed);\n }\n return (persisted ?? null) === (proposed ?? null);\n });\n}\n\nexport class DocumentTaxCollection extends SmrtCollection<DocumentTax> {\n static readonly _itemClass = DocumentTax;\n\n /**\n * Read immutable commerce document-tax snapshots for one tenant.\n *\n * Invoice/credit rows join their shared storage by identity and tenant.\n * Purchase Contract rows first use the Contract owner's bounded hydrated\n * candidate API so custom PurchaseContract descendants retain their STI\n * classification. The query then joins only those candidate ids by identity\n * and tenant. Stored snapshots remain authoritative; this never recalculates\n * money or resolves present-day tax configuration.\n */\n async listReportFacts(\n options: DocumentTaxReportFactsOptions,\n ): Promise<DocumentTaxReportFact[]> {\n assertReportFactOptions(options);\n const [invoiceFacts, purchaseFacts] = await Promise.all([\n this.listInvoiceReportFacts(options),\n this.listPurchaseContractReportFacts(options),\n ]);\n return [...invoiceFacts, ...purchaseFacts].sort(\n (left, right) =>\n left.issueDate.localeCompare(right.issueDate) ||\n left.documentId.localeCompare(right.documentId) ||\n String(left.taxCodeId).localeCompare(String(right.taxCodeId)) ||\n String(left.taxComponentId).localeCompare(String(right.taxComponentId)),\n );\n }\n\n private async listInvoiceReportFacts(\n options: DocumentTaxReportFactsOptions,\n ): Promise<DocumentTaxReportFact[]> {\n const currencyClause = options.currency ? ' AND d.currency = ?' : '';\n const result = await this.db.query(\n `SELECT d.tenant_id, d.document_type, d.document_id, d.currency, d.tax_code_id, d.kind,\n d.tax_component_id, d.tax_component_name, d.liability_account_id,\n d.taxable_minor, d.tax_minor, d.recoverable_minor,\n i.kind AS invoice_kind, i.invoice_number, i.customer_id, i.issue_date, i.status\n FROM document_taxes d\n JOIN invoices i\n ON CAST(i.id AS TEXT) = CAST(d.document_id AS TEXT)\n AND i.tenant_id = d.tenant_id\n WHERE CAST(d.tenant_id AS TEXT) = ?\n AND CAST(i.tenant_id AS TEXT) = ?\n AND (\n (d.document_type = 'invoice' AND i.kind = 'invoice')\n OR (d.document_type = 'credit_note' AND i.kind = 'credit_note')\n )\n AND i.status NOT IN ('draft', 'cancelled')\n AND i.issue_date >= ?\n AND i.issue_date <= ?${currencyClause}\n ORDER BY i.issue_date ASC, i.id ASC, d.tax_code_id ASC, d.tax_component_id ASC`,\n options.tenantId,\n options.tenantId,\n options.from.toISOString(),\n options.to.toISOString(),\n ...(options.currency ? [options.currency] : []),\n );\n return result.rows.map((row) => ({\n tenantId: requiredText(row.tenant_id, 'tenant id'),\n documentType: invoiceDocumentType(row.document_type),\n documentId: requiredText(row.document_id, 'document id'),\n documentNumber: requiredText(row.invoice_number, 'invoice number'),\n partyId:\n typeof row.customer_id === 'string' && row.customer_id.trim()\n ? row.customer_id\n : null,\n documentKind: invoiceKind(row.invoice_kind),\n issueDate: reportDate(row.issue_date, 'issue date'),\n status: requiredText(row.status, 'invoice status'),\n direction: 'sales' as const,\n currency: requiredText(row.currency, 'currency'),\n taxCodeId: row.tax_code_id == null ? null : String(row.tax_code_id),\n taxCodeKind: taxCodeKind(row.kind),\n taxableMinor: storedMinor(row.taxable_minor, 'taxable minor'),\n taxMinor: storedMinor(row.tax_minor, 'tax minor'),\n recoverableMinor: storedMinor(row.recoverable_minor, 'recoverable minor'),\n taxComponentId:\n row.tax_component_id == null ? null : String(row.tax_component_id),\n componentName:\n row.tax_component_name == null ? null : String(row.tax_component_name),\n liabilityAccountId:\n row.liability_account_id == null\n ? null\n : String(row.liability_account_id),\n commitmentId: null,\n commitmentLineId: null,\n }));\n }\n\n private async listPurchaseContractReportFacts(\n options: DocumentTaxReportFactsOptions,\n ): Promise<DocumentTaxReportFact[]> {\n const contracts = await withTenant({ tenantId: options.tenantId }, () =>\n ContractCollection.create({ db: this.db }).then((collection) =>\n collection.listSnapshotReportContracts({\n tenantId: options.tenantId,\n from: options.from,\n to: options.to,\n }),\n ),\n );\n const purchases = contracts.filter(classifyContractPurchase);\n const ids = purchases.flatMap((contract) =>\n contract.id ? [contract.id] : [],\n );\n if (ids.length === 0) return [];\n const byId = new Map(\n purchases.flatMap((contract) =>\n contract.id ? ([[contract.id, contract]] as const) : [],\n ),\n );\n const placeholders = ids.map(() => '?').join(', ');\n const currencyClause = options.currency ? ' AND d.currency = ?' : '';\n const result = await this.db.query(\n `SELECT d.tenant_id, d.document_type, d.document_id, d.currency, d.tax_code_id, d.kind,\n d.tax_component_id, d.tax_component_name, d.liability_account_id,\n d.taxable_minor, d.tax_minor, d.recoverable_minor\n FROM document_taxes d\n JOIN contracts c\n ON CAST(c.id AS TEXT) = CAST(d.document_id AS TEXT)\n AND c.tenant_id = d.tenant_id\n WHERE CAST(d.tenant_id AS TEXT) = ?\n AND CAST(c.tenant_id AS TEXT) = ?\n AND d.document_type = 'contract'\n AND c.status NOT IN ('draft', 'cancelled')\n AND CAST(d.document_id AS TEXT) IN (${placeholders})${currencyClause}\n ORDER BY c.issue_date ASC, c.id ASC, d.tax_code_id ASC, d.tax_component_id ASC`,\n options.tenantId,\n options.tenantId,\n ...ids,\n ...(options.currency ? [options.currency] : []),\n );\n return result.rows.flatMap((row): DocumentTaxReportFact[] => {\n const documentId = requiredText(row.document_id, 'contract id');\n const contract = byId.get(documentId);\n if (!contract) return [];\n return [\n {\n tenantId: requiredText(row.tenant_id, 'tenant id'),\n documentType: contractDocumentType(row.document_type),\n documentId,\n documentNumber: contract.reference.trim() || documentId,\n partyId:\n 'vendorId' in contract &&\n typeof contract.vendorId === 'string' &&\n contract.vendorId.trim()\n ? contract.vendorId\n : null,\n documentKind: 'contract',\n issueDate: reportDate(contract.issueDate, 'contract issue date'),\n status: requiredText(contract.status, 'contract status'),\n direction: 'purchase',\n currency: requiredText(row.currency, 'currency'),\n taxCodeId: row.tax_code_id == null ? null : String(row.tax_code_id),\n taxCodeKind: taxCodeKind(row.kind),\n taxableMinor: storedMinor(row.taxable_minor, 'taxable minor'),\n taxMinor: storedMinor(row.tax_minor, 'tax minor'),\n recoverableMinor: storedMinor(\n row.recoverable_minor,\n 'recoverable minor',\n ),\n taxComponentId:\n row.tax_component_id == null ? null : String(row.tax_component_id),\n componentName:\n row.tax_component_name == null\n ? null\n : String(row.tax_component_name),\n liabilityAccountId:\n row.liability_account_id == null\n ? null\n : String(row.liability_account_id),\n // Expenses reference their PurchaseContract id as commitmentId.\n commitmentId: documentId,\n commitmentLineId: null,\n },\n ];\n });\n }\n\n async findByDocument(\n tenantId: string,\n documentType: CommerceDocumentType,\n documentId: string,\n ): Promise<DocumentTax[]> {\n return this.list({\n where: { tenantId, documentType, documentId },\n orderBy: ['taxCodeId ASC', 'taxComponentId ASC'],\n });\n }\n\n /**\n * Replace one draft document's derived rows on the caller's transaction.\n * Unchanged rows are not saved, preserving their exact persisted bytes.\n *\n * @internal Aggregate persistence only.\n */\n async replaceDerivedForDocument(\n capability: DocumentMoneyWriteCapability,\n input: {\n tenantId: string;\n documentType: CommerceDocumentType;\n documentId: string;\n rows: readonly DocumentTaxWriteInput[];\n },\n ): Promise<DocumentTax[]> {\n if (capability !== DOCUMENT_MONEY_WRITE) {\n throw new MoneyValidationError(\n 'FROZEN_DOCUMENT',\n 'DocumentTax write capability is required',\n );\n }\n const desired = new Map<string, DocumentTaxWriteInput>();\n for (const row of input.rows) {\n if (\n row.tenantId !== input.tenantId ||\n row.documentType !== input.documentType ||\n row.documentId !== input.documentId\n ) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'DocumentTax replacement rows must share tenant and document identity',\n );\n }\n const key = identity(row);\n if (desired.has(key)) {\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'DocumentTax replacement contains a duplicate code/component identity',\n );\n }\n desired.set(key, row);\n }\n\n const existing = await this.findByDocument(\n input.tenantId,\n input.documentType,\n input.documentId,\n );\n const byIdentity = new Map(existing.map((row) => [identity(row), row]));\n const result: DocumentTax[] = [];\n for (const [key, rowInput] of [...desired].sort(([left], [right]) =>\n compareCodeUnits(left, right),\n )) {\n const current = byIdentity.get(key);\n if (current) {\n byIdentity.delete(key);\n if (!unchanged(current, rowInput)) {\n Object.assign(current, rowInput);\n await current.saveDerived(capability);\n }\n result.push(current);\n continue;\n }\n const created = await this.createUnsaved(rowInput);\n await created.saveDerived(capability);\n result.push(created);\n }\n for (const stale of [...byIdentity.values()].sort((left, right) =>\n compareCodeUnits(String(left.id), String(right.id)),\n )) {\n await stale.deleteDerived(capability, {\n expectedUpdatedAt: stale.updated_at ?? undefined,\n });\n }\n return result;\n }\n}\n"],"mappings":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