@financica/ubl 0.15.0 → 0.16.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.
- package/CHANGELOG.md +161 -0
- package/dist/build/index.d.ts +76 -40
- package/dist/build/index.d.ts.map +1 -1
- package/dist/build/index.js +55 -109
- package/dist/build/index.js.map +1 -1
- package/dist/index.d.ts +149 -121
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +277 -233
- package/dist/index.js.map +1 -1
- package/package.json +16 -7
- package/src/attachments.ts +67 -0
- package/src/build/address.ts +64 -0
- package/src/build/attachment.ts +33 -0
- package/src/build/identifiers.ts +253 -0
- package/src/build/index.ts +69 -0
- package/src/build/numeric.ts +41 -0
- package/src/build/party.ts +127 -0
- package/src/build/tax-category.ts +152 -0
- package/src/build/tax-totals.ts +143 -0
- package/src/build/ubl/constants.ts +30 -0
- package/src/build/ubl/serialize.ts +258 -0
- package/src/build/ubl/types.ts +179 -0
- package/src/build/utils.ts +6 -0
- package/src/build/xml.ts +84 -0
- package/src/errors.ts +15 -0
- package/src/index.ts +40 -0
- package/src/mlr.ts +156 -0
- package/src/normalize.ts +407 -0
- package/src/parser.ts +596 -0
- package/src/types.ts +234 -0
- package/src/xml-dom.ts +37 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { getPeppolIdentifierSchemes } from "@financica/peppol/countries";
|
|
2
|
+
import {
|
|
3
|
+
countryFromVatNumber,
|
|
4
|
+
normalizeParticipantValue,
|
|
5
|
+
} from "@financica/peppol/identifiers";
|
|
6
|
+
import type { UblCompanyId, UblEndpoint } from "./ubl/types";
|
|
7
|
+
import { normalizeString } from "./utils";
|
|
8
|
+
|
|
9
|
+
const normalizeBelgianCompanyNumber = (value: string | null | undefined) => {
|
|
10
|
+
if (!value) return "";
|
|
11
|
+
// EAS 0208 (BE:EN) is 10 bare digits, so the printed dots are decoration.
|
|
12
|
+
return normalizeParticipantValue("0208", value).toUpperCase().replace(/^BE/, "");
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Strip whitespace/punctuation from a country-specific company number.
|
|
17
|
+
* For Belgium, also strips an optional `BE` prefix.
|
|
18
|
+
*/
|
|
19
|
+
export const normalizeCompanyNumberForCountry = (
|
|
20
|
+
countryCode: string | null | undefined,
|
|
21
|
+
companyNumber: string | null | undefined,
|
|
22
|
+
) => {
|
|
23
|
+
if (!companyNumber) return "";
|
|
24
|
+
const upper = countryCode?.trim().toUpperCase() ?? "";
|
|
25
|
+
if (upper === "BE") return normalizeBelgianCompanyNumber(companyNumber);
|
|
26
|
+
return companyNumber.trim();
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Peppol/ISO 6523 ICD scheme for a legal registration number
|
|
31
|
+
* (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`), e.g. BE → `0208`
|
|
32
|
+
* (enterprise number), NL → `0106` (KvK), FR → `0002` (SIRENE). The table is
|
|
33
|
+
* `@financica/peppol`'s country profiles.
|
|
34
|
+
*
|
|
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
|
|
37
|
+
* CompanyID is emitted without a `schemeID` attribute.
|
|
38
|
+
*/
|
|
39
|
+
export const resolveCompanyIdScheme = (params: {
|
|
40
|
+
countryCode: string | null;
|
|
41
|
+
companyNumber: string | null;
|
|
42
|
+
}): string | null => {
|
|
43
|
+
const companyNumber = normalizeString(params.companyNumber);
|
|
44
|
+
if (!companyNumber) return null;
|
|
45
|
+
|
|
46
|
+
const fromCountry = getPeppolIdentifierSchemes(
|
|
47
|
+
params.countryCode,
|
|
48
|
+
)?.companyIdentifierScheme;
|
|
49
|
+
if (fromCountry) return fromCountry;
|
|
50
|
+
|
|
51
|
+
// Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.
|
|
52
|
+
const prefix = companyNumber
|
|
53
|
+
.replace(/[^A-Za-z]/g, "")
|
|
54
|
+
.toUpperCase()
|
|
55
|
+
.slice(0, 2);
|
|
56
|
+
return getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? null;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
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
|
|
62
|
+
* company number.
|
|
63
|
+
*/
|
|
64
|
+
export const buildCompanyId = (params: {
|
|
65
|
+
countryCode: string | null;
|
|
66
|
+
companyNumber: string | null;
|
|
67
|
+
}): UblCompanyId | null => {
|
|
68
|
+
const normalized = normalizeString(
|
|
69
|
+
normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),
|
|
70
|
+
);
|
|
71
|
+
if (!normalized) return null;
|
|
72
|
+
return {
|
|
73
|
+
value: normalized,
|
|
74
|
+
scheme: resolveCompanyIdScheme({
|
|
75
|
+
countryCode: params.countryCode,
|
|
76
|
+
companyNumber: normalized,
|
|
77
|
+
}),
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Resolve the Peppol participant identifier for a VAT number, deriving the EAS
|
|
83
|
+
* scheme from the number's own country prefix (falling back to `countryCode`).
|
|
84
|
+
*
|
|
85
|
+
* `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
|
|
86
|
+
*
|
|
87
|
+
* The scheme comes from `@financica/peppol`'s country resolution, so countries
|
|
88
|
+
* that route on their registry number alone (Norway, Denmark) yield `null`
|
|
89
|
+
* here — their VAT number is not a Peppol participant identifier.
|
|
90
|
+
*
|
|
91
|
+
* The value keeps its country prefix, matching how participants register (the
|
|
92
|
+
* Peppol directory lists this party as `9925:be0206582284`). Returns `null`
|
|
93
|
+
* when the country has no VAT EAS scheme or the input is empty.
|
|
94
|
+
*/
|
|
95
|
+
export const resolveVatEndpoint = (params: {
|
|
96
|
+
vatNumber: string | null | undefined;
|
|
97
|
+
countryCode?: string | null | undefined;
|
|
98
|
+
}): UblEndpoint | null => {
|
|
99
|
+
const value = normalizeString(params.vatNumber);
|
|
100
|
+
if (!value) return null;
|
|
101
|
+
|
|
102
|
+
const fromPrefix = countryFromVatNumber(value);
|
|
103
|
+
const scheme =
|
|
104
|
+
getPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ??
|
|
105
|
+
getPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;
|
|
106
|
+
if (!scheme) return null;
|
|
107
|
+
|
|
108
|
+
// Every scheme in the table is a VAT scheme, whose value carries no
|
|
109
|
+
// separator, so the printed dots/spaces are dropped.
|
|
110
|
+
const cleaned = normalizeParticipantValue(scheme, value).toUpperCase();
|
|
111
|
+
if (!cleaned) return null;
|
|
112
|
+
|
|
113
|
+
return { scheme, value: cleaned };
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Parse a Peppol participant identifier into a {@link UblEndpoint}.
|
|
118
|
+
*
|
|
119
|
+
* Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
|
|
120
|
+
* `null` for values without an explicit scheme, since `cbc:EndpointID` requires
|
|
121
|
+
* a `schemeID` and guessing one would mis-route the document.
|
|
122
|
+
*/
|
|
123
|
+
export const parsePeppolEndpoint = (
|
|
124
|
+
peppolId: string | null | undefined,
|
|
125
|
+
): UblEndpoint | null => {
|
|
126
|
+
const normalized = normalizeString(peppolId);
|
|
127
|
+
if (!normalized) return null;
|
|
128
|
+
const separatorIndex = normalized.indexOf(":");
|
|
129
|
+
if (separatorIndex <= 0) return null;
|
|
130
|
+
const scheme = normalized.slice(0, separatorIndex).trim();
|
|
131
|
+
const value = normalized.slice(separatorIndex + 1).trim();
|
|
132
|
+
if (!scheme || !value) return null;
|
|
133
|
+
return { scheme, value };
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export interface CustomerTaxIdentifiers {
|
|
137
|
+
peppolID: string | null;
|
|
138
|
+
glnNumber: string | null;
|
|
139
|
+
taxNumber: string | null;
|
|
140
|
+
vatNumber: string | null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* One customer tax identifier as stored by Stripe (`customer_tax_ids[]`) or an
|
|
145
|
+
* equivalent `{type, value}` pair. `type` is a Stripe tax-ID type such as
|
|
146
|
+
* `eu_vat`, or a custom type such as `peppol_id`; blank entries are skipped.
|
|
147
|
+
*/
|
|
148
|
+
export interface CustomerTaxIdInput {
|
|
149
|
+
type: string | null | undefined;
|
|
150
|
+
value: string | null | undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const normalizeIdentifierType = (value: string | null) =>
|
|
154
|
+
value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Pick the first usable Peppol identifier, GLN, VAT number, and tax number
|
|
158
|
+
* from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
|
|
159
|
+
*
|
|
160
|
+
* Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.
|
|
161
|
+
* Peppol IDs are typically stored as a custom `peppol_id` type.
|
|
162
|
+
*/
|
|
163
|
+
export const extractCustomerTaxIdentifiers = (
|
|
164
|
+
taxIds: readonly CustomerTaxIdInput[] | null | undefined,
|
|
165
|
+
): CustomerTaxIdentifiers => {
|
|
166
|
+
let peppolID: string | null = null;
|
|
167
|
+
let glnNumber: string | null = null;
|
|
168
|
+
let taxNumber: string | null = null;
|
|
169
|
+
let vatNumber: string | null = null;
|
|
170
|
+
|
|
171
|
+
for (const entry of taxIds ?? []) {
|
|
172
|
+
const type = normalizeIdentifierType(normalizeString(entry.type));
|
|
173
|
+
const value = normalizeString(entry.value);
|
|
174
|
+
if (!type || !value) continue;
|
|
175
|
+
|
|
176
|
+
if (!peppolID && type.includes("peppol")) {
|
|
177
|
+
peppolID = value;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (!glnNumber && type.includes("gln")) {
|
|
181
|
+
glnNumber = value;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (!vatNumber && type.includes("vat")) {
|
|
185
|
+
vatNumber = value;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
// Any other typed id (ca_gst_hst, au_abn, us_ein, ...) is a registration
|
|
189
|
+
// number: it goes to BT-30, not BT-31.
|
|
190
|
+
if (!taxNumber) taxNumber = value;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return { peppolID, glnNumber, taxNumber, vatNumber };
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Build the fully-qualified Peppol participant identifiers (`scheme:value`) a
|
|
198
|
+
* receiver lookup will accept, in priority order, de-duplicated.
|
|
199
|
+
*
|
|
200
|
+
* Stripe stores a customer's VAT number without a Peppol scheme (e.g.
|
|
201
|
+
* `BE0206582284`), but a participant lookup needs the qualified identifier
|
|
202
|
+
* (`9925:BE0206582284`). This attaches the right scheme:
|
|
203
|
+
*
|
|
204
|
+
* 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
|
|
205
|
+
* 2. a GLN under EAS `0088`;
|
|
206
|
+
* 3. the VAT number under its country's VAT EAS scheme (see
|
|
207
|
+
* {@link resolveVatEndpoint});
|
|
208
|
+
* 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
|
|
209
|
+
* under EAS `0208` — many Belgian entities register only under that;
|
|
210
|
+
* 5. a generic tax/registration number under its country's company-ID scheme.
|
|
211
|
+
*
|
|
212
|
+
* `countryCode` (the customer's country, when known) disambiguates schemes for
|
|
213
|
+
* identifiers that don't carry a country prefix (GLN, plain tax numbers).
|
|
214
|
+
*/
|
|
215
|
+
export const listPeppolReceiverIdentifierCandidates = (
|
|
216
|
+
customer: Partial<CustomerTaxIdentifiers>,
|
|
217
|
+
countryCode?: string | null,
|
|
218
|
+
): string[] => {
|
|
219
|
+
const candidates: string[] = [];
|
|
220
|
+
const add = (id: { scheme?: string | null; value: string } | null) => {
|
|
221
|
+
if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
// 1. An explicit Peppol ID already carries its own scheme.
|
|
225
|
+
const peppol = normalizeString(customer.peppolID);
|
|
226
|
+
if (peppol) candidates.push(peppol);
|
|
227
|
+
|
|
228
|
+
// 2. GLN → EAS 0088 (Global Location Number).
|
|
229
|
+
const gln = normalizeString(customer.glnNumber);
|
|
230
|
+
if (gln) add({ scheme: "0088", value: normalizeParticipantValue("0088", gln) });
|
|
231
|
+
|
|
232
|
+
// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).
|
|
233
|
+
const vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
|
|
234
|
+
add(vat);
|
|
235
|
+
|
|
236
|
+
// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is
|
|
237
|
+
// the VAT digits without the `BE` prefix, and some entities register only so.
|
|
238
|
+
if (vat?.scheme === "9925") {
|
|
239
|
+
add(
|
|
240
|
+
buildCompanyId({
|
|
241
|
+
countryCode: "BE",
|
|
242
|
+
companyNumber: customer.vatNumber ?? null,
|
|
243
|
+
}),
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// 5. A generic tax/registration number → its country's company-ID scheme.
|
|
248
|
+
const tax = normalizeString(customer.taxNumber);
|
|
249
|
+
if (tax)
|
|
250
|
+
add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));
|
|
251
|
+
|
|
252
|
+
return Array.from(new Set(candidates));
|
|
253
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
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.
|
|
6
|
+
|
|
7
|
+
// ── UBL document model + serializer ────────────────────────────────────
|
|
8
|
+
export * from "./ubl/constants";
|
|
9
|
+
export { serializeUblDocument } from "./ubl/serialize";
|
|
10
|
+
export type {
|
|
11
|
+
UblAddress,
|
|
12
|
+
UblAttachment,
|
|
13
|
+
UblCompanyId,
|
|
14
|
+
UblDocument,
|
|
15
|
+
UblEndpoint,
|
|
16
|
+
UblLine,
|
|
17
|
+
UblMonetaryTotal,
|
|
18
|
+
UblParty,
|
|
19
|
+
UblPeriod,
|
|
20
|
+
UblTaxCategory,
|
|
21
|
+
UblTaxSubtotal,
|
|
22
|
+
UblTaxTotal,
|
|
23
|
+
} from "./ubl/types";
|
|
24
|
+
|
|
25
|
+
// ── Party builders ─────────────────────────────────────────────────────
|
|
26
|
+
export {
|
|
27
|
+
buildCustomerParty,
|
|
28
|
+
buildSupplierParty,
|
|
29
|
+
type SupplierVatStatus,
|
|
30
|
+
type UblCustomer,
|
|
31
|
+
type UblSupplier,
|
|
32
|
+
} from "./party";
|
|
33
|
+
|
|
34
|
+
// ── Re-usable helpers ──────────────────────────────────────────────────
|
|
35
|
+
export { type AddressInput, normalizeAddress } from "./address";
|
|
36
|
+
export { buildPdfAttachment, sanitizeUblDocumentForAudit } from "./attachment";
|
|
37
|
+
export {
|
|
38
|
+
buildCompanyId,
|
|
39
|
+
type CustomerTaxIdentifiers,
|
|
40
|
+
type CustomerTaxIdInput,
|
|
41
|
+
extractCustomerTaxIdentifiers,
|
|
42
|
+
listPeppolReceiverIdentifierCandidates,
|
|
43
|
+
normalizeCompanyNumberForCountry,
|
|
44
|
+
parsePeppolEndpoint,
|
|
45
|
+
resolveCompanyIdScheme,
|
|
46
|
+
resolveVatEndpoint,
|
|
47
|
+
} from "./identifiers";
|
|
48
|
+
export {
|
|
49
|
+
centsToDecimal,
|
|
50
|
+
deriveUnitPrice,
|
|
51
|
+
roundCurrency,
|
|
52
|
+
type UnitPrice,
|
|
53
|
+
} from "./numeric";
|
|
54
|
+
export {
|
|
55
|
+
coerceLinesForSupplierVatStatus,
|
|
56
|
+
EXEMPT_TAXABILITY_REASONS,
|
|
57
|
+
resolveTaxCategoryFromTaxAmounts,
|
|
58
|
+
type TaxAmountInfo,
|
|
59
|
+
taxCategoryFromReasonOrRate,
|
|
60
|
+
} from "./tax-category";
|
|
61
|
+
export {
|
|
62
|
+
type BuildTaxTotalsOptions,
|
|
63
|
+
type BuildTaxTotalsResult,
|
|
64
|
+
buildTaxTotals,
|
|
65
|
+
reconcileLinesToExclTotal,
|
|
66
|
+
} from "./tax-totals";
|
|
67
|
+
|
|
68
|
+
// ── Low-level XML primitives ───────────────────────────────────────────
|
|
69
|
+
export { el, serializeDocument, type XmlAttrs, type XmlElement } from "./xml";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Round a number to 2 decimal places (cents). */
|
|
2
|
+
export const roundCurrency = (value: number) =>
|
|
3
|
+
Math.round((value + Number.EPSILON) * 100) / 100;
|
|
4
|
+
|
|
5
|
+
/** Convert an integer cent amount into a 2-decimal currency value. */
|
|
6
|
+
export const centsToDecimal = (cents: number) => roundCurrency(cents / 100);
|
|
7
|
+
|
|
8
|
+
/** The `cac:Price` pair for a line: BT-146 and the optional BT-149. */
|
|
9
|
+
export interface UnitPrice {
|
|
10
|
+
/** `cbc:PriceAmount` (BT-146). */
|
|
11
|
+
priceAmount: number;
|
|
12
|
+
/** `cbc:BaseQuantity` (BT-149) — the units `priceAmount` covers. Omitted = 1. */
|
|
13
|
+
baseQuantity?: number | undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Derive the `cac:Price` for a line whose net total is authoritative.
|
|
18
|
+
*
|
|
19
|
+
* Peppol rule PEPPOL-EN16931-R120 checks
|
|
20
|
+
* `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within
|
|
21
|
+
* a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that
|
|
22
|
+
* whenever the division doesn't land on a cent: 940.00 over 14 units gives
|
|
23
|
+
* 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and
|
|
24
|
+
* rejected as a fatal validation error.
|
|
25
|
+
*
|
|
26
|
+
* 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
|
+
*/
|
|
32
|
+
export const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {
|
|
33
|
+
// A zero or fractional-to-zero quantity still has to price something; BT-149
|
|
34
|
+
// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.
|
|
35
|
+
const units = quantity > 0 ? quantity : 1;
|
|
36
|
+
const perUnit = roundCurrency(netTotal / units);
|
|
37
|
+
if (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {
|
|
38
|
+
return { priceAmount: perUnit };
|
|
39
|
+
}
|
|
40
|
+
return { priceAmount: roundCurrency(netTotal), baseQuantity: units };
|
|
41
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { type AddressInput, normalizeAddress } from "./address";
|
|
2
|
+
import { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from "./identifiers";
|
|
3
|
+
import type { UblAddress, UblEndpoint, UblParty } from "./ubl/types";
|
|
4
|
+
import { normalizeString } from "./utils";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the
|
|
8
|
+
* seller does not charge VAT:
|
|
9
|
+
*
|
|
10
|
+
* - `subject` — subject to VAT (the normal case): line categories come from
|
|
11
|
+
* the data.
|
|
12
|
+
* - `not_subject` — not subject to VAT.
|
|
13
|
+
* - `small_business` — small business / franchise exemption (e.g. Belgian
|
|
14
|
+
* Article 56bis).
|
|
15
|
+
*
|
|
16
|
+
* For the last two, `coerceLinesForSupplierVatStatus` (tax-category.ts) turns
|
|
17
|
+
* every line into a non-charging exempt category so no VAT is reported.
|
|
18
|
+
* Providers that encode this numerically (Scrada: 1/2/3) map at their boundary.
|
|
19
|
+
*/
|
|
20
|
+
export type SupplierVatStatus = "subject" | "not_subject" | "small_business";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Caller-provided supplier data, normalized into a stable shape.
|
|
24
|
+
*
|
|
25
|
+
* Each consumer builds this from its own data store. Once a `UblSupplier`
|
|
26
|
+
* exists, the party builder no longer needs to know where it came from.
|
|
27
|
+
*/
|
|
28
|
+
export interface UblSupplier {
|
|
29
|
+
/** Display + legal name shown on the invoice. */
|
|
30
|
+
name: string;
|
|
31
|
+
/** ISO 3166-1 alpha-2 country code (e.g. `"BE"`). */
|
|
32
|
+
countryCode: string;
|
|
33
|
+
/**
|
|
34
|
+
* Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)
|
|
35
|
+
* and legacy/internal fields (`street`, `zip_code`) are both accepted.
|
|
36
|
+
*/
|
|
37
|
+
address: AddressInput | null;
|
|
38
|
+
/** Country-specific company/registration number (e.g. BE enterprise number). */
|
|
39
|
+
companyNumber?: string | null;
|
|
40
|
+
/** VAT number with country prefix (e.g. `"BE0793904121"`). */
|
|
41
|
+
vatNumber?: string | null;
|
|
42
|
+
/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */
|
|
43
|
+
vatStatus: SupplierVatStatus;
|
|
44
|
+
/** Peppol participant identifier in `scheme:value` form (e.g. `"0208:0793904121"`). */
|
|
45
|
+
peppolID?: string | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Convert a {@link UblSupplier} into the supplier (seller) party. */
|
|
49
|
+
export const buildSupplierParty = (supplier: UblSupplier): UblParty => {
|
|
50
|
+
const address = normalizeAddress(supplier.address, supplier.countryCode);
|
|
51
|
+
return {
|
|
52
|
+
endpoint: parsePeppolEndpoint(supplier.peppolID),
|
|
53
|
+
name: supplier.name,
|
|
54
|
+
address,
|
|
55
|
+
vatNumber: normalizeString(supplier.vatNumber),
|
|
56
|
+
legalName: supplier.name,
|
|
57
|
+
companyId: buildCompanyId({
|
|
58
|
+
countryCode: supplier.countryCode,
|
|
59
|
+
companyNumber: supplier.companyNumber ?? null,
|
|
60
|
+
}),
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Caller-provided customer (buyer) data, normalized into a stable shape.
|
|
66
|
+
*
|
|
67
|
+
* Each consumer (the Stripe adapter, app-specific row builders) resolves its
|
|
68
|
+
* own identifiers and address, then hands this generic shape to
|
|
69
|
+
* {@link buildCustomerParty}, so the Peppol routing logic lives in one place.
|
|
70
|
+
*/
|
|
71
|
+
export interface UblCustomer {
|
|
72
|
+
/** Display + legal name shown on the invoice. */
|
|
73
|
+
name: string;
|
|
74
|
+
/** Customer address, already normalized by the caller. */
|
|
75
|
+
address: UblAddress;
|
|
76
|
+
/**
|
|
77
|
+
* The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration
|
|
78
|
+
* schemes for identifiers that don't carry a country prefix. Pass the
|
|
79
|
+
* customer's *own* country (never the supplier's) so the document is not
|
|
80
|
+
* mis-routed; falls back to the address country when omitted.
|
|
81
|
+
*/
|
|
82
|
+
countryCode?: string | null;
|
|
83
|
+
/** Peppol participant identifier in `scheme:value` form (e.g. `"0208:0793904121"`). */
|
|
84
|
+
peppolID?: string | null;
|
|
85
|
+
/** Global Location Number (resolved under EAS `0088`). */
|
|
86
|
+
glnNumber?: string | null;
|
|
87
|
+
/** Generic tax/registration number (no VAT prefix). */
|
|
88
|
+
taxNumber?: string | null;
|
|
89
|
+
/** VAT number with country prefix (e.g. `"BE0793904121"`). */
|
|
90
|
+
vatNumber?: string | null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Convert a {@link UblCustomer} into the customer (buyer) party.
|
|
95
|
+
*
|
|
96
|
+
* The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
|
|
97
|
+
* priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
|
|
98
|
+
* identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the
|
|
99
|
+
* VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That
|
|
100
|
+
* last step matters because most data stores hold a customer's VAT without a
|
|
101
|
+
* scheme, so without it a VAT-only customer would have no endpoint and the
|
|
102
|
+
* document would be unroutable.
|
|
103
|
+
*/
|
|
104
|
+
export const buildCustomerParty = (
|
|
105
|
+
customer: UblCustomer,
|
|
106
|
+
endpointOverride?: UblEndpoint | null,
|
|
107
|
+
): UblParty => {
|
|
108
|
+
const countryCode =
|
|
109
|
+
normalizeString(customer.countryCode) ?? customer.address.countryCode;
|
|
110
|
+
const endpoint =
|
|
111
|
+
endpointOverride ??
|
|
112
|
+
parsePeppolEndpoint(customer.peppolID) ??
|
|
113
|
+
(customer.glnNumber ? { scheme: "0088", value: customer.glnNumber } : null) ??
|
|
114
|
+
resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
endpoint,
|
|
118
|
+
name: customer.name,
|
|
119
|
+
address: customer.address,
|
|
120
|
+
vatNumber: normalizeString(customer.vatNumber),
|
|
121
|
+
legalName: customer.name,
|
|
122
|
+
companyId: buildCompanyId({
|
|
123
|
+
countryCode,
|
|
124
|
+
companyNumber: customer.taxNumber ?? null,
|
|
125
|
+
}),
|
|
126
|
+
};
|
|
127
|
+
};
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { SupplierVatStatus } from "./party";
|
|
2
|
+
import type { UblLine, UblTaxCategory } from "./ubl/types";
|
|
3
|
+
import { normalizeString } from "./utils";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category
|
|
7
|
+
* (`E`). Reverse charge is handled separately (category `AE`).
|
|
8
|
+
*/
|
|
9
|
+
export const EXEMPT_TAXABILITY_REASONS = new Set([
|
|
10
|
+
"customer_exempt",
|
|
11
|
+
"product_exempt",
|
|
12
|
+
"not_subject_to_tax",
|
|
13
|
+
"not_collecting",
|
|
14
|
+
"not_supported",
|
|
15
|
+
"portion_product_exempt",
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */
|
|
19
|
+
const EXEMPTION_REASON_TEXT: Record<string, string> = {
|
|
20
|
+
reverse_charge: "Reverse charge",
|
|
21
|
+
intra_community: "Intra-community supply",
|
|
22
|
+
export: "Export outside the EU",
|
|
23
|
+
customer_exempt: "Exempt based on customer status",
|
|
24
|
+
product_exempt: "Exempt based on the supplied goods or services",
|
|
25
|
+
portion_product_exempt: "Exempt based on the supplied goods or services",
|
|
26
|
+
not_subject_to_tax: "Not subject to VAT",
|
|
27
|
+
not_collecting: "VAT not collected",
|
|
28
|
+
not_supported: "VAT not applicable",
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export interface TaxAmountInfo {
|
|
32
|
+
amount: number;
|
|
33
|
+
taxability_reason?: string | null;
|
|
34
|
+
tax_rate_percentage?: number | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const normalizeTaxCategoryId = (value: string | null | undefined): string | null =>
|
|
38
|
+
normalizeString(value)?.toUpperCase() ?? null;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
|
|
42
|
+
* numeric rate into a {@link UblTaxCategory}.
|
|
43
|
+
*
|
|
44
|
+
* - Reverse charge → `AE` (0%, with exemption reason)
|
|
45
|
+
* - Intra-community supply → `K` (0%, with exemption reason)
|
|
46
|
+
* - Export outside the EU → `G` (0%, with exemption reason)
|
|
47
|
+
* - Any other exempt reason → `E` (0%, with exemption reason)
|
|
48
|
+
* - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)
|
|
49
|
+
* - Otherwise → `S` (standard, the line's rate)
|
|
50
|
+
*/
|
|
51
|
+
export const taxCategoryFromReasonOrRate = (params: {
|
|
52
|
+
taxCategoryId?: string | null;
|
|
53
|
+
taxabilityReason: string | null;
|
|
54
|
+
rate: number;
|
|
55
|
+
}): UblTaxCategory => {
|
|
56
|
+
const categoryHint = normalizeTaxCategoryId(params.taxCategoryId);
|
|
57
|
+
const reason = params.taxabilityReason;
|
|
58
|
+
|
|
59
|
+
if (categoryHint === "AE" || reason === "reverse_charge") {
|
|
60
|
+
return {
|
|
61
|
+
id: "AE",
|
|
62
|
+
percent: 0,
|
|
63
|
+
exemptionReason: EXEMPTION_REASON_TEXT["reverse_charge"],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (categoryHint === "K" || reason === "intra_community") {
|
|
67
|
+
return {
|
|
68
|
+
id: "K",
|
|
69
|
+
percent: 0,
|
|
70
|
+
exemptionReason: EXEMPTION_REASON_TEXT["intra_community"],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
if (categoryHint === "G" || reason === "export") {
|
|
74
|
+
return {
|
|
75
|
+
id: "G",
|
|
76
|
+
percent: 0,
|
|
77
|
+
exemptionReason: EXEMPTION_REASON_TEXT["export"],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
if (categoryHint === "E" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {
|
|
81
|
+
return {
|
|
82
|
+
id: "E",
|
|
83
|
+
percent: 0,
|
|
84
|
+
exemptionReason:
|
|
85
|
+
(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT",
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) {
|
|
89
|
+
return { id: "Z", percent: 0 };
|
|
90
|
+
}
|
|
91
|
+
return { id: "S", percent: params.rate };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Resolve a {@link UblTaxCategory} from a line's Stripe tax info.
|
|
96
|
+
*
|
|
97
|
+
* Exempt / reverse-charge / zero-rated reasons take precedence over the rate;
|
|
98
|
+
* otherwise the rate decides standard (`S`) vs zero-rated (`Z`).
|
|
99
|
+
*/
|
|
100
|
+
export const resolveTaxCategoryFromTaxAmounts = (
|
|
101
|
+
taxAmounts: TaxAmountInfo[],
|
|
102
|
+
rate: number,
|
|
103
|
+
): UblTaxCategory => {
|
|
104
|
+
for (const ta of taxAmounts) {
|
|
105
|
+
if (!ta.taxability_reason) continue;
|
|
106
|
+
if (
|
|
107
|
+
ta.taxability_reason === "reverse_charge" ||
|
|
108
|
+
ta.taxability_reason === "zero_rated" ||
|
|
109
|
+
EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)
|
|
110
|
+
) {
|
|
111
|
+
return taxCategoryFromReasonOrRate({
|
|
112
|
+
taxabilityReason: ta.taxability_reason,
|
|
113
|
+
rate,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* BT-120 text for a small-business/franchise exemption, by supplier country.
|
|
122
|
+
* Countries without a specific legal reference fall back to the generic text.
|
|
123
|
+
*/
|
|
124
|
+
const SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY: Record<string, string> = {
|
|
125
|
+
BE: "Exempt — small business scheme (Article 56bis)",
|
|
126
|
+
};
|
|
127
|
+
const SMALL_BUSINESS_EXEMPTION_REASON = "Exempt — small business scheme";
|
|
128
|
+
const NOT_SUBJECT_EXEMPTION_REASON = "Seller not subject to VAT";
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* When the supplier does not charge VAT, coerce every line to a non-charging
|
|
132
|
+
* exempt category (`E`, 0%) with the appropriate BT-120 reason, so the document
|
|
133
|
+
* reports no VAT regardless of what the upstream line tax data implied. Lines
|
|
134
|
+
* are returned untouched for a `subject` supplier.
|
|
135
|
+
*/
|
|
136
|
+
export const coerceLinesForSupplierVatStatus = (
|
|
137
|
+
lines: UblLine[],
|
|
138
|
+
vatStatus: SupplierVatStatus,
|
|
139
|
+
supplierCountryCode?: string | null,
|
|
140
|
+
): UblLine[] => {
|
|
141
|
+
if (vatStatus === "subject") return lines;
|
|
142
|
+
const country = normalizeString(supplierCountryCode)?.toUpperCase();
|
|
143
|
+
const exemptionReason =
|
|
144
|
+
vatStatus === "small_business"
|
|
145
|
+
? ((country && SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY[country]) ??
|
|
146
|
+
SMALL_BUSINESS_EXEMPTION_REASON)
|
|
147
|
+
: NOT_SUBJECT_EXEMPTION_REASON;
|
|
148
|
+
return lines.map((line) => ({
|
|
149
|
+
...line,
|
|
150
|
+
taxCategory: { id: "E", percent: 0, exemptionReason },
|
|
151
|
+
}));
|
|
152
|
+
};
|