@happyvertical/smrt-commerce 0.62.4 → 0.62.6

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 (74) hide show
  1. package/AGENTS.md +1 -0
  2. package/agents/accounting-connection.md +76 -0
  3. package/agents/accounting-live-gate.md +40 -0
  4. package/agents/accounting-mapping.md +60 -0
  5. package/agents/accounting-payment-sync.md +76 -0
  6. package/agents/ordinary-accounting.md +3 -0
  7. package/dist/accounting-connection.d.ts +179 -0
  8. package/dist/accounting-connection.d.ts.map +1 -0
  9. package/dist/accounting-live-gate.d.ts +50 -0
  10. package/dist/accounting-live-gate.d.ts.map +1 -0
  11. package/dist/accounting-mapping.d.ts +189 -0
  12. package/dist/accounting-mapping.d.ts.map +1 -0
  13. package/dist/accounting-payment-sync.d.ts +233 -0
  14. package/dist/accounting-payment-sync.d.ts.map +1 -0
  15. package/dist/chunks/{InvoiceCollection-Cc-fJrHy.js → InvoiceCollection-xooQnUwq.js} +10 -10
  16. package/dist/chunks/{InvoiceCollection-Cc-fJrHy.js.map → InvoiceCollection-xooQnUwq.js.map} +1 -1
  17. package/dist/chunks/{allocation-integrity-CvXQm3wK.js → allocation-integrity-C4SZJcao.js} +6 -6
  18. package/dist/chunks/{allocation-integrity-CvXQm3wK.js.map → allocation-integrity-C4SZJcao.js.map} +1 -1
  19. package/dist/chunks/{contract-money-BoKHNfV6.js → contract-money-ATacxU6t.js} +4 -7
  20. package/dist/chunks/{contract-money-BoKHNfV6.js.map → contract-money-ATacxU6t.js.map} +1 -1
  21. package/dist/chunks/{invoice-posting-DlR_-TG1.js → invoice-posting-CDfxug3Q.js} +4 -5
  22. package/dist/chunks/{invoice-posting-DlR_-TG1.js.map → invoice-posting-CDfxug3Q.js.map} +1 -1
  23. package/dist/chunks/retention-accounting-BA4wXUQc.js +8710 -0
  24. package/dist/chunks/retention-accounting-BA4wXUQc.js.map +1 -0
  25. package/dist/chunks/{tenant-money-barrier-Bmu4YiID.js → tenant-money-barrier-BdyXIVT5.js} +3 -3
  26. package/dist/chunks/{tenant-money-barrier-Bmu4YiID.js.map → tenant-money-barrier-BdyXIVT5.js.map} +1 -1
  27. package/dist/collections/AccountingConnectionCollection.d.ts +27 -0
  28. package/dist/collections/AccountingConnectionCollection.d.ts.map +1 -0
  29. package/dist/collections/AccountingMappingCollection.d.ts +24 -0
  30. package/dist/collections/AccountingMappingCollection.d.ts.map +1 -0
  31. package/dist/collections/AccountingSyncRecordCollections.d.ts +27 -0
  32. package/dist/collections/AccountingSyncRecordCollections.d.ts.map +1 -0
  33. package/dist/collections/index.d.ts +3 -0
  34. package/dist/collections/index.d.ts.map +1 -1
  35. package/dist/index.d.ts +10 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1532 -21
  38. package/dist/index.js.map +1 -1
  39. package/dist/invoice-accounting-sync.d.ts +6 -0
  40. package/dist/invoice-accounting-sync.d.ts.map +1 -1
  41. package/dist/invoices.js +1 -1
  42. package/dist/manifest.json +6303 -3740
  43. package/dist/models/AccountingConnection.d.ts +101 -0
  44. package/dist/models/AccountingConnection.d.ts.map +1 -0
  45. package/dist/models/AccountingMapping.d.ts +85 -0
  46. package/dist/models/AccountingMapping.d.ts.map +1 -0
  47. package/dist/models/AccountingSyncRecords.d.ts +95 -0
  48. package/dist/models/AccountingSyncRecords.d.ts.map +1 -0
  49. package/dist/models/index.d.ts +3 -0
  50. package/dist/models/index.d.ts.map +1 -1
  51. package/dist/ordinary-accounting.d.ts +1 -0
  52. package/dist/ordinary-accounting.d.ts.map +1 -1
  53. package/dist/recipes.d.ts +1 -1
  54. package/dist/retention-accounting.d.ts +1 -0
  55. package/dist/retention-accounting.d.ts.map +1 -1
  56. package/dist/smrt-knowledge.json +1327 -99
  57. package/dist/smrt-knowledge.okf.md +55 -23
  58. package/package.json +15 -15
  59. package/dist/chunks/ContractLineItemCollection-BKHy-nR8.js +0 -260
  60. package/dist/chunks/ContractLineItemCollection-BKHy-nR8.js.map +0 -1
  61. package/dist/chunks/DocumentTaxCollection-BRebznXF.js +0 -4649
  62. package/dist/chunks/DocumentTaxCollection-BRebznXF.js.map +0 -1
  63. package/dist/chunks/TaxCodeCollection-BBqCugs5.js +0 -155
  64. package/dist/chunks/TaxCodeCollection-BBqCugs5.js.map +0 -1
  65. package/dist/chunks/TaxComponentCollection-BHJjbQxq.js +0 -134
  66. package/dist/chunks/TaxComponentCollection-BHJjbQxq.js.map +0 -1
  67. package/dist/chunks/credit-allocation-yspz0Lab.js +0 -121
  68. package/dist/chunks/credit-allocation-yspz0Lab.js.map +0 -1
  69. package/dist/chunks/retention-accounting-D0KzSw3f.js +0 -3069
  70. package/dist/chunks/retention-accounting-D0KzSw3f.js.map +0 -1
  71. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js +0 -30
  72. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js.map +0 -1
  73. package/dist/chunks/units-8ElbjVZK.js +0 -60
  74. package/dist/chunks/units-8ElbjVZK.js.map +0 -1
