@financica/ubl 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,8 @@ import {
3
3
  countryFromVatNumber,
4
4
  normalizeParticipantValue,
5
5
  } from "@financica/peppol/identifiers";
6
- import type { UblCompanyId, UblEndpoint } from "./ubl/types";
7
- import { normalizeString } from "./utils";
6
+ import type { UblCompanyId, UblEndpoint } from "../types";
7
+ import { compact, normalizeString } from "./utils";
8
8
 
9
9
  const normalizeBelgianCompanyNumber = (value: string | null | undefined) => {
10
10
  if (!value) return "";
@@ -33,19 +33,19 @@ export const normalizeCompanyNumberForCountry = (
33
33
  * `@financica/peppol`'s country profiles.
34
34
  *
35
35
  * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).
36
- * Returns `null` when the scheme can't be determined, in which case the
36
+ * Returns `undefined` when the scheme can't be determined, in which case the
37
37
  * CompanyID is emitted without a `schemeID` attribute.
38
38
  */
39
39
  export const resolveCompanyIdScheme = (params: {
40
40
  countryCode: string | null;
41
41
  companyNumber: string | null;
42
- }): string | null => {
42
+ }): string | undefined => {
43
43
  const companyNumber = normalizeString(params.companyNumber);
44
- if (!companyNumber) return null;
44
+ if (!companyNumber) return undefined;
45
45
 
46
- const fromCountry = getPeppolIdentifierSchemes(
47
- params.countryCode,
48
- )?.companyIdentifierScheme;
46
+ const fromCountry =
47
+ getPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ??
48
+ undefined;
49
49
  if (fromCountry) return fromCountry;
50
50
 
51
51
  // Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.
@@ -53,29 +53,29 @@ export const resolveCompanyIdScheme = (params: {
53
53
  .replace(/[^A-Za-z]/g, "")
54
54
  .toUpperCase()
55
55
  .slice(0, 2);
56
- return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? null;
56
+ return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? undefined;
57
57
  };
58
58
 
59
59
  /**
60
60
  * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the
61
- * country-appropriate ICD scheme when known. Returns `null` when there is no
61
+ * country-appropriate ICD scheme when known. Returns `undefined` when there is no
62
62
  * company number.
63
63
  */
64
64
  export const buildCompanyId = (params: {
65
65
  countryCode: string | null;
66
66
  companyNumber: string | null;
67
- }): UblCompanyId | null => {
67
+ }): UblCompanyId | undefined => {
68
68
  const normalized = normalizeString(
69
69
  normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),
70
70
  );
71
- if (!normalized) return null;
72
- return {
71
+ if (!normalized) return undefined;
72
+ return compact({
73
73
  value: normalized,
74
74
  scheme: resolveCompanyIdScheme({
75
75
  countryCode: params.countryCode,
76
76
  companyNumber: normalized,
77
77
  }),
78
- };
78
+ });
79
79
  };
80
80
 
81
81
  /**
@@ -85,30 +85,30 @@ export const buildCompanyId = (params: {
85
85
  * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
86
86
  *
87
87
  * The scheme comes from `@financica/peppol`'s country resolution, so countries
88
- * that route on their registry number alone (Norway, Denmark) yield `null`
88
+ * that route on their registry number alone (Norway, Denmark) yield `undefined`
89
89
  * here — their VAT number is not a Peppol participant identifier.
90
90
  *
91
91
  * The value keeps its country prefix, matching how participants register (the
92
- * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
92
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`
93
93
  * when the country has no VAT EAS scheme or the input is empty.
94
94
  */
