@happyvertical/smrt-commerce 0.60.13 → 0.60.15

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 (42) hide show
  1. package/AGENTS.md +10 -0
  2. package/agents/invoice-source-binding.md +29 -0
  3. package/dist/chunks/{ContractLineItemCollection-CwGdWgQE.js → ContractLineItemCollection-72DuK6tr.js} +4 -4
  4. package/dist/chunks/{ContractLineItemCollection-CwGdWgQE.js.map → ContractLineItemCollection-72DuK6tr.js.map} +1 -1
  5. package/dist/chunks/{DocumentTaxCollection-BfuNqFNm.js → DocumentTaxCollection-DNo_fziv.js} +165 -49
  6. package/dist/chunks/DocumentTaxCollection-DNo_fziv.js.map +1 -0
  7. package/dist/chunks/{InvoiceCollection-Cxz6Z1uv.js → InvoiceCollection-oUdTA1s-.js} +9 -9
  8. package/dist/chunks/{InvoiceCollection-Cxz6Z1uv.js.map → InvoiceCollection-oUdTA1s-.js.map} +1 -1
  9. package/dist/chunks/{TaxCodeCollection-CKGI5AzL.js → TaxCodeCollection-CrCPUyaW.js} +2 -2
  10. package/dist/chunks/{TaxCodeCollection-CKGI5AzL.js.map → TaxCodeCollection-CrCPUyaW.js.map} +1 -1
  11. package/dist/chunks/{TaxComponentCollection-r9ipXMGD.js → TaxComponentCollection-BGXwXDtt.js} +3 -3
  12. package/dist/chunks/{TaxComponentCollection-r9ipXMGD.js.map → TaxComponentCollection-BGXwXDtt.js.map} +1 -1
  13. package/dist/chunks/{allocation-integrity-Qge856lI.js → allocation-integrity-CgJqS_6u.js} +6 -6
  14. package/dist/chunks/{allocation-integrity-Qge856lI.js.map → allocation-integrity-CgJqS_6u.js.map} +1 -1
  15. package/dist/chunks/{contract-money-ByflBBOV.js → contract-money-B05oKoxQ.js} +6 -6
  16. package/dist/chunks/{contract-money-ByflBBOV.js.map → contract-money-B05oKoxQ.js.map} +1 -1
  17. package/dist/chunks/{invoice-posting-DeixlpG-.js → invoice-posting-ECbJBE0g.js} +3 -3
  18. package/dist/chunks/{invoice-posting-DeixlpG-.js.map → invoice-posting-ECbJBE0g.js.map} +1 -1
  19. package/dist/chunks/{retention-accounting-DT3N01yc.js → retention-accounting-Dpzjo1Ia.js} +8 -8
  20. package/dist/chunks/{retention-accounting-DT3N01yc.js.map → retention-accounting-Dpzjo1Ia.js.map} +1 -1
  21. package/dist/chunks/{tenant-money-barrier-BtMoMg85.js → tenant-money-barrier-M-2l6pxS.js} +3 -3
  22. package/dist/chunks/{tenant-money-barrier-BtMoMg85.js.map → tenant-money-barrier-M-2l6pxS.js.map} +1 -1
  23. package/dist/chunks/types-Bbm0Xflc.js.map +1 -1
  24. package/dist/document-money.d.ts.map +1 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +15 -14
  28. package/dist/index.js.map +1 -1
  29. package/dist/invoice-source-binding.d.ts +32 -0
  30. package/dist/invoice-source-binding.d.ts.map +1 -0
  31. package/dist/invoices.js +1 -1
  32. package/dist/manifest.json +27 -5
  33. package/dist/models/InvoiceLineItem.d.ts +2 -0
  34. package/dist/models/InvoiceLineItem.d.ts.map +1 -1
  35. package/dist/recipes.d.ts +3 -0
  36. package/dist/recipes.d.ts.map +1 -1
  37. package/dist/smrt-knowledge.json +22 -6
  38. package/dist/smrt-knowledge.okf.md +15 -11
  39. package/dist/types/index.d.ts +2 -0
  40. package/dist/types/index.d.ts.map +1 -1
  41. package/package.json +13 -13
  42. package/dist/chunks/DocumentTaxCollection-BfuNqFNm.js.map +0 -1