@@ -1,155 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { MoneyValidationError } from "../money.js";
3
- import { SmrtCollection, SmrtObject, field, smrt } from "@happyvertical/smrt-core";
4
- import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
5
- //#region src/models/TaxCode.ts
6
- var __defProp = Object.defineProperty;
7
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
9
- enumerable: true,
10
- configurable: true,
11
- writable: true,
12
- value
13
- }) : obj[key] = value;
14
- var __decorateClass = (decorators, target, key, kind) => {
15
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
16
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
17
- if (kind && result) __defProp(target, key, result);
18
- return result;
19
- };
20
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
- var TaxCode = class extends SmrtObject {
22
- tenantId = "";
23
- code = "";
24
- name = "";
25
- kind = "taxable";
26
- appliesTo = "both";
27
- /** Ordered component IDs; compound includes every preceding component in this code. */
28
- /** Stored JSON is guarded through the typed accessor below. */
29
- componentsJson = "[]";
30
- get components() {
31
- try {
32
- const value = JSON.parse(this.componentsJson);
33
- if (!Array.isArray(value)) return [];
34
- return value.filter((part) => !!part && typeof part === "object" && typeof part.taxComponentId === "string" && typeof part.compound === "boolean");
35
- } catch {
36
- return [];
37
- }
38
- }
39
- set components(value) {
40
- this.componentsJson = typeof value === "string" ? value : JSON.stringify(value);
41
- }
42
- active = true;
43
- constructor(options = {}) {
44
- super(options);
45
- if (options.tenantId !== void 0) this.tenantId = options.tenantId ?? "";
46
- if (options.code !== void 0) this.code = options.code;
47
- if (options.name !== void 0) this.name = options.name;
48
- if (options.kind !== void 0) this.kind = options.kind;
49
- if (options.appliesTo !== void 0) this.appliesTo = options.appliesTo;
50
- if (options.components !== void 0) this.components = structuredClone(options.components);
51
- if (options.active !== void 0) this.active = options.active;
52
- }
53
- async save(options) {
54
- if (!this.code.trim() || !this.name.trim()) throw new Error("Tax code requires a nonempty code and name");
55
- if (![
56
- "taxable",
57
- "zero-rated",
58
- "exempt",
59
- "out-of-scope"
60
- ].includes(this.kind)) throw new Error("Tax code kind is invalid");
61
- if (![
62
- "sales",
63
- "purchases",
64
- "both"
65
- ].includes(this.appliesTo)) throw new Error("Tax code appliesTo is invalid");
66
- const parts = this.parsedComponents();
67
- if (!parts) throw new Error("Tax code components must be a valid JSON array");
68
- const nonTaxable = this.kind !== "taxable";
69
- if (nonTaxable && parts.length) throw new MoneyValidationError("TAX_CODE_NON_TAXABLE_COMPONENTS", `${this.kind} tax codes cannot have components.`);
70
- if (!nonTaxable && !parts.length) throw new MoneyValidationError("TAX_CODE_TAXABLE_EMPTY", "Taxable tax codes require at least one component.");
71
- const seen = /* @__PURE__ */ new Set();
72
- for (const component of parts) {
73
- if (seen.has(component.taxComponentId)) throw new MoneyValidationError("TAX_CODE_DUPLICATE_COMPONENT", "A tax code cannot contain the same component twice.");
74
- seen.add(component.taxComponentId);
75
- }
76
- return this.withTransaction(async () => {
77
- const { TaxComponentCollection } = await import("./TaxComponentCollection-BHJjbQxq.js").then((n) => n.n);
78
- const components = await TaxComponentCollection.create({ db: this.db });
79
- for (const part of parts) {
80
- const component = await components.get({ id: part.taxComponentId }, { cache: false });
81
- if (!component) throw new Error("Tax code components must belong to the same tenant");
82
- if (!component.updated_at) throw new Error("Tax code component is missing its revision");
83
- await component.claimRevision(component.updated_at);
84
- if (!this.tenantId) this.tenantId = component.tenantId;
85
- if (component.tenantId !== this.tenantId) throw new Error("Tax code components must belong to the same tenant");
86
- }
87
- return await super.save(options);
88
- });
89
- }
90
- parsedComponents() {
91
- try {
92
- const value = JSON.parse(this.componentsJson);
93
- if (!Array.isArray(value)) return null;
94
- if (value.some((part) => !part || typeof part !== "object" || typeof part.taxComponentId !== "string" || !part.taxComponentId.trim() || typeof part.compound !== "boolean")) return null;
95
- return value;
96
- } catch {
97
- return null;
98
- }
99
- }
100
- };
101
- __publicField(TaxCode, "__smrtPackage__", "@happyvertical/smrt-commerce");
102
- __decorateClass([tenantId()], TaxCode.prototype, "tenantId", 2);
103
- __decorateClass([field({ description: "A stable short code, for example gst-pst-bc." })], TaxCode.prototype, "code", 2);
104
- __decorateClass([field({ description: "The name people see for this tax code." })], TaxCode.prototype, "name", 2);
105
- __decorateClass([field({ description: "How the tax code is reported." })], TaxCode.prototype, "kind", 2);
106
- __decorateClass([field({ description: "Whether the code applies to sales, purchases or both." })], TaxCode.prototype, "appliesTo", 2);
107
- __decorateClass([field({
108
- description: "The ordered tax components in this code.",
109
- transient: true
110
- })], TaxCode.prototype, "components", 1);
111
- __decorateClass([field({ description: "Whether users may select this code for new documents." })], TaxCode.prototype, "active", 2);
112
- TaxCode = __decorateClass([TenantScoped({ mode: "required" }), smrt({
113
- conflictColumns: ["tenant_id", "code"],
114
- api: {
115
- include: [
116
- "list",
117
- "get",
118
- "create",
119
- "update"
120
- ],
121
- writable: [
122
- "code",
123
- "name",
124
- "kind",
125
- "appliesTo",
126
- "components",
127
- "active"
128
- ]
129
- },
130
- mcp: { include: ["list", "get"] },
131
- cli: { skipApiCheck: true }
132
- })], TaxCode);
133
- //#endregion
134
- //#region src/collections/TaxCodeCollection.ts
135
- var TaxCodeCollection_exports = /* @__PURE__ */ __exportAll({ TaxCodeCollection: () => TaxCodeCollection });
136
- var TaxCodeCollection = class extends SmrtCollection {
137
- static _itemClass = TaxCode;
138
- /**
139
- * Find a code by its stable `code`. Pass `tenantId` whenever it is known:
140
- * without an active tenancy filter the lookup is otherwise unscoped.
141
- */
142
- async findByCode(code, tenantId) {
143
- return (await this.list({
144
- where: tenantId ? {
145
- code,
146
- tenantId
147
- } : { code },
148
- limit: 1
149
- }))[0] ?? null;
150
- }
151
- };
152
- //#endregion
153
- export { TaxCodeCollection_exports as n, TaxCode as r, TaxCodeCollection as t };
154
-
155
- //# sourceMappingURL=TaxCodeCollection-BBqCugs5.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaxCodeCollection-BBqCugs5.js","names":[],"sources":["../../src/models/TaxCode.ts","../../src/collections/TaxCodeCollection.ts"],"sourcesContent":["import {\n field,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport { MoneyValidationError } from '../money.js';\nimport type { TaxCodeOptions, TaxCodePart } from '../types/index.js';\n\nexport type TaxCodeKind = 'taxable' | 'zero-rated' | 'exempt' | 'out-of-scope';\nexport type TaxCodeAppliesTo = 'sales' | 'purchases' | 'both';\n\n/** A reusable tax code whose ordered component list is safe to edit. */\n@TenantScoped({ mode: 'required' })\n@smrt({\n conflictColumns: ['tenant_id', 'code'],\n api: {\n include: ['list', 'get', 'create', 'update'],\n writable: ['code', 'name', 'kind', 'appliesTo', 'components', 'active'],\n },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class TaxCode extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @tenantId()\n tenantId = '';\n\n @field({ description: 'A stable short code, for example gst-pst-bc.' })\n code = '';\n\n @field({ description: 'The name people see for this tax code.' })\n name = '';\n\n @field({ description: 'How the tax code is reported.' })\n kind: TaxCodeKind = 'taxable';\n\n @field({\n description: 'Whether the code applies to sales, purchases or both.',\n })\n appliesTo: TaxCodeAppliesTo = 'both';\n\n /** Ordered component IDs; compound includes every preceding component in this code. */\n /** Stored JSON is guarded through the typed accessor below. */\n componentsJson = '[]';\n\n @field({\n description: 'The ordered tax components in this code.',\n transient: true,\n })\n get components(): TaxCodePart[] {\n try {\n const value: unknown = JSON.parse(this.componentsJson);\n if (!Array.isArray(value)) return [];\n return value.filter(\n (part): part is TaxCodePart =>\n !!part &&\n typeof part === 'object' &&\n typeof (part as TaxCodePart).taxComponentId === 'string' &&\n typeof (part as TaxCodePart).compound === 'boolean',\n );\n } catch {\n return [];\n }\n }\n\n set components(value: TaxCodePart[] | string) {\n this.componentsJson =\n typeof value === 'string' ? value : JSON.stringify(value);\n }\n\n @field({\n description: 'Whether users may select this code for new documents.',\n })\n active = true;\n\n constructor(options: TaxCodeOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId ?? '';\n if (options.code !== undefined) this.code = options.code;\n if (options.name !== undefined) this.name = options.name;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.appliesTo !== undefined) this.appliesTo = options.appliesTo;\n if (options.components !== undefined)\n this.components = structuredClone(options.components);\n if (options.active !== undefined) this.active = options.active;\n }\n\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (!this.code.trim() || !this.name.trim())\n throw new Error('Tax code requires a nonempty code and name');\n if (\n !['taxable', 'zero-rated', 'exempt', 'out-of-scope'].includes(this.kind)\n )\n throw new Error('Tax code kind is invalid');\n if (!['sales', 'purchases', 'both'].includes(this.appliesTo))\n throw new Error('Tax code appliesTo is invalid');\n const parts = this.parsedComponents();\n if (!parts)\n throw new Error('Tax code components must be a valid JSON array');\n const nonTaxable = this.kind !== 'taxable';\n if (nonTaxable && parts.length) {\n throw new MoneyValidationError(\n 'TAX_CODE_NON_TAXABLE_COMPONENTS',\n `${this.kind} tax codes cannot have components.`,\n );\n }\n if (!nonTaxable && !parts.length) {\n throw new MoneyValidationError(\n 'TAX_CODE_TAXABLE_EMPTY',\n 'Taxable tax codes require at least one component.',\n );\n }\n const seen = new Set<string>();\n for (const component of parts) {\n if (seen.has(component.taxComponentId)) {\n throw new MoneyValidationError(\n 'TAX_CODE_DUPLICATE_COMPONENT',\n 'A tax code cannot contain the same component twice.',\n );\n }\n seen.add(component.taxComponentId);\n }\n return this.withTransaction(async () => {\n const { TaxComponentCollection } = await import(\n '../collections/TaxComponentCollection.js'\n );\n const components = await TaxComponentCollection.create({ db: this.db });\n for (const part of parts) {\n const component = await components.get(\n { id: part.taxComponentId },\n { cache: false },\n );\n if (!component) {\n throw new Error('Tax code components must belong to the same tenant');\n }\n if (!component.updated_at)\n throw new Error('Tax code component is missing its revision');\n await component.claimRevision(component.updated_at);\n if (!this.tenantId) this.tenantId = component.tenantId;\n if (component.tenantId !== this.tenantId)\n throw new Error('Tax code components must belong to the same tenant');\n }\n return (await super.save(options)) as this;\n });\n }\n\n private parsedComponents(): TaxCodePart[] | null {\n try {\n const value: unknown = JSON.parse(this.componentsJson);\n if (!Array.isArray(value)) return null;\n if (\n value.some(\n (part) =>\n !part ||\n typeof part !== 'object' ||\n typeof (part as TaxCodePart).taxComponentId !== 'string' ||\n !(part as TaxCodePart).taxComponentId.trim() ||\n typeof (part as TaxCodePart).compound !== 'boolean',\n )\n )\n return null;\n return value as TaxCodePart[];\n } catch {\n return null;\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { TaxCode } from '../models/TaxCode.js';\n\nexport class TaxCodeCollection extends SmrtCollection<TaxCode> {\n static readonly _itemClass = TaxCode;\n\n /**\n * Find a code by its stable `code`. Pass `tenantId` whenever it is known:\n * without an active tenancy filter the lookup is otherwise unscoped.\n */\n async findByCode(code: string, tenantId?: string): Promise<TaxCode | null> {\n return (\n (\n await this.list({\n where: tenantId ? { code, tenantId } : { code },\n limit: 1,\n })\n )[0] ?? null\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBO,IAAM,UAAN,cAAsB,WAAW;CAEtC,WAAW;CAGX,OAAO;CAGP,OAAO;CAGP,OAAoB;CAKpB,YAA8B;;;CAI9B,iBAAiB;CAMjB,IAAI,aAA4B;EAC9B,IAAI;GACF,MAAM,QAAiB,KAAK,MAAM,KAAK,cAAc;GACrD,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;GACnC,OAAO,MAAM,QACV,SACC,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,OAAQ,KAAqB,mBAAmB,YAChD,OAAQ,KAAqB,aAAa,SAC9C;EACF,QAAQ;GACN,OAAO,CAAC;EACV;CACF;CAEA,IAAI,WAAW,OAA+B;EAC5C,KAAK,iBACH,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;CAC5D;CAKA,SAAS;CAET,YAAY,UAA0B,CAAC,GAAG;EACxC,MAAM,OAAO;EACb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ,YAAY;EACxE,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,eAAe,KAAA,GACzB,KAAK,aAAa,gBAAgB,QAAQ,UAAU;EACtD,IAAI,QAAQ,WA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,iBAAiB,CAAC,aAAa,MAAM;CACrC,KAAK;EACH,SAAS;GAAC;GAAQ;GAAO;GAAU;EAAQ;EAC3C,UAAU;GAAC;GAAQ;GAAQ;GAAQ;GAAa;GAAc;EAAQ;CACxE;CACA,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;AAC5B,CAAC,CAAA,GACY,OAAA;;;;ACrBN,IAAM,oBAAN,cAAgC,eAAwB;CAC7D,OAAgB,aAAa;;;;;CAM7B,MAAM,WAAW,MAAc,UAA4C;EACzE,QAEI,MAAM,KAAK,KAAK;GACd,OAAO,WAAW;IAAE;IAAM;GAAS,IAAI,EAAE,KAAK;GAC9C,OAAO;EACT,CAAC,EAAA,CACD,MAAM;CAEZ;AACF"}
@@ -1,134 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { MoneyValidationError } from "../money.js";
3
- import { SmrtCollection, SmrtObject, crossPackageRef, field, smrt } from "@happyvertical/smrt-core";
4
- import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
5
- import { AccountCollection } from "@happyvertical/smrt-ledgers";
6
- //#region src/models/TaxComponent.ts
7
- var __defProp = Object.defineProperty;
8
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value
14
- }) : obj[key] = value;
15
- var __decorateClass = (decorators, target, key, kind) => {
16
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
17
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
18
- if (kind && result) __defProp(target, key, result);
19
- return result;
20
- };
21
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- var PERCENT = /^(\d+)(?:\.(\d{1,6}))?$/;
23
- function isPercent(value) {
24
- const match = PERCENT.exec(value);
25
- if (!match) return false;
26
- return BigInt(match[1]) * 1000000n + BigInt((match[2] ?? "").padEnd(6, "0")) <= 100000000n;
27
- }
28
- function canonicalPercent(value) {
29
- const [whole, fraction = ""] = String(value).split(".");
30
- const normalizedWhole = whole.replace(/^0+(?=\d)/, "") || "0";
31
- const normalizedFraction = fraction.replace(/0+$/, "");
32
- return normalizedFraction ? `${normalizedWhole}.${normalizedFraction}` : normalizedWhole;
33
- }
34
- var TaxComponent = class extends SmrtObject {
35
- tenantId = "";
36
- name = "";
37
- percent = "0.0";
38
- liabilityAccountId = "";
39
- recoverable = false;
40
- active = true;
41
- constructor(options = {}) {
42
- super(options);
43
- if (options.tenantId !== void 0) this.tenantId = options.tenantId ?? "";
44
- if (options.name !== void 0) this.name = options.name;
45
- if (options.percent !== void 0) this.percent = options.percent;
46
- if (options.liabilityAccountId !== void 0) this.liabilityAccountId = options.liabilityAccountId;
47
- if (options.recoverable !== void 0) this.recoverable = options.recoverable;
48
- if (options.active !== void 0) this.active = options.active;
49
- }
50
- async initialize() {
51
- await super.initialize();
52
- this.percent = canonicalPercent(String(this.percent));
53
- return this;
54
- }
55
- async save(options) {
56
- if (!this.name.trim()) throw new Error("Tax component requires a nonempty name");
57
- if (!isPercent(this.percent)) throw new MoneyValidationError("PERCENT_OUT_OF_RANGE", "Tax component percent must be between 0 and 100 with at most six decimal places.");
58
- this.percent = canonicalPercent(this.percent);
59
- return this.withTransaction(async () => {
60
- const { TaxComponentCollection } = await Promise.resolve().then(() => TaxComponentCollection_exports);
61
- const components = await TaxComponentCollection.create({ db: this.db });
62
- const persisted = this.id ? await components.get({ id: this.id }, { cache: false }) : null;
63
- if (persisted && canonicalPercent(persisted.percent) !== this.percent) {
64
- const callerRevision = options?.expectedUpdatedAt;
65
- const referenced = await this.isReferenced(persisted, callerRevision);
66
- this.updated_at = persisted.updated_at;
67
- if (callerRevision !== void 0 && persisted.updated_at) options = {
68
- ...options,
69
- expectedUpdatedAt: persisted.updated_at
70
- };
71
- if (referenced) throw new MoneyValidationError("PERCENT_OUT_OF_RANGE", "A referenced tax component rate is immutable; archive it and repoint its tax codes.");
72
- }
73
- if (this.liabilityAccountId) {
74
- const account = await (await AccountCollection.create({ db: this.db })).get({ id: this.liabilityAccountId }, { cache: false });
75
- if (!account || account.tenantId !== this.tenantId) throw new Error("Tax component liability account must belong to its tenant");
76
- }
77
- return await super.save(options);
78
- });
79
- }
80
- async isReferenced(persisted, expectedUpdatedAt) {
81
- if (!this.id) return false;
82
- if (!persisted.updated_at) throw new Error("Referenced tax component is missing its revision");
83
- await persisted.claimRevision(expectedUpdatedAt ?? persisted.updated_at);
84
- const { TaxCodeCollection } = await import("./TaxCodeCollection-BBqCugs5.js").then((n) => n.n);
85
- const { DocumentTaxCollection } = await import("./DocumentTaxCollection-BRebznXF.js").then((n) => n.n);
86
- if ((await (await TaxCodeCollection.create({ db: this.db })).list({ where: { tenantId: this.tenantId } })).some((code) => code.components.some((component) => component.taxComponentId === this.id))) return true;
87
- return (await (await DocumentTaxCollection.create({ db: this.db })).list({
88
- where: {
89
- tenantId: this.tenantId,
90
- taxComponentId: this.id
91
- },
92
- limit: 1
93
- })).length > 0;
94
- }
95
- };
96
- __publicField(TaxComponent, "__smrtPackage__", "@happyvertical/smrt-commerce");
97
- __decorateClass([tenantId()], TaxComponent.prototype, "tenantId", 2);
98
- __decorateClass([field({ description: "The name of this tax component, for example GST." })], TaxComponent.prototype, "name", 2);
99
- __decorateClass([field({
100
- type: "decimal",
101
- description: "The tax percentage, for example 7.125 for 7.125 percent."
102
- })], TaxComponent.prototype, "percent", 2);
103
- __decorateClass([crossPackageRef("@happyvertical/smrt-ledgers:Account", { description: "The liability account that receives this tax component." })], TaxComponent.prototype, "liabilityAccountId", 2);
104
- __decorateClass([field({ description: "Whether purchases using this component may recover the full input tax. Partial recovery is not supported." })], TaxComponent.prototype, "recoverable", 2);
105
- __decorateClass([field({ description: "Whether new tax codes and overrides may select it." })], TaxComponent.prototype, "active", 2);
106
- TaxComponent = __decorateClass([TenantScoped({ mode: "required" }), smrt({
107
- api: {
108
- include: [
109
- "list",
110
- "get",
111
- "create",
112
- "update"
113
- ],
114
- writable: [
115
- "name",
116
- "percent",
117
- "liabilityAccountId",
118
- "recoverable",
119
- "active"
120
- ]
121
- },
122
- mcp: { include: ["list", "get"] },
123
- cli: { skipApiCheck: true }
124
- })], TaxComponent);
125
- //#endregion
126
- //#region src/collections/TaxComponentCollection.ts
127
- var TaxComponentCollection_exports = /* @__PURE__ */ __exportAll({ TaxComponentCollection: () => TaxComponentCollection });
128
- var TaxComponentCollection = class extends SmrtCollection {
129
- static _itemClass = TaxComponent;
130
- };
131
- //#endregion
132
- export { TaxComponentCollection_exports as n, TaxComponent as r, TaxComponentCollection as t };
133
-
134
- //# sourceMappingURL=TaxComponentCollection-BHJjbQxq.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaxComponentCollection-BHJjbQxq.js","names":[],"sources":["../../src/models/TaxComponent.ts","../../src/collections/TaxComponentCollection.ts"],"sourcesContent":["import {\n crossPackageRef,\n field,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { AccountCollection } from '@happyvertical/smrt-ledgers';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport { MoneyValidationError } from '../money.js';\nimport type { TaxComponentOptions } from '../types/index.js';\n\nconst PERCENT = /^(\\d+)(?:\\.(\\d{1,6}))?$/;\n\nfunction isPercent(value: string): boolean {\n const match = PERCENT.exec(value);\n if (!match) return false;\n const scaled =\n BigInt(match[1]) * 1_000_000n + BigInt((match[2] ?? '').padEnd(6, '0'));\n return scaled <= 100_000_000n;\n}\n\nfunction canonicalPercent(value: string): string {\n const [whole, fraction = ''] = String(value).split('.');\n const normalizedWhole = whole.replace(/^0+(?=\\d)/, '') || '0';\n const normalizedFraction = fraction.replace(/0+$/, '');\n return normalizedFraction\n ? `${normalizedWhole}.${normalizedFraction}`\n : normalizedWhole;\n}\n\n/**\n * One reusable tax rate component. Codes may combine components, but the\n * component's percent is immutable after it has been saved: archive it and\n * repoint editable codes to a replacement rate instead of rewriting history.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n api: {\n include: ['list', 'get', 'create', 'update'],\n writable: [\n 'name',\n 'percent',\n 'liabilityAccountId',\n 'recoverable',\n 'active',\n ],\n },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class TaxComponent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-commerce\";\n @tenantId()\n tenantId = '';\n\n @field({ description: 'The name of this tax component, for example GST.' })\n name = '';\n\n /** Percent, not a fraction: 7.125 means 7.125%. Stored as DECIMAL. */\n @field({\n type: 'decimal',\n description: 'The tax percentage, for example 7.125 for 7.125 percent.',\n })\n percent = '0.0';\n\n @crossPackageRef('@happyvertical/smrt-ledgers:Account', {\n description: 'The liability account that receives this tax component.',\n })\n liabilityAccountId = '';\n\n @field({\n description:\n 'Whether purchases using this component may recover the full input tax. Partial recovery is not supported.',\n })\n recoverable = false;\n\n @field({ description: 'Whether new tax codes and overrides may select it.' })\n active = true;\n\n constructor(options: TaxComponentOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId ?? '';\n if (options.name !== undefined) this.name = options.name;\n if (options.percent !== undefined) this.percent = options.percent;\n if (options.liabilityAccountId !== undefined)\n this.liabilityAccountId = options.liabilityAccountId;\n if (options.recoverable !== undefined)\n this.recoverable = options.recoverable;\n if (options.active !== undefined) this.active = options.active;\n }\n\n override async initialize(): Promise<this> {\n await super.initialize();\n this.percent = canonicalPercent(String(this.percent));\n return this;\n }\n\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (!this.name.trim())\n throw new Error('Tax component requires a nonempty name');\n if (!isPercent(this.percent)) {\n throw new MoneyValidationError(\n 'PERCENT_OUT_OF_RANGE',\n 'Tax component percent must be between 0 and 100 with at most six decimal places.',\n );\n }\n this.percent = canonicalPercent(this.percent);\n return this.withTransaction(async () => {\n const { TaxComponentCollection } = await import(\n '../collections/TaxComponentCollection.js'\n );\n const components = await TaxComponentCollection.create({ db: this.db });\n const persisted = this.id\n ? await components.get({ id: this.id }, { cache: false })\n : null;\n if (persisted && canonicalPercent(persisted.percent) !== this.percent) {\n const callerRevision = options?.expectedUpdatedAt;\n const referenced = await this.isReferenced(persisted, callerRevision);\n // claimRevision advanced the row's version; the pending save must use\n // that version rather than its stale caller snapshot.\n this.updated_at = persisted.updated_at;\n if (callerRevision !== undefined && persisted.updated_at)\n options = { ...options, expectedUpdatedAt: persisted.updated_at };\n if (referenced) {\n throw new MoneyValidationError(\n 'PERCENT_OUT_OF_RANGE',\n 'A referenced tax component rate is immutable; archive it and repoint its tax codes.',\n );\n }\n }\n if (this.liabilityAccountId) {\n const accounts = await AccountCollection.create({ db: this.db });\n const account = await accounts.get(\n { id: this.liabilityAccountId },\n { cache: false },\n );\n if (!account || account.tenantId !== this.tenantId) {\n throw new Error(\n 'Tax component liability account must belong to its tenant',\n );\n }\n }\n return (await super.save(options)) as this;\n });\n }\n\n private async isReferenced(\n persisted: TaxComponent,\n expectedUpdatedAt?: Date | string,\n ): Promise<boolean> {\n if (!this.id) return false;\n if (!persisted.updated_at)\n throw new Error('Referenced tax component is missing its revision');\n // Claim before inspecting references. TaxCode.save() claims the same row\n // before attaching it, so a concurrent rate edit must reload and retry.\n await persisted.claimRevision(expectedUpdatedAt ?? persisted.updated_at);\n const { TaxCodeCollection } = await import(\n '../collections/TaxCodeCollection.js'\n );\n const { DocumentTaxCollection } = await import(\n '../collections/DocumentTaxCollection.js'\n );\n const codes = await TaxCodeCollection.create({ db: this.db });\n const usedByCode = (\n await codes.list({ where: { tenantId: this.tenantId } })\n ).some((code) =>\n code.components.some((component) => component.taxComponentId === this.id),\n );\n if (usedByCode) return true;\n const documentTaxes = await DocumentTaxCollection.create({ db: this.db });\n return (\n (\n await documentTaxes.list({\n where: { tenantId: this.tenantId, taxComponentId: this.id },\n limit: 1,\n })\n ).length > 0\n );\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { TaxComponent } from '../models/TaxComponent.js';\n\nexport class TaxComponentCollection extends SmrtCollection<TaxComponent> {\n static readonly _itemClass = TaxComponent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,UAAU;AAEhB,SAAS,UAAU,OAAwB;CACzC,MAAM,QAAQ,QAAQ,KAAK,KAAK;CAChC,IAAI,CAAC,OAAO,OAAO;CAGnB,OADE,OAAO,MAAM,EAAE,IAAI,WAAa,QAAQ,MAAM,MAAM,GAAA,CAAI,OAAO,GAAG,GAAG,CAAC,KACvD;AACnB;AAEA,SAAS,iBAAiB,OAAuB;CAC/C,MAAM,CAAC,OAAO,WAAW,MAAM,OAAO,KAAK,CAAA,CAAE,MAAM,GAAG;CACtD,MAAM,kBAAkB,MAAM,QAAQ,aAAa,EAAE,KAAK;CAC1D,MAAM,qBAAqB,SAAS,QAAQ,OAAO,EAAE;CACrD,OAAO,qBACH,GAAG,gBAAe,GAAI,uBACtB;AACN;AAsBO,IAAM,eAAN,cAA2B,WAAW;CAE3C,WAAW;CAGX,OAAO;CAOP,UAAU;CAKV,qBAAqB;CAMrB,cAAc;CAGd,SAAS;CAET,YAAY,UAA+B,CAAC,GAAG;EAC7C,MAAM,OAAO;EACb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ,YAAY;EACxE,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,YAAY,KAAA,GAAW,KAAK,UAAU,QAAQ;EAC1D,IAAI,QAAQ,uBAAuB,KAAA,GACjC,KAAK,qBAAqB,QAAQ;EACpC,IAAI,QAAQ,gBAAgB,KAAA,GAC1B,KAAK,cAAc,QAAQ;EAC7B,IAAI,QAAQ,WAAW,KAAA,GAAW,KAAK,SAAS,QAAQ;CAC1D;CAEA,MAAe,aAA4B;EAC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E,aA0BX,WAAA,UAAA,CAAA;AA1BW,eAAN,gBAAA,CAfN,aAAa,EAAE,MAAM,WAAW,CAAC,GACjC,KAAK;CACJ,KAAK;EACH,SAAS;GAAC;GAAQ;GAAO;GAAU;EAAQ;EAC3C,UAAU;GACR;GACA;GACA;GACA;GACA;EACF;CACF;CACA,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;AAC5B,CAAC,CAAA,GACY,YAAA;;;;AChDN,IAAM,yBAAN,cAAqC,eAA6B;CACvE,OAAgB,aAAa;AAC/B"}
@@ -1,121 +0,0 @@
1
- import { n as roundSignedRational } from "./money-rational-CcW7gzG5.js";
2
- import { MoneyValidationError } from "../money.js";
3
- //#region src/credit-allocation.ts
4
- var QUANTITY_SCALE = 1000000n;
5
- function quantityUnits(value, label) {
6
- if (!/^(?:0|[1-9]\d*)(?:\.\d{1,6})?$/.test(value)) throw new MoneyValidationError("INVALID_MONEY_INPUT", `${label} must be a nonnegative decimal with at most six places`);
7
- const [whole, fraction = ""] = value.split(".");
8
- return BigInt(whole) * QUANTITY_SCALE + BigInt(fraction.padEnd(6, "0"));
9
- }
10
- function safeSigned(value, label) {
11
- if (value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER)) throw new MoneyValidationError("UNSAFE_MONEY", `${label} is unsafe`);
12
- return Number(value);
13
- }
14
- function magnitude(value) {
15
- return value < 0n ? -value : value;
16
- }
17
- function calculateAvailableRefund(input) {
18
- for (const [label, value] of Object.entries(input)) if (!Number.isSafeInteger(value) || value < 0) throw new MoneyValidationError("UNSAFE_MONEY", `${label} must be a nonnegative safe integer`);
19
- const outstanding = Math.max(0, input.sourceTotalMinor - input.sourcePaidMinor);
20
- return Math.max(0, Math.max(0, input.issuedCreditMinor - outstanding) - input.settledRefundMinor);
21
- }
22
- function allocateFrozenCredit(sourceLines, issued, requests) {
23
- for (const source of sourceLines) {
24
- if (!source.id || !Number.isSafeInteger(source.netMinor) || !Number.isSafeInteger(source.discountMinor) || !Number.isSafeInteger(source.unitPrice)) throw new MoneyValidationError("UNSAFE_MONEY", "Frozen source money must use safe integer minor units");
25
- if (quantityUnits(source.quantity, "Source quantity") <= 0n) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Frozen source quantity must be positive");
26
- }
27
- const sources = new Map(sourceLines.map((line) => [line.id, line]));
28
- if (sources.size !== sourceLines.length || !requests.length) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Credit allocation requires distinct source lines and requests");
29
- const requestedIds = /* @__PURE__ */ new Set();
30
- const consumed = /* @__PURE__ */ new Map();
31
- for (const row of issued) {
32
- if (!row.creditedLineId || !Number.isInteger(row.netMinor) || !Number.isInteger(row.discountMinor)) throw new MoneyValidationError("UNSAFE_MONEY", "Issued credit money must use safe integer minor units");
33
- if (!Number.isSafeInteger(row.netMinor) || !Number.isSafeInteger(row.discountMinor)) throw new MoneyValidationError("UNSAFE_MONEY", "Issued credit money must use safe integer minor units");
34
- if (!sources.has(row.creditedLineId)) throw new MoneyValidationError("INVALID_MONEY_INPUT", `Issued credit references unknown line ${row.creditedLineId}`);
35
- const current = consumed.get(row.creditedLineId) ?? {
36
- quantity: 0n,
37
- net: 0n,
38
- discount: 0n
39
- };
40
- const issuedQuantity = quantityUnits(row.quantity, "Issued credit quantity");
41
- current.quantity += issuedQuantity;
42
- current.net += BigInt(row.netMinor);
43
- current.discount += BigInt(row.discountMinor);
44
- consumed.set(row.creditedLineId, current);
45
- }
46
- const allocations = [...requests].sort((left, right) => left.creditedLineId < right.creditedLineId ? -1 : 1).map((request) => {
47
- if (requestedIds.has(request.creditedLineId)) throw new MoneyValidationError("INVALID_MONEY_INPUT", "A credit may reference a source line only once");
48
- requestedIds.add(request.creditedLineId);
49
- const source = sources.get(request.creditedLineId);
50
- if (!source) throw new MoneyValidationError("INVALID_MONEY_INPUT", `Unknown credited line ${request.creditedLineId}`);
51
- const used = consumed.get(source.id) ?? {
52
- quantity: 0n,
53
- net: 0n,
54
- discount: 0n
55
- };
56
- const sourceQuantity = quantityUnits(source.quantity, "Source quantity");
57
- const remainingQuantity = sourceQuantity - used.quantity;
58
- const sourceNet = BigInt(source.netMinor);
59
- const sourceDiscount = BigInt(source.discountMinor);
60
- const sign = sourceNet < 0n ? -1n : 1n;
61
- if (used.net !== 0n && (used.net < 0n ? -1n : 1n) !== sign || used.discount !== 0n && sourceDiscount !== 0n && (used.discount < 0n ? -1n : 1n) !== (sourceDiscount < 0n ? -1n : 1n)) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Issued credit signs must match the frozen source line");
62
- const remainingNet = magnitude(sourceNet) - magnitude(used.net);
63
- const remainingDiscount = magnitude(sourceDiscount) - magnitude(used.discount);
64
- if (remainingQuantity < 0n || remainingNet < 0n || remainingDiscount < 0n) throw new MoneyValidationError("CREDIT_EXCEEDS_LINE", "Persisted credits already exceed the frozen source line");
65
- const snapshot = {
66
- sourceQuantity: source.quantity,
67
- sourceUnitPrice: source.unitPrice,
68
- sourceDiscountType: source.discountType,
69
- sourceDiscountRate: String(source.discountRate),
70
- sourceDiscountMinor: source.discountMinor
71
- };
72
- if ("quantity" in request) {
73
- const quantity = quantityUnits(request.quantity, "Credit quantity");
74
- if (quantity <= 0n || quantity > remainingQuantity) throw new MoneyValidationError("CREDIT_EXCEEDS_LINE", "Credit quantity exceeds the remaining frozen quantity");
75
- const exhaustsLine = quantity === remainingQuantity;
76
- const discountSign = sourceDiscount < 0n ? -1n : 1n;
77
- const incrementalDiscount = (source.discountType === "none" ? 0n : roundSignedRational(sourceDiscount * (used.quantity + quantity), sourceQuantity)) - used.discount;
78
- const boundedIncrementalDiscount = incrementalDiscount === 0n || (incrementalDiscount < 0n ? -1n : 1n) !== discountSign ? 0n : discountSign * (magnitude(incrementalDiscount) < remainingDiscount ? magnitude(incrementalDiscount) : remainingDiscount);
79
- const discount = source.discountType === "none" ? 0n : exhaustsLine ? discountSign * remainingDiscount : boundedIncrementalDiscount;
80
- return {
81
- creditedLineId: source.id,
82
- basis: {
83
- kind: "quantity",
84
- quantity: request.quantity,
85
- ...snapshot
86
- },
87
- netMinor: null,
88
- discountMinor: safeSigned(discount, "Credit discount"),
89
- remainingNetMinor: safeSigned(sign * remainingNet, "Remaining credit net amount"),
90
- exhaustsLine
91
- };
92
- }
93
- if (!Number.isSafeInteger(request.netMinor) || request.netMinor <= 0) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Credit net amount must be a positive safe integer");
94
- const amount = BigInt(request.netMinor);
95
- if (amount > remainingNet) throw new MoneyValidationError("CREDIT_EXCEEDS_LINE", "Credit net amount exceeds the remaining frozen net amount");
96
- return {
97
- creditedLineId: source.id,
98
- basis: {
99
- kind: "net_amount",
100
- netMinor: request.netMinor,
101
- ...snapshot
102
- },
103
- netMinor: safeSigned(sign * amount, "Credit net amount"),
104
- discountMinor: 0,
105
- remainingNetMinor: safeSigned(sign * remainingNet, "Remaining credit net amount"),
106
- exhaustsLine: amount === remainingNet
107
- };
108
- });
109
- const exhausted = new Set(allocations.filter((row) => row.exhaustsLine).map((row) => row.creditedLineId));
110
- return {
111
- allocations,
112
- exhaustsDocument: sourceLines.every((line) => {
113
- const used = consumed.get(line.id);
114
- return magnitude(BigInt(line.netMinor)) - magnitude(used?.net ?? 0n) === 0n || exhausted.has(line.id);
115
- })
116
- };
117
- }
118
- //#endregion
119
- export { calculateAvailableRefund as n, allocateFrozenCredit as t };
120
-
121
- //# sourceMappingURL=credit-allocation-yspz0Lab.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"credit-allocation-yspz0Lab.js","names":[],"sources":["../../src/credit-allocation.ts"],"sourcesContent":["/** Pure allocation of positive credit requests against frozen invoice lines. */\n\nimport { MoneyValidationError } from './money.js';\nimport { roundSignedRational } from './money-rational.js';\nimport type { InvoiceCreditCalculationBasis } from './types/index.js';\n\nconst QUANTITY_SCALE = 1_000_000n;\n\nfunction quantityUnits(value: string, label: string): bigint {\n if (!/^(?:0|[1-9]\\d*)(?:\\.\\d{1,6})?$/.test(value))\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `${label} must be a nonnegative decimal with at most six places`,\n );\n const [whole, fraction = ''] = value.split('.');\n return BigInt(whole) * QUANTITY_SCALE + BigInt(fraction.padEnd(6, '0'));\n}\n\nfunction safeSigned(value: bigint, label: string): number {\n if (\n value < BigInt(Number.MIN_SAFE_INTEGER) ||\n value > BigInt(Number.MAX_SAFE_INTEGER)\n )\n throw new MoneyValidationError('UNSAFE_MONEY', `${label} is unsafe`);\n return Number(value);\n}\n\nfunction magnitude(value: bigint): bigint {\n return value < 0n ? -value : value;\n}\n\nexport interface FrozenCreditSourceLine {\n id: string;\n quantity: string;\n netMinor: number;\n discountMinor: number;\n unitPrice: number;\n discountType: 'none' | 'percent' | 'amount';\n discountRate: string;\n}\n\nexport interface IssuedCreditConsumption {\n creditedLineId: string;\n quantity: string;\n netMinor: number;\n discountMinor: number;\n}\n\nexport type FrozenCreditRequest =\n | { creditedLineId: string; quantity: string }\n | { creditedLineId: string; netMinor: number };\n\nexport interface FrozenCreditAllocation {\n creditedLineId: string;\n basis: InvoiceCreditCalculationBasis;\n netMinor: number | null;\n discountMinor: number;\n /** Signed tax-exclusive source capacity remaining before this allocation. */\n remainingNetMinor: number;\n exhaustsLine: boolean;\n}\n\nexport interface FrozenCreditAllocationResult {\n allocations: FrozenCreditAllocation[];\n exhaustsDocument: boolean;\n}\n\nexport interface AvailableRefundInput {\n sourceTotalMinor: number;\n sourcePaidMinor: number;\n issuedCreditMinor: number;\n settledRefundMinor: number;\n}\n\n/** Exact unapplied credit available to refund across one source invoice. */\nexport function calculateAvailableRefund(input: AvailableRefundInput): number {\n for (const [label, value] of Object.entries(input)) {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new MoneyValidationError(\n 'UNSAFE_MONEY',\n `${label} must be a nonnegative safe integer`,\n );\n }\n const outstanding = Math.max(\n 0,\n input.sourceTotalMinor - input.sourcePaidMinor,\n );\n return Math.max(\n 0,\n Math.max(0, input.issuedCreditMinor - outstanding) -\n input.settledRefundMinor,\n );\n}\n\n/** Validate caps and normalize flat-discount/final-residual allocation. */\nexport function allocateFrozenCredit(\n sourceLines: readonly FrozenCreditSourceLine[],\n issued: readonly IssuedCreditConsumption[],\n requests: readonly FrozenCreditRequest[],\n): FrozenCreditAllocationResult {\n for (const source of sourceLines) {\n if (\n !source.id ||\n !Number.isSafeInteger(source.netMinor) ||\n !Number.isSafeInteger(source.discountMinor) ||\n !Number.isSafeInteger(source.unitPrice)\n )\n throw new MoneyValidationError(\n 'UNSAFE_MONEY',\n 'Frozen source money must use safe integer minor units',\n );\n if (quantityUnits(source.quantity, 'Source quantity') <= 0n)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Frozen source quantity must be positive',\n );\n }\n const sources = new Map(sourceLines.map((line) => [line.id, line]));\n if (sources.size !== sourceLines.length || !requests.length)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Credit allocation requires distinct source lines and requests',\n );\n const requestedIds = new Set<string>();\n const consumed = new Map<\n string,\n { quantity: bigint; net: bigint; discount: bigint }\n >();\n for (const row of issued) {\n if (\n !row.creditedLineId ||\n !Number.isInteger(row.netMinor) ||\n !Number.isInteger(row.discountMinor)\n )\n throw new MoneyValidationError(\n 'UNSAFE_MONEY',\n 'Issued credit money must use safe integer minor units',\n );\n if (\n !Number.isSafeInteger(row.netMinor) ||\n !Number.isSafeInteger(row.discountMinor)\n )\n throw new MoneyValidationError(\n 'UNSAFE_MONEY',\n 'Issued credit money must use safe integer minor units',\n );\n if (!sources.has(row.creditedLineId))\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `Issued credit references unknown line ${row.creditedLineId}`,\n );\n const current = consumed.get(row.creditedLineId) ?? {\n quantity: 0n,\n net: 0n,\n discount: 0n,\n };\n const issuedQuantity = quantityUnits(\n row.quantity,\n 'Issued credit quantity',\n );\n current.quantity += issuedQuantity;\n current.net += BigInt(row.netMinor);\n current.discount += BigInt(row.discountMinor);\n consumed.set(row.creditedLineId, current);\n }\n const allocations = [...requests]\n .sort((left, right) =>\n left.creditedLineId < right.creditedLineId ? -1 : 1,\n )\n .map((request): FrozenCreditAllocation => {\n if (requestedIds.has(request.creditedLineId))\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'A credit may reference a source line only once',\n );\n requestedIds.add(request.creditedLineId);\n const source = sources.get(request.creditedLineId);\n if (!source)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n `Unknown credited line ${request.creditedLineId}`,\n );\n const used = consumed.get(source.id) ?? {\n quantity: 0n,\n net: 0n,\n discount: 0n,\n };\n const sourceQuantity = quantityUnits(source.quantity, 'Source quantity');\n const remainingQuantity = sourceQuantity - used.quantity;\n const sourceNet = BigInt(source.netMinor);\n const sourceDiscount = BigInt(source.discountMinor);\n const sign = sourceNet < 0n ? -1n : 1n;\n if (\n (used.net !== 0n && (used.net < 0n ? -1n : 1n) !== sign) ||\n (used.discount !== 0n &&\n sourceDiscount !== 0n &&\n (used.discount < 0n ? -1n : 1n) !== (sourceDiscount < 0n ? -1n : 1n))\n )\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Issued credit signs must match the frozen source line',\n );\n const remainingNet = magnitude(sourceNet) - magnitude(used.net);\n const remainingDiscount =\n magnitude(sourceDiscount) - magnitude(used.discount);\n if (remainingQuantity < 0n || remainingNet < 0n || remainingDiscount < 0n)\n throw new MoneyValidationError(\n 'CREDIT_EXCEEDS_LINE',\n 'Persisted credits already exceed the frozen source line',\n );\n const snapshot = {\n sourceQuantity: source.quantity,\n sourceUnitPrice: source.unitPrice,\n sourceDiscountType: source.discountType,\n sourceDiscountRate: String(source.discountRate),\n sourceDiscountMinor: source.discountMinor,\n } as const;\n if ('quantity' in request) {\n const quantity = quantityUnits(request.quantity, 'Credit quantity');\n if (quantity <= 0n || quantity > remainingQuantity)\n throw new MoneyValidationError(\n 'CREDIT_EXCEEDS_LINE',\n 'Credit quantity exceeds the remaining frozen quantity',\n );\n const exhaustsLine = quantity === remainingQuantity;\n const discountSign = sourceDiscount < 0n ? -1n : 1n;\n const cumulativeDiscount =\n source.discountType === 'none'\n ? 0n\n : roundSignedRational(\n sourceDiscount * (used.quantity + quantity),\n sourceQuantity,\n );\n const incrementalDiscount = cumulativeDiscount - used.discount;\n const boundedIncrementalDiscount =\n incrementalDiscount === 0n ||\n (incrementalDiscount < 0n ? -1n : 1n) !== discountSign\n ? 0n\n : discountSign *\n (magnitude(incrementalDiscount) < remainingDiscount\n ? magnitude(incrementalDiscount)\n : remainingDiscount);\n const discount =\n source.discountType === 'none'\n ? 0n\n : exhaustsLine\n ? discountSign * remainingDiscount\n : boundedIncrementalDiscount;\n return {\n creditedLineId: source.id,\n basis: { kind: 'quantity', quantity: request.quantity, ...snapshot },\n netMinor: null,\n discountMinor: safeSigned(discount, 'Credit discount'),\n remainingNetMinor: safeSigned(\n sign * remainingNet,\n 'Remaining credit net amount',\n ),\n exhaustsLine,\n };\n }\n if (!Number.isSafeInteger(request.netMinor) || request.netMinor <= 0)\n throw new MoneyValidationError(\n 'INVALID_MONEY_INPUT',\n 'Credit net amount must be a positive safe integer',\n );\n const amount = BigInt(request.netMinor);\n if (amount > remainingNet)\n throw new MoneyValidationError(\n 'CREDIT_EXCEEDS_LINE',\n 'Credit net amount exceeds the remaining frozen net amount',\n );\n return {\n creditedLineId: source.id,\n basis: { kind: 'net_amount', netMinor: request.netMinor, ...snapshot },\n netMinor: safeSigned(sign * amount, 'Credit net amount'),\n discountMinor: 0,\n remainingNetMinor: safeSigned(\n sign * remainingNet,\n 'Remaining credit net amount',\n ),\n exhaustsLine: amount === remainingNet,\n };\n });\n const exhausted = new Set(\n allocations\n .filter((row) => row.exhaustsLine)\n .map((row) => row.creditedLineId),\n );\n return {\n allocations,\n exhaustsDocument: sourceLines.every((line) => {\n const used = consumed.get(line.id);\n return (\n magnitude(BigInt(line.netMinor)) - magnitude(used?.net ?? 0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