95
95
  export const resolveVatEndpoint = (params: {
96
96
  vatNumber: string | null | undefined;
97
97
  countryCode?: string | null | undefined;
98
- }): UblEndpoint | null => {
98
+ }): UblEndpoint | undefined => {
99
99
  const value = normalizeString(params.vatNumber);
100
- if (!value) return null;
100
+ if (!value) return undefined;
101
101
 
102
102
  const fromPrefix = countryFromVatNumber(value);
103
103
  const scheme =
104
104
  getPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ??
105
105
  getPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;
106
- if (!scheme) return null;
106
+ if (!scheme) return undefined;
107
107
 
108
108
  // Every scheme in the table is a VAT scheme, whose value carries no
109
109
  // separator, so the printed dots/spaces are dropped.
110
110
  const cleaned = normalizeParticipantValue(scheme, value).toUpperCase();
111
- if (!cleaned) return null;
111
+ if (!cleaned) return undefined;
112
112
 
113
113
  return { scheme, value: cleaned };
114
114
  };
@@ -117,19 +117,19 @@ export const resolveVatEndpoint = (params: {
117
117
  * Parse a Peppol participant identifier into a {@link UblEndpoint}.
118
118
  *
119
119
  * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
120
- * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
120
+ * `undefined` for values without an explicit scheme, since `cbc:EndpointID` requires
121
121
  * a `schemeID` and guessing one would mis-route the document.
122
122
  */
123
123
  export const parsePeppolEndpoint = (
124
124
  peppolId: string | null | undefined,
125
- ): UblEndpoint | null => {
125
+ ): UblEndpoint | undefined => {
126
126
  const normalized = normalizeString(peppolId);
127
- if (!normalized) return null;
127
+ if (!normalized) return undefined;
128
128
  const separatorIndex = normalized.indexOf(":");
129
- if (separatorIndex <= 0) return null;
129
+ if (separatorIndex <= 0) return undefined;
130
130
  const scheme = normalized.slice(0, separatorIndex).trim();
131
131
  const value = normalized.slice(separatorIndex + 1).trim();
132
- if (!scheme || !value) return null;
132
+ if (!scheme || !value) return undefined;
133
133
  return { scheme, value };
134
134
  };
135
135
 
@@ -150,8 +150,8 @@ export interface CustomerTaxIdInput {
150
150
  value: string | null | undefined;
151
151
  }
152
152
 
153
- const normalizeIdentifierType = (value: string | null) =>
154
- value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
153
+ const normalizeIdentifierType = (value: string | undefined) =>
154
+ value?.toLowerCase().replace(/[^a-z0-9]+/g, "_");
155
155
 
156
156
  /**
157
157
  * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
@@ -217,7 +217,7 @@ export const listPeppolReceiverIdentifierCandidates = (
217
217
  countryCode?: string | null,
218
218
  ): string[] => {
219
219
  const candidates: string[] = [];
220
- const add = (id: { scheme?: string | null; value: string } | null) => {
220
+ const add = (id: { scheme?: string | undefined; value: string } | undefined) => {
221
221
  if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
222
222
  };
223
223
 
@@ -1,26 +1,46 @@
1
- // Generic Peppol BIS Billing 3.0 UBL build core: a document model, a
2
- // serializer, and the party/tax/identifier/attachment builders shared by every
3
- // "X → UBL" adapter (e.g. @financica/stripe-ubl, and app-specific row builders).
4
- // Exposed under the `@financica/ubl/build` subpath so its build-side types do
5
- // not collide with the parse-side types exported from the package root.
1
+ // Generic Peppol BIS Billing 3.0 UBL build core: a serializer and the
2
+ // party/tax/identifier/attachment builders shared by every "X → UBL" adapter
3
+ // (e.g. @financica/stripe-ubl, and app-specific row builders). The document
4
+ // model is the one the parser produces (`../types`), re-exported here so a
5
+ // build-side caller needs only this subpath.
6
6
 
7
7
  // ── UBL document model + serializer ────────────────────────────────────
8
8
  export * from "./ubl/constants";
9
- export { serializeUblDocument } from "./ubl/serialize";
9
+ export { UblBuildError } from "../errors";
10
+ export { serializeUblDocument, serializeUblInvoice } from "./ubl/serialize";
10
11
  export type {
11
12
  UblAddress,
13
+ UblAllowanceCharge,
12
14
  UblAttachment,
15
+ UblBillingReference,
16
+ UblCommodityClassification,
13
17
  UblCompanyId,
14
- UblDocument,
18
+ UblContact,
19
+ UblDelivery,
20
+ UblDocumentReference,
15
21
  UblEndpoint,
22
+ UblInvoice,
23
+ UblInvoicePeriod,
24
+ UblItemProperty,
16
25
  UblLine,
17
26
  UblMonetaryTotal,
18
27
  UblParty,
19
- UblPeriod,
28
+ UblPartyIdentification,
29
+ UblPaymentMeans,
30
+ UblPriceAllowance,
31
+ UblSchemedId,
20
32
  UblTaxCategory,
21
33
  UblTaxSubtotal,
22
34
  UblTaxTotal,
23
- } from "./ubl/types";
35
+ } from "../types";
36
+ import type {
37
+ UblInvoice as _UblInvoice,
38
+ UblInvoicePeriod as _UblInvoicePeriod,
39
+ } from "../types";
40
+ /** @deprecated The build and parse models are one; use {@link UblInvoice}. */
41
+ export type UblDocument = _UblInvoice;
42
+ /** @deprecated Use {@link UblInvoicePeriod}. */
43
+ export type UblPeriod = _UblInvoicePeriod;
24
44
 
25
45
  // ── Party builders ─────────────────────────────────────────────────────
26
46
  export {
@@ -59,6 +79,7 @@ export {
59
79
  taxCategoryFromReasonOrRate,
60
80
  } from "./tax-category";
61
81
  export {
82
+ allocateAcrossTaxCategories,
62
83
  type BuildTaxTotalsOptions,
63
84
  type BuildTaxTotalsResult,
64
85
  buildTaxTotals,
@@ -5,11 +5,15 @@ export const roundCurrency = (value: number) =>
5
5
  /** Convert an integer cent amount into a 2-decimal currency value. */
6
6
  export const centsToDecimal = (cents: number) => roundCurrency(cents / 100);
7
7
 
8
- /** The `cac:Price` pair for a line: BT-146 and the optional BT-149. */
8
+ /** The `cac:Price` pair for a line: the per-unit price and the optional BT-149. */
9
9
  export interface UnitPrice {
10
- /** `cbc:PriceAmount` (BT-146). */
11
- priceAmount: number;
12
- /** `cbc:BaseQuantity` (BT-149) — the units `priceAmount` covers. Omitted = 1. */
10
+ /** Net price of one unit (`UblLine.unitPrice`). */
11
+ unitPrice: number;
12
+ /**
13
+ * `cbc:BaseQuantity` (BT-149) — set when the per-unit price is not exact in
14
+ * cents; the serializer then emits `PriceAmount = unitPrice × baseQuantity`
15
+ * (the line net). Omitted = 1.
16
+ */
13
17
  baseQuantity?: number | undefined;
14
18
  }
15
19
 
@@ -17,17 +21,19 @@ export interface UnitPrice {
17
21
  * Derive the `cac:Price` for a line whose net total is authoritative.
18
22
  *
19
23
  * Peppol rule PEPPOL-EN16931-R120 checks
20
- * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
24
+ * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within
21
25
  * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
22
26
  * whenever the division doesn't land on a cent: 940.00 over 14 units gives
23
27
  * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
24
28
  * rejected as a fatal validation error.
25
29
  *
26
30
  * So the cent-rounded unit price is only used when it reproduces the net
27
- * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =
28
- * the net, `baseQuantity` = the quantity), which is exact at any magnitude
29
- * instead of merely within tolerance — the residual of a rounded unit price
30
- * grows with quantity and would eventually breach 0.02 at any fixed precision.
31
+ * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is
32
+ * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so
33
+ * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the
34
+ * quantity, which is exact at any magnitude instead of merely within tolerance
35
+ * — the residual of a rounded unit price grows with quantity and would
36
+ * eventually breach 0.02 at any fixed precision.
31
37
  */
32
38
  export const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {
33
39
  // A zero or fractional-to-zero quantity still has to price something; BT-149
@@ -35,7 +41,7 @@ export const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice =
35
41
  const units = quantity > 0 ? quantity : 1;
36
42
  const perUnit = roundCurrency(netTotal / units);
37
43
  if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {
38
- return { priceAmount: perUnit };
44
+ return { unitPrice: perUnit };
39
45
  }
40
- return { priceAmount: roundCurrency(netTotal), baseQuantity: units };
46
+ return { unitPrice: roundCurrency(netTotal) / units, baseQuantity: units };
41
47
  };
@@ -1,7 +1,7 @@
1
1
  import { type AddressInput, normalizeAddress } from "./address";
2
2
  import { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from "./identifiers";
3
- import type { UblAddress, UblEndpoint, UblParty } from "./ubl/types";
4
- import { normalizeString } from "./utils";
3
+ import type { UblAddress, UblEndpoint, UblParty } from "../types";
4
+ import { compact, normalizeString } from "./utils";
5
5
 
6
6
  /**
7
7
  * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the
@@ -45,20 +45,20 @@ export interface UblSupplier {
45
45
  peppolID?: string | null;
46
46
  }
47
47
 
48
- /** Convert a {@link UblSupplier} into the supplier (seller) party. */
48
+ /** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */
49
49
  export const buildSupplierParty = (supplier: UblSupplier): UblParty => {
50
50
  const address = normalizeAddress(supplier.address, supplier.countryCode);
51
- return {
51
+ return compact({
52
52
  endpoint: parsePeppolEndpoint(supplier.peppolID),
53
53
  name: supplier.name,
54
+ registrationName: supplier.name,
54
55
  address,
55
- vatNumber: normalizeString(supplier.vatNumber),
56
- legalName: supplier.name,
56
+ vatId: normalizeString(supplier.vatNumber),
57
57
  companyId: buildCompanyId({
58
58
  countryCode: supplier.countryCode,
59
59
  companyNumber: supplier.companyNumber ?? null,
60
60
  }),
61
- };
61
+ });
62
62
  };
63
63
 
64
64
  /**
@@ -91,7 +91,7 @@ export interface UblCustomer {
91
91
  }
92
92
 
93
93
  /**
94
- * Convert a {@link UblCustomer} into the customer (buyer) party.
94
+ * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).
95
95
  *
96
96
  * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
97
97
  * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
@@ -106,22 +106,24 @@ export const buildCustomerParty = (
106
106
  endpointOverride?: UblEndpoint | null,
107
107
  ): UblParty => {
108
108
  const countryCode =
109
- normalizeString(customer.countryCode) ?? customer.address.countryCode;
109
+ normalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;
110
110
  const endpoint =
111
111
  endpointOverride ??
112
112
  parsePeppolEndpoint(customer.peppolID) ??
113
- (customer.glnNumber ? { scheme: "0088", value: customer.glnNumber } : null) ??
113
+ (customer.glnNumber
114
+ ? { scheme: "0088", value: customer.glnNumber }
115
+ : undefined) ??
114
116
  resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
115
117
 
116
- return {
118
+ return compact({
117
119
  endpoint,
118
120
  name: customer.name,
121
+ registrationName: customer.name,
119
122
  address: customer.address,
120
- vatNumber: normalizeString(customer.vatNumber),
121
- legalName: customer.name,
123
+ vatId: normalizeString(customer.vatNumber),
122
124
  companyId: buildCompanyId({
123
125
  countryCode,
124
126
  companyNumber: customer.taxNumber ?? null,
125
127
  }),
126
- };
128
+ });
127
129
  };
@@ -1,5 +1,5 @@
1
1
  import type { SupplierVatStatus } from "./party";
2
- import type { UblLine, UblTaxCategory } from "./ubl/types";
2
+ import type { UblLine, UblTaxCategory } from "../types";
3
3
  import { normalizeString } from "./utils";
4
4
 
5
5
  /**
@@ -34,8 +34,8 @@ export interface TaxAmountInfo {
34
34
  tax_rate_percentage?: number | null;
35
35
  }
36
36
 
37
- const normalizeTaxCategoryId = (value: string | null | undefined): string | null =>
38
- normalizeString(value)?.toUpperCase() ?? null;
37
+ const normalizeTaxCategoryId = (value: string | null | undefined): string | undefined =>
38
+ normalizeString(value)?.toUpperCase();
39
39
 
40
40
  /**
41
41
  * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
@@ -82,7 +82,8 @@ export const taxCategoryFromReasonOrRate = (params: {
82
82
  id: "E",
83
83
  percent: 0,
84
84
  exemptionReason:
85
- (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT",
85
+ (reason ? EXEMPTION_REASON_TEXT[reason] : undefined) ??
86
+ "Exempt from VAT",
86
87
  };
87
88
  }
88
89
  if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) {
@@ -1,11 +1,16 @@
1
- import { deriveUnitPrice, roundCurrency } from "./numeric";
1
+ import { UblBuildError } from "../errors";
2
2
  import type {
3
+ UblAllowanceCharge,
3
4
  UblLine,
4
5
  UblMonetaryTotal,
5
6
  UblTaxCategory,
6
7
  UblTaxSubtotal,
7
8
  UblTaxTotal,
8
- } from "./ubl/types";
9
+ } from "../types";
10
+ import { deriveUnitPrice, roundCurrency } from "./numeric";
11
+ import { compact } from "./utils";
12
+
13
+ const lineNet = (line: UblLine): number => line.lineExtensionAmount ?? 0;
9
14
 
10
15
  /**
11
16
  * Adjust the largest line's net amount so the line nets sum to the
@@ -22,39 +27,38 @@ export const reconcileLinesToExclTotal = (
22
27
  authoritativeTotalExclVat: number,
23
28
  ): UblLine[] => {
24
29
  if (lines.length === 0) return lines;
25
- const computed = roundCurrency(
26
- lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),
27
- );
30
+ const computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));
28
31
  const diff = roundCurrency(authoritativeTotalExclVat - computed);
29
32
  if (diff === 0) return lines;
30
33
 
31
34
  const largestIdx = lines.reduce(
32
35
  (maxIdx, line, idx, arr) =>
33
- line.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)
34
- ? idx
35
- : maxIdx,
36
+ lineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : maxIdx,
36
37
  0,
37
38
  );
38
39
 
39
40
  return lines.map((line, idx) => {
40
41
  if (idx !== largestIdx) return line;
41
- const adjusted = roundCurrency(line.lineExtensionAmount + diff);
42
+ const adjusted = roundCurrency(lineNet(line) + diff);
42
43
  // Re-derive the price from the adjusted net through the shared helper —
43
44
  // nudging the net without re-deriving BT-146/BT-149 to match is exactly
44
45
  // what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally
45
46
  // so a line that no longer needs one doesn't keep a stale value.
46
- const { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);
47
- return {
47
+ const { unitPrice, baseQuantity } = deriveUnitPrice(
48
+ adjusted,
49
+ line.quantity ?? 0,
50
+ );
51
+ return compact({
48
52
  ...line,
49
53
  lineExtensionAmount: adjusted,
50
- priceAmount,
54
+ unitPrice,
51
55
  baseQuantity,
52
- };
56
+ });
53
57
  });
54
58
  };
55
59
 
56
60
  const categoryKey = (category: UblTaxCategory): string =>
57
- `${category.id}:${category.percent}`;
61
+ `${category.id ?? ""}:${category.percent ?? ""}`;
58
62
 
59
63
  export interface BuildTaxTotalsResult {
60
64
  taxTotal: UblTaxTotal;
@@ -70,6 +74,13 @@ export interface BuildTaxTotalsOptions {
70
74
  prepaidAmount?: number;
71
75
  /** BT-114 — rounding applied to the payable amount. */
72
76
  payableRoundingAmount?: number;
77
+ /**
78
+ * Document-level allowances and charges (BG-20/BG-21). Each one joins the
79
+ * VAT breakdown of its own category (BR-S-08: taxable = line nets −
80
+ * allowances + charges) and feeds BT-107/BT-108, so BT-109 is
81
+ * BT-106 − BT-107 + BT-108 (BR-CO-13). Put the same array on the document.
82
+ */
83
+ allowanceCharges?: UblAllowanceCharge[];
73
84
  }
74
85
 
75
86
  /**
@@ -87,6 +98,9 @@ export interface BuildTaxTotalsOptions {
87
98
  * invariant holds by construction. The result is *not* clamped: a prepayment
88
99
  * exceeding the total yields a negative payable amount, surfacing the upstream
89
100
  * overpayment rather than hiding it.
101
+ *
102
+ * @throws {UblBuildError} for a line, allowance or charge without a
103
+ * `taxCategory` — there is no VAT breakdown to put it in.
90
104
  */
91
105
  export const buildTaxTotals = (
92
106
  lines: UblLine[],
@@ -98,30 +112,64 @@ export const buildTaxTotals = (
98
112
  >();
99
113
 
100
114
  for (const line of lines) {
115
+ if (!line.taxCategory) {
116
+ throw new UblBuildError(
117
+ `Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`,
118
+ );
119
+ }
101
120
  const key = categoryKey(line.taxCategory);
102
121
  const current = groups.get(key) ?? {
103
122
  category: line.taxCategory,
104
123
  taxableAmount: 0,
105
124
  };
106
- current.taxableAmount = roundCurrency(
107
- current.taxableAmount + line.lineExtensionAmount,
108
- );
125
+ current.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));
126
+ groups.set(key, current);
127
+ }
128
+ const allowanceCharges = options?.allowanceCharges ?? [];
129
+ for (const [index, item] of allowanceCharges.entries()) {
130
+ if (!item.taxCategory) {
131
+ throw new UblBuildError(
132
+ `allowanceCharges[${index}] has no taxCategory (BT-95/BT-102); cannot build the VAT breakdown`,
133
+ );
134
+ }
135
+ const key = categoryKey(item.taxCategory);
136
+ const current = groups.get(key) ?? {
137
+ category: item.taxCategory,
138
+ taxableAmount: 0,
139
+ };
140
+ const signed = item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0);
141
+ current.taxableAmount = roundCurrency(current.taxableAmount + signed);
109
142
  groups.set(key, current);
110
143
  }
111
144
 
112
145
  const subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({
113
146
  taxableAmount: group.taxableAmount,
114
- taxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),
147
+ taxAmount: roundCurrency(
148
+ (group.taxableAmount * (group.category.percent ?? 0)) / 100,
149
+ ),
115
150
  category: group.category,
116
151
  }));
117
152
 
118
153
  const lineExtensionAmount = roundCurrency(
119
- lines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),
154
+ lines.reduce((sum, line) => sum + lineNet(line), 0),
120
155
  );