@@ -4,12 +4,12 @@ import { MoneyValidationError, assertIntegerMinorUnits, calculateMoneyDocument,
4
4
  import { n as withHistoricalCommerceWrite, t as assertHistoricalCommerceWrite } from "./historical-commerce-internal-C9ButfuH.js";
5
5
  import { t as allocateFrozenCredit } from "./credit-allocation-yspz0Lab.js";
6
6
  import { _ as withDocumentMoneyTransaction, a as assertCommerceMoneySchemaCurrent, f as DOCUMENT_MONEY_READ_REBIND, g as withDocumentMoneyObjectTransaction, h as lockDocumentMoneyParents, p as DOCUMENT_MONEY_WRITE } from "./detect-DAE-_NAk.js";
7
- import { s as parseInvoiceRetention, t as InvoiceCollection } from "./InvoiceCollection-Cxz6Z1uv.js";
8
- import { n as withTenantMoneyCollectionRead, r as withTenantMoneyRuntime, t as lockTenantMoneyRuntime } from "./tenant-money-barrier-BtMoMg85.js";
9
- import { t as TaxCodeCollection } from "./TaxCodeCollection-CKGI5AzL.js";
10
- import { t as ContractLineItemCollection } from "./ContractLineItemCollection-CwGdWgQE.js";
11
- import { t as TaxComponentCollection } from "./TaxComponentCollection-r9ipXMGD.js";
12
- import { SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
7
+ import { s as parseInvoiceRetention, t as InvoiceCollection } from "./InvoiceCollection-oUdTA1s-.js";
8
+ import { n as withTenantMoneyCollectionRead, r as withTenantMoneyRuntime, t as lockTenantMoneyRuntime } from "./tenant-money-barrier-M-2l6pxS.js";
9
+ import { t as TaxCodeCollection } from "./TaxCodeCollection-CrCPUyaW.js";
10
+ import { t as ContractLineItemCollection } from "./ContractLineItemCollection-72DuK6tr.js";
11
+ import { t as TaxComponentCollection } from "./TaxComponentCollection-BGXwXDtt.js";
12
+ import { ObjectRegistry, SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
13
13
  import { TenantScoped, getTenantId, queryGlobal, queryWithGlobals, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
14
14
  import { ISO_4217_MINOR_UNITS } from "@happyvertical/smrt-ui/currency";
15
15
  import { createHash } from "node:crypto";
@@ -502,6 +502,7 @@ var InvoiceLineItem = class extends SmrtObject {
502
502
  * ID of the source (e.g., campaign ID, contract ID)
503
503
  */
504
504
  sourceId = "";
505
+ sourceReservationId = null;
505
506
  /**
506
507
  * Service period start (for time-based billing)
507
508
  */
@@ -542,6 +543,7 @@ var InvoiceLineItem = class extends SmrtObject {
542
543
  if (options.amount !== void 0) this.amount = options.amount;
543
544
  if (options.sourceType !== void 0) this.sourceType = options.sourceType;
544
545
  if (options.sourceId !== void 0) this.sourceId = options.sourceId;
546
+ if (options.sourceReservationId !== void 0) this.sourceReservationId = options.sourceReservationId;
545
547
  if (options.periodStart !== void 0) this.periodStart = options.periodStart;
546
548
  if (options.periodEnd !== void 0) this.periodEnd = options.periodEnd;
547
549
  if (options.revenueAccountId !== void 0) this.revenueAccountId = options.revenueAccountId;
@@ -610,6 +612,11 @@ __decorateClass$4([field({
610
612
  description: "The line amount: net of discount, and including tax only when the document's prices include tax.",
611
613
  ui: { format: "money" }
612
614
  })], InvoiceLineItem.prototype, "amount", 2);
615
+ __decorateClass$4([field({
616
+ type: "text",
617
+ nullable: true,
618
+ readonly: true
619
+ })], InvoiceLineItem.prototype, "sourceReservationId", 2);
613
620
  __decorateClass$4([crossPackageRef("@happyvertical/smrt-ledgers:Account", { nullable: true })], InvoiceLineItem.prototype, "revenueAccountId", 2);
614
621
  InvoiceLineItem = __decorateClass$4([TenantScoped({ mode: "optional" }), smrt({
615
622
  api: {
@@ -1226,7 +1233,7 @@ var Contract = class extends SmrtObject {
1226
1233
  * Calculate and update totals from line items
1227
1234
  */
1228
1235
  async recalculateTotals() {
1229
- const { recalculateContractTotals } = await import("./contract-money-ByflBBOV.js").then((n) => n.n);
1236
+ const { recalculateContractTotals } = await import("./contract-money-B05oKoxQ.js").then((n) => n.n);
1230
1237
  await recalculateContractTotals(this);
1231
1238
  }
1232
1239
  /**
@@ -1257,12 +1264,12 @@ var Contract = class extends SmrtObject {
1257
1264
  * write surface (#2401).
1258
1265
  */
1259
1266
  async save(options) {
1260
- const { saveContract } = await import("./contract-money-ByflBBOV.js").then((n) => n.n);
1267
+ const { saveContract } = await import("./contract-money-B05oKoxQ.js").then((n) => n.n);
1261
1268
  return await saveContract(this, options);
1262
1269
  }
1263
1270
  /** Received purchase monetary history cannot be deleted. */
1264
1271
  async delete(options = {}) {
1265
- const { deleteContract } = await import("./contract-money-ByflBBOV.js").then((n) => n.n);
1272
+ const { deleteContract } = await import("./contract-money-B05oKoxQ.js").then((n) => n.n);
1266
1273
  await deleteContract(this, options);
1267
1274
  }
1268
1275
  /** @internal Contract aggregate persistence only. */
@@ -1876,15 +1883,15 @@ var ContractCollection = class extends SmrtCollection {
1876
1883
  };
1877
1884
  //#endregion
1878
1885
  //#region src/contract-billing-schedule.ts
1879
- function invalid$3(message) {
1886
+ function invalid$4(message) {
1880
1887
  throw new MoneyValidationError("INVALID_MONEY_INPUT", message);
1881
1888
  }
1882
1889
  function text$1(value, label) {
1883
- if (typeof value !== "string" || !value || value.trim() !== value) invalid$3(`${label} must be nonempty trimmed text`);
1890
+ if (typeof value !== "string" || !value || value.trim() !== value) invalid$4(`${label} must be nonempty trimmed text`);
1884
1891
  return value;
1885
1892
  }
1886
1893
  function integer$1(value, label, signed = false) {
1887
- if (typeof value !== "number" || !Number.isSafeInteger(value) || !signed && value < 0) invalid$3(`${label} must be a ${signed ? "" : "nonnegative "}safe integer`);
1894
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || !signed && value < 0) invalid$4(`${label} must be a ${signed ? "" : "nonnegative "}safe integer`);
1888
1895
  return value;
1889
1896
  }
1890
1897
  function safe(value) {
@@ -1894,15 +1901,15 @@ function context(input) {
1894
1901
  text$1(input.tenantId, "Tenant");
1895
1902
  text$1(input.contractId, "Contract");
1896
1903
  text$1(input.requestId, "Request");
1897
- if (getTenantId() !== input.tenantId) invalid$3("Schedule command requires its active tenant context");
1904
+ if (getTenantId() !== input.tenantId) invalid$4("Schedule command requires its active tenant context");
1898
1905
  }
1899
1906
  function milestones(value) {
1900
- if (!Array.isArray(value) || value.length === 0) invalid$3("A schedule requires milestones");
1907
+ if (!Array.isArray(value) || value.length === 0) invalid$4("A schedule requires milestones");
1901
1908
  const keys = /* @__PURE__ */ new Set();
1902
1909
  return value.map((entry) => {
1903
- if (!entry || typeof entry !== "object") invalid$3("Invalid milestone");
1910
+ if (!entry || typeof entry !== "object") invalid$4("Invalid milestone");
1904
1911
  const key = text$1(entry.key, "Milestone key");
1905
- if (keys.has(key)) invalid$3("Milestone keys must be unique");
1912
+ if (keys.has(key)) invalid$4("Milestone keys must be unique");
1906
1913
  keys.add(key);
1907
1914
  return {
1908
1915
  key,
@@ -1912,11 +1919,11 @@ function milestones(value) {
1912
1919
  });
1913
1920
  }
1914
1921
  function money(value) {
1915
- if (!value || typeof value !== "object") invalid$3("Approved invoice money is required");
1922
+ if (!value || typeof value !== "object") invalid$4("Approved invoice money is required");
1916
1923
  const netMinor = integer$1(value.netMinor, "Approved net");
1917
1924
  const taxMinor = integer$1(value.taxMinor, "Approved tax");
1918
1925
  const grossMinor = integer$1(value.grossMinor, "Approved gross");
1919
- if (BigInt(netMinor) + BigInt(taxMinor) !== BigInt(grossMinor)) invalid$3("Approved invoice money must reconcile");
1926
+ if (BigInt(netMinor) + BigInt(taxMinor) !== BigInt(grossMinor)) invalid$4("Approved invoice money must reconcile");
1920
1927
  return {
1921
1928
  netMinor,
1922
1929
  taxMinor,
@@ -1925,10 +1932,10 @@ function money(value) {
1925
1932
  }
1926
1933
  function allocateContractMilestones(totalMinor, weights) {
1927
1934
  integer$1(totalMinor, "Total");
1928
- if (!Array.isArray(weights) || !weights.length) invalid$3("Milestone weights are required");
1935
+ if (!Array.isArray(weights) || !weights.length) invalid$4("Milestone weights are required");
1929
1936
  const values = weights.map((value) => {
1930
1937
  integer$1(value, "Weight");
1931
- if (!value) invalid$3("Weights must be positive");
1938
+ if (!value) invalid$4("Weights must be positive");
1932
1939
  return BigInt(value);
1933
1940
  });
1934
1941
  const sum = values.reduce((a, b) => a + b, 0n);
@@ -1945,9 +1952,9 @@ function getContractBillingSchedule(contract) {
1945
1952
  try {
1946
1953
  parsed = JSON.parse(contract.billingScheduleJson);
1947
1954
  } catch {
1948
- invalid$3("Stored billing schedule is invalid");
1955
+ invalid$4("Stored billing schedule is invalid");
1949
1956
  }
1950
- if (parsed.version !== 1 || parsed.capacityPolicy !== "issued-consumed" || !Array.isArray(parsed.revisions) || !parsed.revisions.length || !Array.isArray(parsed.claims)) invalid$3("Stored billing schedule is invalid");
1957
+ if (parsed.version !== 1 || parsed.capacityPolicy !== "issued-consumed" || !Array.isArray(parsed.revisions) || !parsed.revisions.length || !Array.isArray(parsed.claims)) invalid$4("Stored billing schedule is invalid");
1951
1958
  return parsed;
1952
1959
  }
1953
1960
  async function loadContract(db, tenantId, contractId) {
@@ -1958,7 +1965,7 @@ async function loadContract(db, tenantId, contractId) {
1958
1965
  collection
1959
1966
  }]);
1960
1967
  const contract = await collection.get({ id: contractId }, { cache: false });
1961
- if (!(contract instanceof Order || contract instanceof Agreement) || contract.tenantId !== tenantId || !contract.customerId || contract.status !== ContractStatus.ACCEPTED || !contract.moneySnapshotId) invalid$3("Schedule requires an accepted customer contract in the active tenant");
1968
+ if (!(contract instanceof Order || contract instanceof Agreement) || contract.tenantId !== tenantId || !contract.customerId || contract.status !== ContractStatus.ACCEPTED || !contract.moneySnapshotId) invalid$4("Schedule requires an accepted customer contract in the active tenant");
1962
1969
  return contract;
1963
1970
  }
1964
1971
  async function approveContractBillingSchedule(input) {
@@ -1973,32 +1980,32 @@ async function approveContractBillingSchedule(input) {
1973
1980
  amendmentMinor: integer$1(input.amendmentMinor, "Amendment", true),
1974
1981
  milestones: milestones(input.milestones)
1975
1982
  };
1976
- if (proposal.basis !== "net" && proposal.basis !== "gross") invalid$3("Schedule basis must explicitly be net or gross");
1983
+ if (proposal.basis !== "net" && proposal.basis !== "gross") invalid$4("Schedule basis must explicitly be net or gross");
1977
1984
  return withTenantMoneyRuntime(input.db, input.tenantId, async ({ db }) => {
1978
1985
  const contract = await loadContract(db, input.tenantId, input.contractId);
1979
1986
  const stored = getContractBillingSchedule(contract);
1980
1987
  const replay = stored?.revisions.find((entry) => entry.requestId === input.requestId);
1981
1988
  if (replay) {
1982
1989
  const { revision: revision2, approvedTotalMinor: _total, ...old } = replay;
1983
- if (revision2 !== expectedRevision + 1 || JSON.stringify(old) !== JSON.stringify(proposal)) invalid$3("Schedule request changed");
1990
+ if (revision2 !== expectedRevision + 1 || JSON.stringify(old) !== JSON.stringify(proposal)) invalid$4("Schedule request changed");
1984
1991
  return replay;
1985
1992
  }
1986
- if (stored?.claims.some((entry) => entry.requestId === input.requestId)) invalid$3("Request identity already used");
1993
+ if (stored?.claims.some((entry) => entry.requestId === input.requestId)) invalid$4("Request identity already used");
1987
1994
  const previous = stored?.revisions.at(-1);
1988
- if ((previous?.revision ?? 0) !== expectedRevision) invalid$3("Schedule revision changed");
1989
- if (contract.currency !== proposal.currency || previous && (previous.currency !== proposal.currency || previous.basis !== proposal.basis)) invalid$3("Schedule currency and basis must match original approval");
1995
+ if ((previous?.revision ?? 0) !== expectedRevision) invalid$4("Schedule revision changed");
1996
+ if (contract.currency !== proposal.currency || previous && (previous.currency !== proposal.currency || previous.basis !== proposal.basis)) invalid$4("Schedule currency and basis must match original approval");
1990
1997
  const originalAmountMinor = stored?.originalAmountMinor ?? (proposal.basis === "net" ? contract.subtotal : contract.totalAmount);
1991
1998
  integer$1(originalAmountMinor, "Original contract amount");
1992
1999
  if (!stored) {
1993
- if (proposal.amendmentMinor !== 0) invalid$3("Initial schedule cannot amend original contract value");
1994
- if ((await (await InvoiceCollection.create({ db })).findByContract(input.contractId)).some((invoice) => invoice.kind === "invoice" && !!invoice.moneySnapshotId)) invalid$3("Existing issued contract invoices prevent initial schedule approval");
2000
+ if (proposal.amendmentMinor !== 0) invalid$4("Initial schedule cannot amend original contract value");
2001
+ if ((await (await InvoiceCollection.create({ db })).findByContract(input.contractId)).some((invoice) => invoice.kind === "invoice" && !!invoice.moneySnapshotId)) invalid$4("Existing issued contract invoices prevent initial schedule approval");
1995
2002
  }
1996
2003
  const approvedTotalMinor = safe(BigInt(previous?.approvedTotalMinor ?? originalAmountMinor) + BigInt(proposal.amendmentMinor));
1997
- if (proposal.milestones.reduce((sum, entry) => sum + BigInt(entry.amountMinor), 0n) !== BigInt(approvedTotalMinor)) invalid$3("Milestone total must equal original contract plus approved amendments");
2004
+ if (proposal.milestones.reduce((sum, entry) => sum + BigInt(entry.amountMinor), 0n) !== BigInt(approvedTotalMinor)) invalid$4("Milestone total must equal original contract plus approved amendments");
1998
2005
  for (const claim of stored?.claims ?? []) {
1999
2006
  const prior = stored?.revisions.find((entry) => entry.revision === claim.revision)?.milestones.find((entry) => entry.key === claim.milestoneKey);
2000
2007
  const next = proposal.milestones.find((entry) => entry.key === claim.milestoneKey);
2001
- if (!prior || !next || JSON.stringify(prior) !== JSON.stringify(next)) invalid$3("An issued milestone cannot be removed or changed");
2008
+ if (!prior || !next || JSON.stringify(prior) !== JSON.stringify(next)) invalid$4("An issued milestone cannot be removed or changed");
2002
2009
  }
2003
2010
  const revision = {
2004
2011
  revision: expectedRevision + 1,
@@ -2023,19 +2030,19 @@ async function assertContractScheduleInvoiceFreeze(db, invoice) {
2023
2030
  if (invoice.kind !== "invoice" || !invoice.contractId) return;
2024
2031
  const contract = await (await ContractCollection.create({ db })).get({ id: invoice.contractId }, { cache: false });
2025
2032
  if (!contract) return;
2026
- if (contract.tenantId !== invoice.tenantId) invalid$3("Invoice contract must belong to its active tenant");
2033
+ if (contract.tenantId !== invoice.tenantId) invalid$4("Invoice contract must belong to its active tenant");
2027
2034
  if (!getContractBillingSchedule(contract)) return;
2028
2035
  if (invoice.status === InvoiceStatus.CANCELLED && !invoice.moneySnapshotId && !invoice.arJournalId) return;
2029
- if (!(contract instanceof Order || contract instanceof Agreement)) invalid$3("Scheduled contract must be a customer contract");
2036
+ if (!(contract instanceof Order || contract instanceof Agreement)) invalid$4("Scheduled contract must be a customer contract");
2030
2037
  const permission = invoice.id ? issuePermissions.get(db)?.get(invoice.id) : void 0;
2031
- if (!permission || permission.contractId !== invoice.contractId) invalid$3("Scheduled contract invoices must use issueContractMilestoneInvoice");
2032
- if (invoice.customerId !== contract.customerId || invoice.currency !== contract.currency) invalid$3("Milestone invoice must match contract customer and currency");
2038
+ if (!permission || permission.contractId !== invoice.contractId) invalid$4("Scheduled contract invoices must use issueContractMilestoneInvoice");
2039
+ if (invoice.customerId !== contract.customerId || invoice.currency !== contract.currency) invalid$4("Milestone invoice must match contract customer and currency");
2033
2040
  const actual = {
2034
2041
  netMinor: invoice.subtotal,
2035
2042
  taxMinor: invoice.taxAmount,
2036
2043
  grossMinor: invoice.totalAmount
2037
2044
  };
2038
- if (JSON.stringify(actual) !== JSON.stringify(permission.approvedMoney) || (permission.basis === "net" ? invoice.subtotal : invoice.totalAmount) !== permission.amountMinor) invalid$3("Milestone invoice money differs from approved amounts");
2045
+ if (JSON.stringify(actual) !== JSON.stringify(permission.approvedMoney) || (permission.basis === "net" ? invoice.subtotal : invoice.totalAmount) !== permission.amountMinor) invalid$4("Milestone invoice money differs from approved amounts");
2039
2046
  }
2040
2047
  async function issueContractMilestoneInvoice(input) {
2041
2048
  context(input);
@@ -2050,19 +2057,19 @@ async function issueContractMilestoneInvoice(input) {
2050
2057
  return withTenantMoneyRuntime(input.db, input.tenantId, async ({ db }) => {
2051
2058
  const contract = await loadContract(db, input.tenantId, input.contractId);
2052
2059
  const state = getContractBillingSchedule(contract);
2053
- if (!state) invalid$3("Contract has no approved billing schedule");
2060
+ if (!state) invalid$4("Contract has no approved billing schedule");
2054
2061
  const replay = state.claims.find((entry) => entry.requestId === request.requestId);
2055
2062
  if (replay) {
2056
2063
  const { moneySnapshotId: _snapshot, ...prior } = replay;
2057
- if (JSON.stringify(prior) !== JSON.stringify(request)) invalid$3("Milestone issue request changed");
2064
+ if (JSON.stringify(prior) !== JSON.stringify(request)) invalid$4("Milestone issue request changed");
2058
2065
  return replay;
2059
2066
  }
2060
- if (state.revisions.some((entry) => entry.requestId === request.requestId)) invalid$3("Request identity already used");
2067
+ if (state.revisions.some((entry) => entry.requestId === request.requestId)) invalid$4("Request identity already used");
2061
2068
  const revision = state.revisions.at(-1);
2062
- if (!revision || revision.revision !== request.revision) invalid$3("Schedule revision changed");
2069
+ if (!revision || revision.revision !== request.revision) invalid$4("Schedule revision changed");
2063
2070
  const milestone = revision.milestones.find((entry) => entry.key === request.milestoneKey);
2064
- if (!milestone) invalid$3("Milestone does not exist in approved revision");
2065
- if (state.claims.some((entry) => entry.milestoneKey === request.milestoneKey || entry.invoiceId === request.invoiceId)) invalid$3("Milestone or invoice already consumed");
2071
+ if (!milestone) invalid$4("Milestone does not exist in approved revision");
2072
+ if (state.claims.some((entry) => entry.milestoneKey === request.milestoneKey || entry.invoiceId === request.invoiceId)) invalid$4("Milestone or invoice already consumed");
2066
2073
  const invoices = await InvoiceCollection.create({ db });
2067
2074
  await lockDocumentMoneyParents([{
2068
2075
  id: request.invoiceId,
@@ -2070,7 +2077,7 @@ async function issueContractMilestoneInvoice(input) {
2070
2077
  collection: invoices
2071
2078
  }]);
2072
2079
  const invoice = await invoices.get({ id: request.invoiceId }, { cache: false });
2073
- if (!invoice || invoice.tenantId !== input.tenantId || invoice.kind !== "invoice" || invoice.status !== InvoiceStatus.DRAFT || invoice.moneySnapshotId || invoice.contractId !== input.contractId || invoice.customerId !== contract.customerId || invoice.currency !== revision.currency) invalid$3("Milestone requires a matching unissued draft in the active tenant");
2080
+ if (!invoice || invoice.tenantId !== input.tenantId || invoice.kind !== "invoice" || invoice.status !== InvoiceStatus.DRAFT || invoice.moneySnapshotId || invoice.contractId !== input.contractId || invoice.customerId !== contract.customerId || invoice.currency !== revision.currency) invalid$4("Milestone requires a matching unissued draft in the active tenant");
2074
2081
  const permissions = issuePermissions.get(db) ?? /* @__PURE__ */ new Map();
2075
2082
  permissions.set(request.invoiceId, {
2076
2083
  contractId: input.contractId,
@@ -2086,7 +2093,7 @@ async function issueContractMilestoneInvoice(input) {
2086
2093
  permissions.delete(request.invoiceId);
2087
2094
  if (!permissions.size) issuePermissions.delete(db);
2088
2095
  }
2089
- if (!invoice.moneySnapshotId) invalid$3("Milestone invoice was not frozen");
2096
+ if (!invoice.moneySnapshotId) invalid$4("Milestone invoice was not frozen");
2090
2097
  const claim = {
2091
2098
  ...request,
2092
2099
  moneySnapshotId: invoice.moneySnapshotId
@@ -2098,6 +2105,105 @@ async function issueContractMilestoneInvoice(input) {
2098
2105
  });
2099
2106
  }
2100
2107
  //#endregion
2108
+ //#region src/invoice-source-binding.ts
2109
+ var handlers = /* @__PURE__ */ new Map();
2110
+ var writes = /* @__PURE__ */ new WeakMap();
2111
+ function invalid$3(message) {
2112
+ throw new MoneyValidationError("FROZEN_DOCUMENT", message);
2113
+ }
2114
+ function registerInvoiceSourceBinding(sourceType, handler) {
2115
+ if (!/^billable:@[a-z0-9-]+\/[a-z0-9-]+:[A-Za-z][A-Za-z0-9]*$/.test(sourceType)) invalid$3("Billable source type must be package qualified");
2116
+ if (handlers.has(sourceType) && handlers.get(sourceType) !== handler) invalid$3("Billable source handler already registered");
2117
+ handlers.set(sourceType, handler);
2118
+ }
2119
+ async function handlerFor(type) {
2120
+ if (!handlers.has(type) && type.startsWith("billable:")) await ObjectRegistry.tryLoadFromExternalPackage(type.slice(9));
2121
+ const handler = handlers.get(type);
2122
+ if (!handler) invalid$3("Protected invoice source handler is unavailable");
2123
+ return handler;
2124
+ }
2125
+ async function assertInvoiceLineSource(executor, invoice, line, persisted, issuing = false) {
2126
+ const old = persisted?.sourceReservationId ?? null;
2127
+ const next = line.sourceReservationId ?? null;
2128
+ const authorized = writes.has(line) && writes.get(line) === next;
2129
+ if (old !== next && !authorized) invalid$3("Invoice source reservation is command-owned");
2130
+ if (old && (line.sourceType !== persisted?.sourceType || line.sourceId !== persisted?.sourceId)) invalid$3("Bound invoice source identity cannot change");
2131
+ if (old && line.sourceType !== persisted?.sourceType) invalid$3("Bound source namespace cannot change");
2132
+ if (line.sourceType.startsWith("billable:") || old || next) {
2133
+ const handler = await handlerFor(line.sourceType);
2134
+ if (issuing && !next) invalid$3("Protected invoice source must be reserved before issue");
2135
+ if (next) await handler({
2136
+ executor,
2137
+ invoice,
2138
+ line,
2139
+ reservationId: next,
2140
+ phase: authorized ? "bind" : "validate"
2141
+ });
2142
+ }
2143
+ }
2144
+ function assertInvoiceSourceDelete(lines) {
2145
+ if (lines.some((line) => line.sourceReservationId)) invalid$3("Release invoice source reservations before deletion");
2146
+ }
2147
+ async function bindInvoiceLineSource(input) {
2148
+ if (!input.tenantId || getTenantId() !== input.tenantId || !input.reservationId) invalid$3("Active tenant and reservation required");
2149
+ const line = await (await InvoiceLineItemCollection.create({ db: input.db })).get({
2150
+ id: input.lineId,
2151
+ tenantId: input.tenantId
2152
+ }, { cache: false });
2153
+ if (!line || line.tenantId !== input.tenantId) invalid$3("Owned invoice line required");
2154
+ await line.withTransaction(async (bound) => {
2155
+ const invoice = await (await InvoiceCollection.create({ db: bound.db })).get({
2156
+ id: bound.invoiceId,
2157
+ tenantId: input.tenantId
2158
+ }, { cache: false });
2159
+ if (!invoice || invoice.status !== "draft") invalid$3("Unissued owned invoice required");
2160
+ if (bound.sourceReservationId && bound.sourceReservationId !== input.reservationId) invalid$3("Invoice line already bound");
2161
+ await (await handlerFor(bound.sourceType))({
2162
+ executor: bound.db,
2163
+ invoice,
2164
+ line: bound,
2165
+ reservationId: input.reservationId,
2166
+ phase: "bind"
2167
+ });
2168
+ bound.sourceReservationId = input.reservationId;
2169
+ writes.set(bound, input.reservationId);
2170
+ try {
2171
+ await bound.save();
2172
+ } finally {
2173
+ writes.delete(bound);
2174
+ }
2175
+ });
2176
+ }
2177
+ async function unbindInvoiceLineSource(input) {
2178
+ if (!input.tenantId || getTenantId() !== input.tenantId) invalid$3("Active tenant required");
2179
+ const line = await (await InvoiceLineItemCollection.create({ db: input.db })).get({
2180
+ id: input.lineId,
2181
+ tenantId: input.tenantId
2182
+ }, { cache: false });
2183
+ if (!line || line.sourceReservationId !== input.reservationId) invalid$3("Owned bound invoice line required");
2184
+ await line.withTransaction(async (bound) => {
2185
+ const invoice = await (await InvoiceCollection.create({ db: bound.db })).get({
2186
+ id: bound.invoiceId,
2187
+ tenantId: input.tenantId
2188
+ }, { cache: false });
2189
+ if (!invoice || invoice.status !== "draft") invalid$3("Issued invoice source cannot be unbound");
2190
+ await (await handlerFor(bound.sourceType))({
2191
+ executor: bound.db,
2192
+ invoice,
2193
+ line: bound,
2194
+ reservationId: input.reservationId,
2195
+ phase: "release"
2196
+ });
2197
+ bound.sourceReservationId = null;
2198
+ writes.set(bound, null);
2199
+ try {
2200
+ await bound.save();
2201
+ } finally {
2202
+ writes.delete(bound);
2203
+ }
2204
+ });
2205
+ }
2206
+ //#endregion
2101
2207
  //#region src/document-money.ts
2102
2208
  var document_money_exports = /* @__PURE__ */ __exportAll({
2103
2209
  deleteInvoice: () => deleteInvoice,
@@ -2160,6 +2266,7 @@ var FROZEN_LINE_FIELDS = [
2160
2266
  "amount",
2161
2267
  "sourceType",
2162
2268
  "sourceId",
2269
+ "sourceReservationId",
2163
2270
  "periodStart",
2164
2271
  "periodEnd",
2165
2272
  "revenueAccountId",
@@ -2868,7 +2975,8 @@ async function saveInvoice(input, options) {
2868
2975
  }
2869
2976
  if (invoice.tenantId !== existing.tenantId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Invoice tenant identity cannot change");
2870
2977
  if (invoice.kind !== existing.kind || invoice.creditedInvoiceId !== existing.creditedInvoiceId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Invoice kind and credited invoice identity are immutable");
2871
- const locked = await lockAndReloadMoneyInvoice(tx, requireId(existing.id, "Invoice"), tenantId, existing.creditedInvoiceId);
2978
+ const existingId = requireId(existing.id, "Invoice");
2979
+ const locked = await lockAndReloadMoneyInvoice(tx, existingId, tenantId, existing.creditedInvoiceId);
2872
2980
  invoice.creditedAmount = locked.invoice.creditedAmount;
2873
2981
  if (isFrozen(locked.invoice)) {
2874
2982
  if (invoice.arReversalJournalId !== locked.invoice.arReversalJournalId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Invoice reversal journal identity is server-managed");
@@ -2885,6 +2993,8 @@ async function saveInvoice(input, options) {
2885
2993
  const snapshotId = freezing ? locked.invoice.moneySnapshotId || crypto.randomUUID() : "";
2886
2994
  await recomputeInvoiceAggregate(tx, invoice, settings, snapshotId);
2887
2995
  if (freezing) {
2996
+ const sourceLines = await (await InvoiceLineItemCollection.create({ db: tx })).findByInvoice(existingId);
2997
+ for (const line of sourceLines) await assertInvoiceLineSource(tx, invoice, line, line, true);
2888
2998
  await assertContractScheduleInvoiceFreeze(tx, invoice);
2889
2999
  const customers = await CustomerCollection.create({ db: tx });
2890
3000
  const customer = invoice.customerId ? await customers.get({ id: invoice.customerId }, { cache: false }) : null;
@@ -2905,17 +3015,19 @@ async function saveInvoiceLineItem(input, options) {
2905
3015
  return withDocumentMoneyObjectTransaction(input, async (line, tx) => {
2906
3016
  const candidateTenantId = getTenantId() ?? line.tenantId ?? null;
2907
3017
  const settings = await lockRuntimeSettings(tx, candidateTenantId);
2908
- const persisted = line.id ? await (await InvoiceLineItemCollection.create({ db: tx })).get({ id: line.id }, { cache: false }) : null;
3018
+ let persisted = line.id ? await (await InvoiceLineItemCollection.create({ db: tx })).get({ id: line.id }, { cache: false }) : null;
2909
3019
  const parentId = persisted?.invoiceId ?? line.invoiceId;
2910
3020
  const first = await loadInvoice(tx, parentId);
2911
3021
  if (candidateTenantId && first.invoice.tenantId !== candidateTenantId) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Invoice line tenant does not match its active money barrier");
2912
3022
  assertTenantId(first.invoice.tenantId);
2913
3023
  const { invoice, source } = await lockAndReloadMoneyInvoice(tx, parentId, first.invoice.tenantId, first.invoice.creditedInvoiceId);
3024
+ persisted = line.id ? await (await InvoiceLineItemCollection.create({ db: tx })).get({ id: line.id }, { cache: false }) : null;
2914
3025
  if (persisted && line.invoiceId !== persisted.invoiceId) throw new MoneyValidationError("FROZEN_DOCUMENT", "Invoice line cannot move between parents");
2915
3026
  line.invoiceId = requireId(invoice.id, "Invoice");
2916
3027
  line.tenantId = invoice.tenantId;
2917
3028
  if (invoice.kind === "invoice" && line.creditedLineId) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Ordinary invoice lines cannot reference credited lines");
2918
3029
  if (invoice.kind === "credit_note" && line.creditedLineId && (!source || source.id !== invoice.creditedInvoiceId)) throw new MoneyValidationError("CREDIT_TARGET_NOT_ISSUED", "Credit source changed while saving its line");
3030
+ await assertInvoiceLineSource(tx, invoice, line, persisted);
2919
3031
  if (isFrozen(invoice)) {
2920
3032
  if (!persisted) throw new MoneyValidationError("FROZEN_DOCUMENT", "Cannot add a line to a frozen invoice");
2921
3033
  assertFieldsUnchanged(line, persisted, FROZEN_LINE_FIELDS, "Invoice line");
@@ -2951,6 +3063,9 @@ async function deleteInvoiceLineItem(input, options) {
2951
3063
  if (candidateTenantId && first.invoice.tenantId !== candidateTenantId) throw new MoneyValidationError("INVALID_MONEY_INPUT", "Invoice line tenant does not match its active money barrier");
2952
3064
  assertTenantId(first.invoice.tenantId);
2953
3065
  const { invoice } = await lockAndReloadInvoice(tx, persisted.invoiceId, first.invoice.tenantId);
3066
+ const current = await (await InvoiceLineItemCollection.create({ db: tx })).get({ id: persisted.id }, { cache: false });
3067
+ if (!current) return;
3068
+ assertInvoiceSourceDelete([current]);
2954
3069
  if (isFrozen(invoice)) throw new MoneyValidationError("FROZEN_DOCUMENT", "Cannot delete a line from a frozen invoice");
2955
3070
  await line.deleteDerived(DOCUMENT_MONEY_WRITE, options);
2956
3071
  const priorAggregate = aggregateSignature(invoice);
@@ -2969,6 +3084,7 @@ async function deleteInvoice(input, options) {
2969
3084
  assertTenantId(persisted.tenantId);
2970
3085
  const persistedId = requireId(persisted.id, "Invoice");
2971
3086
  await lockAndReloadInvoice(tx, persistedId, persisted.tenantId);
3087
+ assertInvoiceSourceDelete(await (await InvoiceLineItemCollection.create({ db: tx })).findByInvoice(persistedId));
2972
3088
  await (await DocumentTaxCollection.create({ db: tx })).replaceDerivedForDocument(DOCUMENT_MONEY_WRITE, {
2973
3089
  tenantId: persisted.tenantId,
2974
3090
  documentType: "invoice",
@@ -4403,6 +4519,6 @@ var DocumentTaxCollection = class extends SmrtCollection {
4403
4519
  }
4404
4520
  };
4405
4521
  //#endregion
4406
- export { PARTY_CONTACT_MAX_LENGTHS as $, PurchaseContractCollection as A, PurchaseOrder as B, refreshIssuedCreditBalance as C, issueContractMilestoneInvoice as D, getContractBillingSchedule as E, Lease as F, Vendor as G, SupplierQuote as H, LicenseSale as I, InvoiceLineItemCollection as J, HistoricalSalesLineCollection as K, Order as L, Cart as M, Contract as N, ContractCollection as O, Estimate as P, DEFAULT_PARTY_CONTACT_FIELD_NAMES as Q, ProductionOrder as R, previewInvoiceMoney as S, approveContractBillingSchedule as T, WholesaleOrder as U, SalesContract as V, classifyContractPurchase as W, CustomerCollection as X, InvoiceLineItem as Y, Customer as Z, historicalText as _, getReceivedSalesContractMoney as a, readPartyContactRows as at, getInvoiceMoneyFacts as b, validateReceivedPurchaseMoneyFacts as c, HistoricalSalesTaxClassificationRequired as d, PartyContactPartyNotFoundError as et, listHistoricalSalesHeaderFacts as f, historicalCalendarDate as g, recordHistoricalSalesMoney as h, getReceivedPurchaseMoney as i, normalizePartyContacts as it, Agreement as j, SalesContractCollection as k, VendorCollection as l, readHistoricalSalesLines as m, DocumentTaxCollection_exports as n, PartyContactValidationError as nt, recordReceivedPurchaseMoney as o, savePartyContacts as ot, getHistoricalSalesMoney as p, HistoricalSalesLine as q, ReceivedPurchaseTaxClassificationRequired as r, applyPartyContactIntent as rt, recordReceivedSalesContractMoney as s, validatePartyContactRows as st, DocumentTaxCollection as t, PartyContactPayloadError as tt, DocumentTax as u, validateHistoricalSalesMoneyFacts as v, allocateContractMilestones as w, lockAndReloadInvoice as x, document_money_exports as y, PurchaseContract as z };
4522
+ export { CustomerCollection as $, issueContractMilestoneInvoice as A, Order as B, refreshIssuedCreditBalance as C, allocateContractMilestones as D, unbindInvoiceLineSource as E, Cart as F, SupplierQuote as G, PurchaseContract as H, Contract as I, Vendor as J, WholesaleOrder as K, Estimate as L, SalesContractCollection as M, PurchaseContractCollection as N, approveContractBillingSchedule as O, Agreement as P, InvoiceLineItem as Q, Lease as R, previewInvoiceMoney as S, registerInvoiceSourceBinding as T, PurchaseOrder as U, ProductionOrder as V, SalesContract as W, HistoricalSalesLine as X, HistoricalSalesLineCollection as Y, InvoiceLineItemCollection as Z, historicalText as _, getReceivedSalesContractMoney as a, PartyContactValidationError as at, getInvoiceMoneyFacts as b, validateReceivedPurchaseMoneyFacts as c, readPartyContactRows as ct, HistoricalSalesTaxClassificationRequired as d, Customer as et, listHistoricalSalesHeaderFacts as f, historicalCalendarDate as g, recordHistoricalSalesMoney as h, getReceivedPurchaseMoney as i, PartyContactPayloadError as it, ContractCollection as j, getContractBillingSchedule as k, VendorCollection as l, savePartyContacts as lt, readHistoricalSalesLines as m, DocumentTaxCollection_exports as n, PARTY_CONTACT_MAX_LENGTHS as nt, recordReceivedPurchaseMoney as o, applyPartyContactIntent as ot, getHistoricalSalesMoney as p, classifyContractPurchase as q, ReceivedPurchaseTaxClassificationRequired as r, PartyContactPartyNotFoundError as rt, recordReceivedSalesContractMoney as s, normalizePartyContacts as st, DocumentTaxCollection as t, DEFAULT_PARTY_CONTACT_FIELD_NAMES as tt, DocumentTax as u, validatePartyContactRows as ut, validateHistoricalSalesMoneyFacts as v, bindInvoiceLineSource as w, lockAndReloadInvoice as x, document_money_exports as y, LicenseSale as z };
4407
4523
 
4408
- //# sourceMappingURL=DocumentTaxCollection-BfuNqFNm.js.map
4524
+ //# sourceMappingURL=DocumentTaxCollection-DNo_fziv.js.map