121
156
  const taxAmount = roundCurrency(
122
- subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),
157
+ subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),
123
158
  );
124
- const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
159
+ const allowanceTotalAmount = roundCurrency(
160
+ allowanceCharges
161
+ .filter((item) => !item.chargeIndicator)
162
+ .reduce((sum, item) => sum + (item.amount ?? 0), 0),
163
+ );
164
+ const chargeTotalAmount = roundCurrency(
165
+ allowanceCharges
166
+ .filter((item) => item.chargeIndicator)
167
+ .reduce((sum, item) => sum + (item.amount ?? 0), 0),
168
+ );
169
+ const taxExclusiveAmount = roundCurrency(
170
+ lineExtensionAmount - allowanceTotalAmount + chargeTotalAmount,
171
+ );
172
+ const taxInclusiveAmount = roundCurrency(taxExclusiveAmount + taxAmount);
125
173
 
126
174
  const prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);
127
175
  const payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);
@@ -133,11 +181,70 @@ export const buildTaxTotals = (
133
181
  taxTotal: { taxAmount, subtotals },
134
182
  monetaryTotal: {
135
183
  lineExtensionAmount,
136
- taxExclusiveAmount: lineExtensionAmount,
184
+ taxExclusiveAmount,
137
185
  taxInclusiveAmount,
186
+ ...(allowanceTotalAmount ? { allowanceTotalAmount } : {}),
187
+ ...(chargeTotalAmount ? { chargeTotalAmount } : {}),
138
188
  ...(prepaidAmount ? { prepaidAmount } : {}),
139
189
  ...(payableRoundingAmount ? { payableRoundingAmount } : {}),
140
190
  payableAmount,
141
191
  },
142
192
  };
143
193
  };
194
+
195
+ /**
196
+ * Split one document-level amount into an allowance or charge per VAT
197
+ * category the lines use, pro rata by each category's line nets, so a
198
+ * shipping charge or an invoice-wide discount on a mixed-rate invoice lands in
199
+ * the right VAT subtotals (an ancillary cost follows the supply it belongs to).
200
+ * Cent remainders go to the largest shares so the parts sum to `amount`
201
+ * exactly; categories that receive nothing are omitted. With no positive
202
+ * line net at all the whole amount goes to the first line's category.
203
+ *
204
+ * @throws {UblBuildError} for a line without a `taxCategory`.
205
+ */
206
+ export const allocateAcrossTaxCategories = (
207
+ amount: number,
208
+ lines: UblLine[],
209
+ template: Pick<UblAllowanceCharge, "chargeIndicator" | "reason" | "reasonCode">,
210
+ ): UblAllowanceCharge[] => {
211
+ const groups = new Map<string, { category: UblTaxCategory; net: number }>();
212
+ for (const line of lines) {
213
+ if (!line.taxCategory) {
214
+ throw new UblBuildError(
215
+ `Line ${line.id} has no taxCategory (BT-151); cannot allocate across categories`,
216
+ );
217
+ }
218
+ const key = categoryKey(line.taxCategory);
219
+ const current = groups.get(key) ?? { category: line.taxCategory, net: 0 };
220
+ current.net = roundCurrency(current.net + Math.max(0, lineNet(line)));
221
+ groups.set(key, current);
222
+ }
223
+ const entries = Array.from(groups.values());
224
+ const total = roundCurrency(amount);
225
+ if (entries.length === 0 || total === 0) return [];
226
+ const netSum = entries.reduce((sum, entry) => sum + entry.net, 0);
227
+ const shares =
228
+ netSum > 0
229
+ ? entries.map((entry) => (total * entry.net) / netSum)
230
+ : entries.map((_entry, index) => (index === 0 ? total : 0));
231
+ const cents = shares.map((share) => Math.floor(share * 100 + 1e-9));
232
+ let remainder =
233
+ Math.round(total * 100) - cents.reduce((sum, value) => sum + value, 0);
234
+ const order = shares
235
+ .map((share, index) => ({
236
+ index,
237
+ fraction: share * 100 - Math.floor(share * 100 + 1e-9),
238
+ }))
239
+ .sort((a, b) => b.fraction - a.fraction);
240
+ for (const { index } of order) {
241
+ if (remainder <= 0) break;
242
+ cents[index] = (cents[index] ?? 0) + 1;
243
+ remainder -= 1;
244
+ }
245
+ return entries.flatMap((entry, index) => {
246
+ const value = (cents[index] ?? 0) / 100;
247
+ if (value === 0) return [];
248
+ return [compact({ ...template, amount: value, taxCategory: entry.category })];
249
+ });
250
+ };