@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.
- package/CHANGELOG.md +20 -0
- package/README.md +67 -26
- package/dist/build/index.d.ts +79 -193
- package/dist/build/index.d.ts.map +1 -1
- package/dist/build/index.js +525 -136
- package/dist/build/index.js.map +1 -1
- package/dist/errors-C9YYJ1xR.js +33 -0
- package/dist/errors-C9YYJ1xR.js.map +1 -0
- package/dist/index.d.ts +2 -224
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +192 -73
- package/dist/index.js.map +1 -1
- package/dist/types-DpwX8-Ix.d.ts +462 -0
- package/dist/types-DpwX8-Ix.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/build/address.ts +9 -10
- package/src/build/attachment.ts +13 -9
- package/src/build/identifiers.ts +28 -28
- package/src/build/index.ts +30 -9
- package/src/build/numeric.ts +17 -11
- package/src/build/party.ts +16 -14
- package/src/build/tax-category.ts +5 -4
- package/src/build/tax-totals.ts +129 -22
- package/src/build/ubl/serialize.ts +894 -134
- package/src/build/utils.ts +12 -4
- package/src/errors.ts +16 -0
- package/src/index.ts +5 -1
- package/src/normalize.ts +24 -18
- package/src/parser.ts +246 -48
- package/src/types.ts +263 -23
- package/src/build/ubl/types.ts +0 -179
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
import { UblBuildError } from "../../errors";
|
|
2
|
+
import type {
|
|
3
|
+
UblAddress,
|
|
4
|
+
UblAllowanceCharge,
|
|
5
|
+
UblAttachment,
|
|
6
|
+
UblBillingReference,
|
|
7
|
+
UblDelivery,
|
|
8
|
+
UblInvoice,
|
|
9
|
+
UblInvoicePeriod,
|
|
10
|
+
UblLine,
|
|
11
|
+
UblParty,
|
|
12
|
+
UblPaymentMeans,
|
|
13
|
+
UblSchemedId,
|
|
14
|
+
UblTaxCategory,
|
|
15
|
+
UblTaxSubtotal,
|
|
16
|
+
} from "../../types";
|
|
1
17
|
import { el, serializeDocument, type XmlElement } from "../xml";
|
|
2
18
|
import {
|
|
3
19
|
COUNTRY_CODE_LIST_ID,
|
|
@@ -11,16 +27,340 @@ import {
|
|
|
11
27
|
UBL_PROFILE_ID,
|
|
12
28
|
VAT_TAX_SCHEME_ID,
|
|
13
29
|
} from "./constants";
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
30
|
+
|
|
31
|
+
// ── Validation ─────────────────────────────────────────────────────────
|
|
32
|
+
//
|
|
33
|
+
// The model is permissive (the parser reads whatever a document states); the
|
|
34
|
+
// serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields and
|
|
35
|
+
// the arithmetic business rules are enforced. Each check names the BT or the
|
|
36
|
+
// rule and the model path in its message.
|
|
37
|
+
|
|
38
|
+
const missing = (what: string, path: string): UblBuildError =>
|
|
39
|
+
new UblBuildError(`Missing ${what} (${path})`);
|
|
40
|
+
|
|
41
|
+
function required<T>(value: T | undefined, what: string, path: string): NonNullable<T> {
|
|
42
|
+
if (value === undefined || value === null || value === "") {
|
|
43
|
+
throw missing(what, path);
|
|
44
|
+
}
|
|
45
|
+
return value as NonNullable<T>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const round2 = (value: number): number => Math.round(value * 100) / 100;
|
|
49
|
+
|
|
50
|
+
/** Sums of cent-rounded amounts must agree to the cent; R120 allows a cent either way. */
|
|
51
|
+
const assertEqual = (
|
|
52
|
+
rule: string,
|
|
53
|
+
actual: number,
|
|
54
|
+
expected: number,
|
|
55
|
+
path: string,
|
|
56
|
+
tolerance = 0.005,
|
|
57
|
+
): void => {
|
|
58
|
+
if (Math.abs(actual - expected) > tolerance) {
|
|
59
|
+
throw new UblBuildError(
|
|
60
|
+
`${rule}: ${path} is ${actual.toFixed(2)}, expected ${expected.toFixed(2)}`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */
|
|
66
|
+
const requiresPercent = (categoryId: string): boolean => categoryId !== "O";
|
|
67
|
+
|
|
68
|
+
const validateTaxCategory = (
|
|
69
|
+
category: UblTaxCategory | undefined,
|
|
70
|
+
path: string,
|
|
71
|
+
): UblTaxCategory & { id: string } => {
|
|
72
|
+
const present = required(category, "VAT category (BT-151/BT-118)", path);
|
|
73
|
+
const id = required(present.id, "VAT category code (BT-151/BT-118)", `${path}.id`);
|
|
74
|
+
if (requiresPercent(id) && present.percent === undefined) {
|
|
75
|
+
throw missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);
|
|
76
|
+
}
|
|
77
|
+
return { ...present, id };
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const validateAllowanceCharge = (
|
|
81
|
+
item: UblAllowanceCharge,
|
|
82
|
+
path: string,
|
|
83
|
+
level: "document" | "line",
|
|
84
|
+
): void => {
|
|
85
|
+
const kind = item.chargeIndicator ? "charge" : "allowance";
|
|
86
|
+
required(item.amount, `${kind} amount (BT-92/BT-99)`, `${path}.amount`);
|
|
87
|
+
if (item.reason === undefined && item.reasonCode === undefined) {
|
|
88
|
+
throw missing(`${kind} reason or reason code (BT-97/BT-98)`, `${path}.reason`);
|
|
89
|
+
}
|
|
90
|
+
if (item.baseAmount !== undefined && item.multiplierFactorNumeric !== undefined) {
|
|
91
|
+
assertEqual(
|
|
92
|
+
"PEPPOL-EN16931-R040",
|
|
93
|
+
item.amount ?? 0,
|
|
94
|
+
round2((item.baseAmount * item.multiplierFactorNumeric) / 100),
|
|
95
|
+
`${path}.amount`,
|
|
96
|
+
0.01,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (level === "document") {
|
|
100
|
+
validateTaxCategory(item.taxCategory, `${path}.taxCategory`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const lineAllowanceTotal = (line: UblLine, charges: boolean): number =>
|
|
105
|
+
(line.allowanceCharges ?? [])
|
|
106
|
+
.filter((item) => item.chargeIndicator === charges)
|
|
107
|
+
.reduce((sum, item) => sum + (item.amount ?? 0), 0);
|
|
108
|
+
|
|
109
|
+
const validateLine = (line: UblLine, index: number): void => {
|
|
110
|
+
const path = `lines[${index}]`;
|
|
111
|
+
required(line.id, "line identifier (BT-126)", `${path}.id`);
|
|
112
|
+
const quantity = required(
|
|
113
|
+
line.quantity,
|
|
114
|
+
"invoiced quantity (BT-129)",
|
|
115
|
+
`${path}.quantity`,
|
|
116
|
+
);
|
|
117
|
+
required(line.unitCode, "unit code (BT-130)", `${path}.unitCode`);
|
|
118
|
+
const unitPrice = required(
|
|
119
|
+
line.unitPrice,
|
|
120
|
+
"net unit price (BT-146)",
|
|
121
|
+
`${path}.unitPrice`,
|
|
122
|
+
);
|
|
123
|
+
const net = required(
|
|
124
|
+
line.lineExtensionAmount,
|
|
125
|
+
"line net amount (BT-131)",
|
|
126
|
+
`${path}.lineExtensionAmount`,
|
|
127
|
+
);
|
|
128
|
+
validateTaxCategory(line.taxCategory, `${path}.taxCategory`);
|
|
129
|
+
(line.allowanceCharges ?? []).forEach((item, itemIndex) =>
|
|
130
|
+
validateAllowanceCharge(item, `${path}.allowanceCharges[${itemIndex}]`, "line"),
|
|
131
|
+
);
|
|
132
|
+
// BT-131 = BT-129 × BT-146 + line charges − line allowances. `unitPrice` is
|
|
133
|
+
// the per-unit figure, so BT-149 is already accounted for.
|
|
134
|
+
assertEqual(
|
|
135
|
+
"PEPPOL-EN16931-R120",
|
|
136
|
+
net,
|
|
137
|
+
round2(
|
|
138
|
+
quantity * unitPrice +
|
|
139
|
+
lineAllowanceTotal(line, true) -
|
|
140
|
+
lineAllowanceTotal(line, false),
|
|
141
|
+
),
|
|
142
|
+
`${path}.lineExtensionAmount`,
|
|
143
|
+
0.02,
|
|
144
|
+
);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const isExternalOnly = (attachment: UblAttachment): boolean =>
|
|
148
|
+
attachment.externalUri !== undefined && attachment.base64Content === undefined;
|
|
149
|
+
|
|
150
|
+
const validateAttachment = (attachment: UblAttachment, index: number): void => {
|
|
151
|
+
if (isExternalOnly(attachment)) return;
|
|
152
|
+
const path = `attachments[${index}]`;
|
|
153
|
+
required(attachment.filename, "attachment filename (BT-125-2)", `${path}.filename`);
|
|
154
|
+
required(
|
|
155
|
+
attachment.mimeCode,
|
|
156
|
+
"attachment MIME code (BT-125-1)",
|
|
157
|
+
`${path}.mimeCode`,
|
|
158
|
+
);
|
|
159
|
+
required(
|
|
160
|
+
attachment.base64Content,
|
|
161
|
+
"attachment content (BT-125)",
|
|
162
|
+
`${path}.base64Content`,
|
|
163
|
+
);
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/** UNCL4461 codes whose payment means need a mandate (direct debit) or an account (credit transfer). */
|
|
167
|
+
const DIRECT_DEBIT_CODES = new Set(["49", "59"]);
|
|
168
|
+
const CREDIT_TRANSFER_CODES = new Set(["30", "58"]);
|
|
169
|
+
|
|
170
|
+
const validatePaymentMeans = (means: UblPaymentMeans, index: number): void => {
|
|
171
|
+
const path = `paymentMeansList[${index}]`;
|
|
172
|
+
const code = required(means.code, "payment means code (BT-81)", `${path}.code`);
|
|
173
|
+
if (CREDIT_TRANSFER_CODES.has(code)) {
|
|
174
|
+
required(
|
|
175
|
+
means.iban,
|
|
176
|
+
`payment account (BT-84) for code ${code}`,
|
|
177
|
+
`${path}.iban`,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
if (DIRECT_DEBIT_CODES.has(code)) {
|
|
181
|
+
required(
|
|
182
|
+
means.mandateId,
|
|
183
|
+
`mandate reference (BT-89) for code ${code}`,
|
|
184
|
+
`${path}.mandateId`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const validateParty = (party: UblParty, role: string, nameBt: string): void => {
|
|
190
|
+
required(party.name, `${role} name (${nameBt})`, `${role}.name`);
|
|
191
|
+
if (party.endpoint && party.endpoint.scheme === undefined) {
|
|
192
|
+
throw missing(`${role} endpoint scheme`, `${role}.endpoint.scheme`);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const paymentMeansList = (doc: UblInvoice): UblPaymentMeans[] =>
|
|
197
|
+
doc.paymentMeansList ?? (doc.paymentMeans ? [doc.paymentMeans] : []);
|
|
198
|
+
|
|
199
|
+
const sumBy = <T>(items: T[], pick: (item: T) => number): number =>
|
|
200
|
+
round2(items.reduce((sum, item) => sum + pick(item), 0));
|
|
201
|
+
|
|
202
|
+
const categoryKey = (category: UblTaxCategory | undefined): string =>
|
|
203
|
+
`${category?.id ?? ""}:${category?.percent ?? ""}`;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The document arithmetic EN 16931 fixes: BR-CO-10 (line sum), BR-CO-11/12
|
|
207
|
+
* (allowance and charge sums), BR-CO-13 (total without VAT), BR-CO-15 (total
|
|
208
|
+
* with VAT), BR-CO-16 (amount due) and the BR-S-08 family (each VAT category's
|
|
209
|
+
* taxable amount is its line nets minus its allowances plus its charges).
|
|
210
|
+
*/
|
|
211
|
+
const validateArithmetic = (doc: UblInvoice): void => {
|
|
212
|
+
const total = doc.monetaryTotal;
|
|
213
|
+
const docItems = doc.allowanceCharges ?? [];
|
|
214
|
+
const allowances = docItems.filter((item) => !item.chargeIndicator);
|
|
215
|
+
const charges = docItems.filter((item) => item.chargeIndicator);
|
|
216
|
+
const lineSum = sumBy(doc.lines, (line) => line.lineExtensionAmount ?? 0);
|
|
217
|
+
const allowanceSum = sumBy(allowances, (item) => item.amount ?? 0);
|
|
218
|
+
const chargeSum = sumBy(charges, (item) => item.amount ?? 0);
|
|
219
|
+
|
|
220
|
+
assertEqual(
|
|
221
|
+
"BR-CO-10",
|
|
222
|
+
total.lineExtensionAmount ?? 0,
|
|
223
|
+
lineSum,
|
|
224
|
+
"monetaryTotal.lineExtensionAmount",
|
|
225
|
+
);
|
|
226
|
+
if (allowances.length > 0 || total.allowanceTotalAmount !== undefined) {
|
|
227
|
+
assertEqual(
|
|
228
|
+
"BR-CO-11",
|
|
229
|
+
total.allowanceTotalAmount ?? 0,
|
|
230
|
+
allowanceSum,
|
|
231
|
+
"monetaryTotal.allowanceTotalAmount",
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
if (charges.length > 0 || total.chargeTotalAmount !== undefined) {
|
|
235
|
+
assertEqual(
|
|
236
|
+
"BR-CO-12",
|
|
237
|
+
total.chargeTotalAmount ?? 0,
|
|
238
|
+
chargeSum,
|
|
239
|
+
"monetaryTotal.chargeTotalAmount",
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
assertEqual(
|
|
243
|
+
"BR-CO-13",
|
|
244
|
+
total.taxExclusiveAmount ?? 0,
|
|
245
|
+
round2(lineSum - allowanceSum + chargeSum),
|
|
246
|
+
"monetaryTotal.taxExclusiveAmount",
|
|
247
|
+
);
|
|
248
|
+
assertEqual(
|
|
249
|
+
"BR-CO-15",
|
|
250
|
+
total.taxInclusiveAmount ?? 0,
|
|
251
|
+
round2((total.taxExclusiveAmount ?? 0) + (doc.taxTotal.taxAmount ?? 0)),
|
|
252
|
+
"monetaryTotal.taxInclusiveAmount",
|
|
253
|
+
);
|
|
254
|
+
assertEqual(
|
|
255
|
+
"BR-CO-16",
|
|
256
|
+
total.payableAmount ?? 0,
|
|
257
|
+
round2(
|
|
258
|
+
(total.taxInclusiveAmount ?? 0) -
|
|
259
|
+
(total.prepaidAmount ?? 0) +
|
|
260
|
+
(total.payableRoundingAmount ?? 0),
|
|
261
|
+
),
|
|
262
|
+
"monetaryTotal.payableAmount",
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
const taxableByCategory = new Map<string, number>();
|
|
266
|
+
const add = (category: UblTaxCategory | undefined, amount: number): void => {
|
|
267
|
+
const key = categoryKey(category);
|
|
268
|
+
taxableByCategory.set(key, round2((taxableByCategory.get(key) ?? 0) + amount));
|
|
269
|
+
};
|
|
270
|
+
for (const line of doc.lines) add(line.taxCategory, line.lineExtensionAmount ?? 0);
|
|
271
|
+
for (const item of docItems) {
|
|
272
|
+
add(
|
|
273
|
+
item.taxCategory,
|
|
274
|
+
item.chargeIndicator ? (item.amount ?? 0) : -(item.amount ?? 0),
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
doc.taxTotal.subtotals.forEach((subtotal, index) => {
|
|
278
|
+
const key = categoryKey(subtotal.category);
|
|
279
|
+
const expected = taxableByCategory.get(key);
|
|
280
|
+
if (expected === undefined) {
|
|
281
|
+
throw new UblBuildError(
|
|
282
|
+
`BR-S-08: taxTotal.subtotals[${index}] (${key}) has no line, allowance or charge in that category`,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
assertEqual(
|
|
286
|
+
"BR-S-08",
|
|
287
|
+
subtotal.taxableAmount ?? 0,
|
|
288
|
+
expected,
|
|
289
|
+
`taxTotal.subtotals[${index}].taxableAmount`,
|
|
290
|
+
);
|
|
291
|
+
});
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const validateInvoice = (doc: UblInvoice): void => {
|
|
295
|
+
required(doc.id, "document identifier (BT-1)", "id");
|
|
296
|
+
required(doc.issueDate, "issue date (BT-2)", "issueDate");
|
|
297
|
+
required(doc.currency, "document currency (BT-5)", "currency");
|
|
298
|
+
if (
|
|
299
|
+
doc.taxPointDate !== undefined &&
|
|
300
|
+
doc.invoicePeriod?.descriptionCode !== undefined
|
|
301
|
+
) {
|
|
302
|
+
throw new UblBuildError(
|
|
303
|
+
"BR-CO-3: a tax point date (BT-7, taxPointDate) and a tax point date code (BT-8, invoicePeriod.descriptionCode) are mutually exclusive",
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
if (doc.taxCurrency !== undefined) {
|
|
307
|
+
required(
|
|
308
|
+
doc.taxTotal.taxAmountInTaxCurrency,
|
|
309
|
+
"VAT total in the accounting currency (BT-111, BR-53)",
|
|
310
|
+
"taxTotal.taxAmountInTaxCurrency",
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
validateParty(doc.seller, "seller", "BT-27");
|
|
314
|
+
validateParty(doc.buyer, "buyer", "BT-44");
|
|
315
|
+
if (doc.payee) required(doc.payee.name, "payee name (BT-59)", "payee.name");
|
|
316
|
+
if (doc.taxRepresentative) {
|
|
317
|
+
required(
|
|
318
|
+
doc.taxRepresentative.name,
|
|
319
|
+
"tax representative name (BT-62)",
|
|
320
|
+
"taxRepresentative.name",
|
|
321
|
+
);
|
|
322
|
+
required(
|
|
323
|
+
doc.taxRepresentative.vatId,
|
|
324
|
+
"tax representative VAT identifier (BT-63)",
|
|
325
|
+
"taxRepresentative.vatId",
|
|
326
|
+
);
|
|
327
|
+
required(
|
|
328
|
+
doc.taxRepresentative.address?.countryCode,
|
|
329
|
+
"tax representative country (BT-69)",
|
|
330
|
+
"taxRepresentative.address.countryCode",
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
if (doc.lines.length === 0) {
|
|
334
|
+
throw new UblBuildError("A document needs at least one line (BG-25, lines)");
|
|
335
|
+
}
|
|
336
|
+
doc.lines.forEach(validateLine);
|
|
337
|
+
(doc.allowanceCharges ?? []).forEach((item, index) =>
|
|
338
|
+
validateAllowanceCharge(item, `allowanceCharges[${index}]`, "document"),
|
|
339
|
+
);
|
|
340
|
+
paymentMeansList(doc).forEach(validatePaymentMeans);
|
|
341
|
+
required(doc.taxTotal.taxAmount, "total VAT amount (BT-110)", "taxTotal.taxAmount");
|
|
342
|
+
const total = doc.monetaryTotal;
|
|
343
|
+
required(
|
|
344
|
+
total.lineExtensionAmount,
|
|
345
|
+
"sum of line net amounts (BT-106)",
|
|
346
|
+
"monetaryTotal.lineExtensionAmount",
|
|
347
|
+
);
|
|
348
|
+
required(
|
|
349
|
+
total.taxExclusiveAmount,
|
|
350
|
+
"total without VAT (BT-109)",
|
|
351
|
+
"monetaryTotal.taxExclusiveAmount",
|
|
352
|
+
);
|
|
353
|
+
required(
|
|
354
|
+
total.taxInclusiveAmount,
|
|
355
|
+
"total with VAT (BT-112)",
|
|
356
|
+
"monetaryTotal.taxInclusiveAmount",
|
|
357
|
+
);
|
|
358
|
+
required(total.payableAmount, "amount due (BT-115)", "monetaryTotal.payableAmount");
|
|
359
|
+
(doc.attachments ?? []).forEach(validateAttachment);
|
|
360
|
+
validateArithmetic(doc);
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// ── Formatting ─────────────────────────────────────────────────────────
|
|
24
364
|
|
|
25
365
|
/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */
|
|
26
366
|
const amount = (value: number): string => value.toFixed(2);
|
|
@@ -34,151 +374,448 @@ const percent = (value: number): string => {
|
|
|
34
374
|
const money = (name: string, value: number, currency: string): XmlElement =>
|
|
35
375
|
el(name, { currencyID: currency }, amount(value));
|
|
36
376
|
|
|
37
|
-
const
|
|
38
|
-
|
|
377
|
+
const optionalMoney = (
|
|
378
|
+
name: string,
|
|
379
|
+
value: number | undefined,
|
|
380
|
+
currency: string,
|
|
381
|
+
): XmlElement | null => (value !== undefined ? money(name, value, currency) : null);
|
|
382
|
+
|
|
383
|
+
const text = (name: string, value: string | undefined): XmlElement | null =>
|
|
384
|
+
value !== undefined ? el(name, null, value) : null;
|
|
385
|
+
|
|
386
|
+
const schemedId = (name: string, id: UblSchemedId | undefined): XmlElement | null =>
|
|
387
|
+
id !== undefined
|
|
388
|
+
? el(name, id.scheme !== undefined ? { schemeID: id.scheme } : null, id.value)
|
|
389
|
+
: null;
|
|
390
|
+
|
|
391
|
+
const taxScheme = (schemeId: string | undefined): XmlElement =>
|
|
392
|
+
el("cac:TaxScheme", null, [el("cbc:ID", null, schemeId ?? VAT_TAX_SCHEME_ID)]);
|
|
39
393
|
|
|
40
394
|
/**
|
|
41
395
|
* Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)
|
|
42
|
-
* and `cac:TaxCategory` (in the VAT breakdown
|
|
43
|
-
* reason for the non-charging
|
|
396
|
+
* and `cac:TaxCategory` (in the VAT breakdown and on document allowances and
|
|
397
|
+
* charges). EN 16931 requires an exemption reason for the non-charging
|
|
398
|
+
* categories (E/AE/O/K/G); the code precedes the text in the sequence.
|
|
44
399
|
*/
|
|
45
|
-
const taxCategory = (
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
400
|
+
const taxCategory = (
|
|
401
|
+
name: string,
|
|
402
|
+
category: UblTaxCategory,
|
|
403
|
+
path: string,
|
|
404
|
+
): XmlElement => {
|
|
405
|
+
const valid = validateTaxCategory(category, path);
|
|
406
|
+
return el(name, null, [
|
|
407
|
+
el("cbc:ID", null, valid.id),
|
|
408
|
+
valid.percent !== undefined
|
|
409
|
+
? el("cbc:Percent", null, percent(valid.percent))
|
|
51
410
|
: null,
|
|
52
|
-
|
|
411
|
+
text("cbc:TaxExemptionReasonCode", valid.exemptionReasonCode),
|
|
412
|
+
text("cbc:TaxExemptionReason", valid.exemptionReason),
|
|
413
|
+
taxScheme(valid.schemeId),
|
|
53
414
|
]);
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
const addressChildren = (address: UblAddress): (XmlElement | null)[] => [
|
|
418
|
+
text("cbc:StreetName", address.street),
|
|
419
|
+
text("cbc:AdditionalStreetName", address.additionalStreet),
|
|
420
|
+
text("cbc:CityName", address.city),
|
|
421
|
+
text("cbc:PostalZone", address.postalZone),
|
|
422
|
+
text("cbc:CountrySubentity", address.countrySubentity),
|
|
423
|
+
address.countryCode !== undefined
|
|
424
|
+
? el("cac:Country", null, [
|
|
425
|
+
el(
|
|
426
|
+
"cbc:IdentificationCode",
|
|
427
|
+
{ listID: COUNTRY_CODE_LIST_ID },
|
|
428
|
+
address.countryCode,
|
|
429
|
+
),
|
|
430
|
+
])
|
|
431
|
+
: null,
|
|
432
|
+
];
|
|
54
433
|
|
|
55
434
|
const postalAddress = (address: UblAddress): XmlElement =>
|
|
56
|
-
el("cac:PostalAddress", null,
|
|
57
|
-
address.street ? el("cbc:StreetName", null, address.street) : null,
|
|
58
|
-
address.additionalStreet
|
|
59
|
-
? el("cbc:AdditionalStreetName", null, address.additionalStreet)
|
|
60
|
-
: null,
|
|
61
|
-
address.city ? el("cbc:CityName", null, address.city) : null,
|
|
62
|
-
address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
|
|
63
|
-
address.countrySubentity
|
|
64
|
-
? el("cbc:CountrySubentity", null, address.countrySubentity)
|
|
65
|
-
: null,
|
|
66
|
-
address.countryCode
|
|
67
|
-
? el("cac:Country", null, [
|
|
68
|
-
el(
|
|
69
|
-
"cbc:IdentificationCode",
|
|
70
|
-
{ listID: COUNTRY_CODE_LIST_ID },
|
|
71
|
-
address.countryCode,
|
|
72
|
-
),
|
|
73
|
-
])
|
|
74
|
-
: null,
|
|
75
|
-
]);
|
|
435
|
+
el("cac:PostalAddress", null, addressChildren(address));
|
|
76
436
|
|
|
77
|
-
const
|
|
437
|
+
const partyIdentifications = (source: UblParty): XmlElement[] =>
|
|
438
|
+
(source.partyIdentifications ?? []).map((identification) =>
|
|
439
|
+
el("cac:PartyIdentification", null, [
|
|
440
|
+
el(
|
|
441
|
+
"cbc:ID",
|
|
442
|
+
identification.schemeId !== undefined
|
|
443
|
+
? { schemeID: identification.schemeId }
|
|
444
|
+
: null,
|
|
445
|
+
identification.id,
|
|
446
|
+
),
|
|
447
|
+
]),
|
|
448
|
+
);
|
|
449
|
+
|
|
450
|
+
const partyName = (name: string): XmlElement =>
|
|
451
|
+
el("cac:PartyName", null, [el("cbc:Name", null, name)]);
|
|
452
|
+
|
|
453
|
+
const partyTaxScheme = (source: UblParty): XmlElement | null =>
|
|
454
|
+
source.vatId !== undefined
|
|
455
|
+
? el("cac:PartyTaxScheme", null, [
|
|
456
|
+
el("cbc:CompanyID", null, source.vatId),
|
|
457
|
+
taxScheme(source.taxSchemeId),
|
|
458
|
+
])
|
|
459
|
+
: null;
|
|
460
|
+
|
|
461
|
+
const companyId = (source: UblParty): XmlElement | null =>
|
|
462
|
+
source.companyId
|
|
463
|
+
? el(
|
|
464
|
+
"cbc:CompanyID",
|
|
465
|
+
source.companyId.scheme !== undefined
|
|
466
|
+
? { schemeID: source.companyId.scheme }
|
|
467
|
+
: null,
|
|
468
|
+
source.companyId.value,
|
|
469
|
+
)
|
|
470
|
+
: null;
|
|
471
|
+
|
|
472
|
+
const contact = (source: UblParty): XmlElement | null =>
|
|
473
|
+
source.contact
|
|
474
|
+
? el("cac:Contact", null, [
|
|
475
|
+
text("cbc:Name", source.contact.name),
|
|
476
|
+
text("cbc:Telephone", source.contact.phone),
|
|
477
|
+
text("cbc:ElectronicMail", source.contact.email),
|
|
478
|
+
])
|
|
479
|
+
: null;
|
|
480
|
+
|
|
481
|
+
/** `cac:Party` for the seller and buyer (BG-4, BG-7). */
|
|
482
|
+
const party = (source: UblParty, name: string): XmlElement =>
|
|
78
483
|
el("cac:Party", null, [
|
|
79
484
|
source.endpoint
|
|
80
485
|
? el(
|
|
81
486
|
"cbc:EndpointID",
|
|
82
|
-
{ schemeID: source.endpoint.scheme },
|
|
487
|
+
{ schemeID: source.endpoint.scheme ?? "" },
|
|
83
488
|
source.endpoint.value,
|
|
84
489
|
)
|
|
85
490
|
: null,
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
source.
|
|
89
|
-
|
|
90
|
-
el("cbc:CompanyID", null, source.vatNumber),
|
|
91
|
-
vatTaxScheme(),
|
|
92
|
-
])
|
|
93
|
-
: null,
|
|
491
|
+
...partyIdentifications(source),
|
|
492
|
+
partyName(name),
|
|
493
|
+
source.address ? postalAddress(source.address) : null,
|
|
494
|
+
partyTaxScheme(source),
|
|
94
495
|
el("cac:PartyLegalEntity", null, [
|
|
95
|
-
el("cbc:RegistrationName", null, source.
|
|
96
|
-
source
|
|
97
|
-
|
|
98
|
-
"cbc:CompanyID",
|
|
99
|
-
source.companyId.scheme
|
|
100
|
-
? { schemeID: source.companyId.scheme }
|
|
101
|
-
: null,
|
|
102
|
-
source.companyId.value,
|
|
103
|
-
)
|
|
104
|
-
: null,
|
|
496
|
+
el("cbc:RegistrationName", null, source.registrationName ?? name),
|
|
497
|
+
companyId(source),
|
|
498
|
+
text("cbc:CompanyLegalForm", source.companyLegalForm),
|
|
105
499
|
]),
|
|
500
|
+
contact(source),
|
|
501
|
+
]);
|
|
502
|
+
|
|
503
|
+
/** `cac:PayeeParty` (BG-10): identification, name and legal entity id, unwrapped. */
|
|
504
|
+
const payeeParty = (source: UblParty): XmlElement =>
|
|
505
|
+
el("cac:PayeeParty", null, [
|
|
506
|
+
...partyIdentifications(source),
|
|
507
|
+
partyName(source.name ?? ""),
|
|
508
|
+
source.companyId ? el("cac:PartyLegalEntity", null, [companyId(source)]) : null,
|
|
509
|
+
]);
|
|
510
|
+
|
|
511
|
+
/** `cac:TaxRepresentativeParty` (BG-11): name, address and VAT id, unwrapped. */
|
|
512
|
+
const taxRepresentativeParty = (source: UblParty): XmlElement =>
|
|
513
|
+
el("cac:TaxRepresentativeParty", null, [
|
|
514
|
+
partyName(source.name ?? ""),
|
|
515
|
+
source.address ? postalAddress(source.address) : null,
|
|
516
|
+
partyTaxScheme(source),
|
|
106
517
|
]);
|
|
107
518
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
519
|
+
/** `cac:Delivery` (BG-13). */
|
|
520
|
+
const delivery = (source: UblDelivery): XmlElement | null => {
|
|
521
|
+
const location =
|
|
522
|
+
source.locationId !== undefined || source.address !== undefined
|
|
523
|
+
? el("cac:DeliveryLocation", null, [
|
|
524
|
+
schemedId("cbc:ID", source.locationId),
|
|
525
|
+
source.address
|
|
526
|
+
? el("cac:Address", null, addressChildren(source.address))
|
|
527
|
+
: null,
|
|
528
|
+
])
|
|
529
|
+
: null;
|
|
530
|
+
const deliveryParty =
|
|
531
|
+
source.partyName !== undefined
|
|
532
|
+
? el("cac:DeliveryParty", null, [partyName(source.partyName)])
|
|
533
|
+
: null;
|
|
534
|
+
if (source.actualDeliveryDate === undefined && !location && !deliveryParty)
|
|
535
|
+
return null;
|
|
536
|
+
return el("cac:Delivery", null, [
|
|
537
|
+
text("cbc:ActualDeliveryDate", source.actualDeliveryDate),
|
|
538
|
+
location,
|
|
539
|
+
deliveryParty,
|
|
540
|
+
]);
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* `cac:PaymentMeans` (BG-16). On a credit note BT-9 has no root element and
|
|
545
|
+
* rides in the first payment means as `cbc:PaymentDueDate`. `cbc:NetworkID`
|
|
546
|
+
* is schema-mandatory inside `cac:CardAccount` and carries no business term;
|
|
547
|
+
* the BIS example value is `NA`.
|
|
548
|
+
*/
|
|
549
|
+
const paymentMeans = (
|
|
550
|
+
source: UblPaymentMeans,
|
|
551
|
+
dueDate: string | undefined,
|
|
552
|
+
): XmlElement =>
|
|
553
|
+
el("cac:PaymentMeans", null, [
|
|
554
|
+
el(
|
|
555
|
+
"cbc:PaymentMeansCode",
|
|
556
|
+
source.codeName !== undefined ? { name: source.codeName } : null,
|
|
557
|
+
source.code ?? "",
|
|
558
|
+
),
|
|
559
|
+
text("cbc:PaymentDueDate", dueDate),
|
|
560
|
+
text("cbc:PaymentID", source.paymentId),
|
|
561
|
+
source.cardNumber !== undefined
|
|
562
|
+
? el("cac:CardAccount", null, [
|
|
563
|
+
el("cbc:PrimaryAccountNumberID", null, source.cardNumber),
|
|
564
|
+
el("cbc:NetworkID", null, "NA"),
|
|
565
|
+
text("cbc:HolderName", source.cardHolder),
|
|
566
|
+
])
|
|
567
|
+
: null,
|
|
568
|
+
source.iban !== undefined
|
|
569
|
+
? el("cac:PayeeFinancialAccount", null, [
|
|
570
|
+
el("cbc:ID", null, source.iban),
|
|
571
|
+
text("cbc:Name", source.accountName),
|
|
572
|
+
source.bic !== undefined
|
|
573
|
+
? el("cac:FinancialInstitutionBranch", null, [
|
|
574
|
+
el("cbc:ID", null, source.bic),
|
|
575
|
+
])
|
|
576
|
+
: null,
|
|
577
|
+
])
|
|
578
|
+
: null,
|
|
579
|
+
source.mandateId !== undefined
|
|
580
|
+
? el("cac:PaymentMandate", null, [
|
|
581
|
+
el("cbc:ID", null, source.mandateId),
|
|
582
|
+
source.debitedAccount !== undefined
|
|
583
|
+
? el("cac:PayerFinancialAccount", null, [
|
|
584
|
+
el("cbc:ID", null, source.debitedAccount),
|
|
585
|
+
])
|
|
586
|
+
: null,
|
|
587
|
+
])
|
|
588
|
+
: null,
|
|
113
589
|
]);
|
|
114
590
|
|
|
115
591
|
/**
|
|
116
|
-
* `cac:
|
|
117
|
-
*
|
|
118
|
-
*
|
|
592
|
+
* `cac:AllowanceCharge` at document level (BG-20/BG-21, with its VAT
|
|
593
|
+
* category) and line level (BG-27/BG-28, without: the line's category
|
|
594
|
+
* applies).
|
|
119
595
|
*/
|
|
120
|
-
const
|
|
596
|
+
const allowanceCharge = (
|
|
597
|
+
item: UblAllowanceCharge,
|
|
598
|
+
currency: string,
|
|
599
|
+
path: string,
|
|
600
|
+
level: "document" | "line",
|
|
601
|
+
): XmlElement =>
|
|
602
|
+
el("cac:AllowanceCharge", null, [
|
|
603
|
+
el("cbc:ChargeIndicator", null, item.chargeIndicator ? "true" : "false"),
|
|
604
|
+
text("cbc:AllowanceChargeReasonCode", item.reasonCode),
|
|
605
|
+
text("cbc:AllowanceChargeReason", item.reason),
|
|
606
|
+
item.multiplierFactorNumeric !== undefined
|
|
607
|
+
? el(
|
|
608
|
+
"cbc:MultiplierFactorNumeric",
|
|
609
|
+
null,
|
|
610
|
+
percent(item.multiplierFactorNumeric),
|
|
611
|
+
)
|
|
612
|
+
: null,
|
|
613
|
+
money("cbc:Amount", item.amount ?? 0, currency),
|
|
614
|
+
optionalMoney("cbc:BaseAmount", item.baseAmount, currency),
|
|
615
|
+
level === "document"
|
|
616
|
+
? taxCategory(
|
|
617
|
+
"cac:TaxCategory",
|
|
618
|
+
item.taxCategory ?? {},
|
|
619
|
+
`${path}.taxCategory`,
|
|
620
|
+
)
|
|
621
|
+
: null,
|
|
622
|
+
]);
|
|
623
|
+
|
|
624
|
+
const taxSubtotal = (
|
|
625
|
+
subtotal: UblTaxSubtotal,
|
|
626
|
+
currency: string,
|
|
627
|
+
index: number,
|
|
628
|
+
): XmlElement => {
|
|
629
|
+
const path = `taxTotal.subtotals[${index}]`;
|
|
630
|
+
return el("cac:TaxSubtotal", null, [
|
|
631
|
+
money(
|
|
632
|
+
"cbc:TaxableAmount",
|
|
633
|
+
required(
|
|
634
|
+
subtotal.taxableAmount,
|
|
635
|
+
"taxable amount (BT-116)",
|
|
636
|
+
`${path}.taxableAmount`,
|
|
637
|
+
),
|
|
638
|
+
currency,
|
|
639
|
+
),
|
|
640
|
+
money(
|
|
641
|
+
"cbc:TaxAmount",
|
|
642
|
+
required(subtotal.taxAmount, "VAT amount (BT-117)", `${path}.taxAmount`),
|
|
643
|
+
currency,
|
|
644
|
+
),
|
|
645
|
+
taxCategory(
|
|
646
|
+
"cac:TaxCategory",
|
|
647
|
+
required(subtotal.category, "VAT category (BT-118)", `${path}.category`),
|
|
648
|
+
`${path}.category`,
|
|
649
|
+
),
|
|
650
|
+
]);
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* `cac:LegalMonetaryTotal` children, in UBL sequence order. BT-107/BT-108 are
|
|
655
|
+
* written when the document carries allowances or charges; BT-113 and BT-114
|
|
656
|
+
* are omitted when absent or zero.
|
|
657
|
+
*/
|
|
658
|
+
const legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {
|
|
121
659
|
const { currency, monetaryTotal: total } = doc;
|
|
660
|
+
const hasAllowances = (doc.allowanceCharges ?? []).some(
|
|
661
|
+
(item) => !item.chargeIndicator,
|
|
662
|
+
);
|
|
663
|
+
const hasCharges = (doc.allowanceCharges ?? []).some(
|
|
664
|
+
(item) => item.chargeIndicator,
|
|
665
|
+
);
|
|
122
666
|
const children: (XmlElement | null)[] = [
|
|
123
|
-
money("cbc:LineExtensionAmount", total.lineExtensionAmount, currency),
|
|
124
|
-
money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount, currency),
|
|
125
|
-
money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount, currency),
|
|
667
|
+
money("cbc:LineExtensionAmount", total.lineExtensionAmount ?? 0, currency),
|
|
668
|
+
money("cbc:TaxExclusiveAmount", total.taxExclusiveAmount ?? 0, currency),
|
|
669
|
+
money("cbc:TaxInclusiveAmount", total.taxInclusiveAmount ?? 0, currency),
|
|
670
|
+
hasAllowances || total.allowanceTotalAmount
|
|
671
|
+
? money(
|
|
672
|
+
"cbc:AllowanceTotalAmount",
|
|
673
|
+
total.allowanceTotalAmount ?? 0,
|
|
674
|
+
currency,
|
|
675
|
+
)
|
|
676
|
+
: null,
|
|
677
|
+
hasCharges || total.chargeTotalAmount
|
|
678
|
+
? money("cbc:ChargeTotalAmount", total.chargeTotalAmount ?? 0, currency)
|
|
679
|
+
: null,
|
|
126
680
|
total.prepaidAmount
|
|
127
681
|
? money("cbc:PrepaidAmount", total.prepaidAmount, currency)
|
|
128
682
|
: null,
|
|
129
683
|
total.payableRoundingAmount
|
|
130
684
|
? money("cbc:PayableRoundingAmount", total.payableRoundingAmount, currency)
|
|
131
685
|
: null,
|
|
132
|
-
money("cbc:PayableAmount", total.payableAmount, currency),
|
|
686
|
+
money("cbc:PayableAmount", total.payableAmount ?? 0, currency),
|
|
133
687
|
];
|
|
134
688
|
return children.filter((child): child is XmlElement => Boolean(child));
|
|
135
689
|
};
|
|
136
690
|
|
|
137
691
|
/**
|
|
138
692
|
* `cac:InvoicePeriod`. Null when neither bound is set — an empty period element
|
|
139
|
-
* fails BR-CO-19, which requires at least one of the two dates.
|
|
693
|
+
* fails BR-CO-19, which requires at least one of the two dates. BT-8 (the tax
|
|
694
|
+
* point date code) is only meaningful on the document period.
|
|
140
695
|
*/
|
|
141
|
-
const invoicePeriod = (period:
|
|
142
|
-
if (!period || (
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
);
|
|
696
|
+
const invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {
|
|
697
|
+
if (!period || (period.startDate === undefined && period.endDate === undefined)) {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
return el("cac:InvoicePeriod", null, [
|
|
701
|
+
text("cbc:StartDate", period.startDate),
|
|
702
|
+
text("cbc:EndDate", period.endDate),
|
|
703
|
+
text("cbc:DescriptionCode", period.descriptionCode),
|
|
704
|
+
]);
|
|
151
705
|
};
|
|
152
706
|
|
|
707
|
+
const item = (source: UblLine): XmlElement =>
|
|
708
|
+
el("cac:Item", null, [
|
|
709
|
+
text("cbc:Description", source.description),
|
|
710
|
+
// BT-153 is mandatory; BT-154 stands in when the line has no name.
|
|
711
|
+
el("cbc:Name", null, source.itemName ?? source.description ?? source.id),
|
|
712
|
+
source.buyersItemId !== undefined
|
|
713
|
+
? el("cac:BuyersItemIdentification", null, [
|
|
714
|
+
el("cbc:ID", null, source.buyersItemId),
|
|
715
|
+
])
|
|
716
|
+
: null,
|
|
717
|
+
source.sellersItemId !== undefined
|
|
718
|
+
? el("cac:SellersItemIdentification", null, [
|
|
719
|
+
el("cbc:ID", null, source.sellersItemId),
|
|
720
|
+
])
|
|
721
|
+
: null,
|
|
722
|
+
source.standardItemId !== undefined
|
|
723
|
+
? el("cac:StandardItemIdentification", null, [
|
|
724
|
+
schemedId("cbc:ID", source.standardItemId),
|
|
725
|
+
])
|
|
726
|
+
: null,
|
|
727
|
+
source.originCountryCode !== undefined
|
|
728
|
+
? el("cac:OriginCountry", null, [
|
|
729
|
+
el("cbc:IdentificationCode", null, source.originCountryCode),
|
|
730
|
+
])
|
|
731
|
+
: null,
|
|
732
|
+
...(source.commodityClassifications ?? []).map((classification) =>
|
|
733
|
+
el("cac:CommodityClassification", null, [
|
|
734
|
+
el(
|
|
735
|
+
"cbc:ItemClassificationCode",
|
|
736
|
+
{
|
|
737
|
+
listID: classification.listId,
|
|
738
|
+
listVersionID: classification.listVersionId,
|
|
739
|
+
},
|
|
740
|
+
classification.value,
|
|
741
|
+
),
|
|
742
|
+
]),
|
|
743
|
+
),
|
|
744
|
+
taxCategory(
|
|
745
|
+
"cac:ClassifiedTaxCategory",
|
|
746
|
+
source.taxCategory ?? {},
|
|
747
|
+
`lines[${source.id}].taxCategory`,
|
|
748
|
+
),
|
|
749
|
+
...(source.additionalItemProperties ?? []).map((property) =>
|
|
750
|
+
el("cac:AdditionalItemProperty", null, [
|
|
751
|
+
el("cbc:Name", null, property.name),
|
|
752
|
+
el("cbc:Value", null, property.value ?? ""),
|
|
753
|
+
]),
|
|
754
|
+
),
|
|
755
|
+
]);
|
|
756
|
+
|
|
153
757
|
const line = (
|
|
154
758
|
source: UblLine,
|
|
155
759
|
currency: string,
|
|
156
|
-
documentType:
|
|
760
|
+
documentType: UblInvoice["documentType"],
|
|
157
761
|
): XmlElement => {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
const quantityElementName =
|
|
161
|
-
|
|
762
|
+
const isCreditNote = documentType === "CreditNote";
|
|
763
|
+
const lineElementName = isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine";
|
|
764
|
+
const quantityElementName = isCreditNote
|
|
765
|
+
? "cbc:CreditedQuantity"
|
|
766
|
+
: "cbc:InvoicedQuantity";
|
|
767
|
+
const unitCode = source.unitCode ?? "";
|
|
768
|
+
// BT-146 covers BT-149 units; the model holds the per-unit price.
|
|
769
|
+
const priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);
|
|
162
770
|
|
|
163
771
|
return el(lineElementName, null, [
|
|
164
772
|
el("cbc:ID", null, source.id),
|
|
165
|
-
|
|
166
|
-
|
|
773
|
+
text("cbc:Note", source.note),
|
|
774
|
+
el(quantityElementName, { unitCode }, String(source.quantity ?? 0)),
|
|
775
|
+
money("cbc:LineExtensionAmount", source.lineExtensionAmount ?? 0, currency),
|
|
776
|
+
text("cbc:AccountingCost", source.accountingCost),
|
|
167
777
|
invoicePeriod(source.invoicePeriod),
|
|
168
|
-
|
|
169
|
-
el("
|
|
170
|
-
|
|
171
|
-
|
|
778
|
+
source.orderLineReference !== undefined
|
|
779
|
+
? el("cac:OrderLineReference", null, [
|
|
780
|
+
el("cbc:LineID", null, source.orderLineReference),
|
|
781
|
+
])
|
|
782
|
+
: null,
|
|
783
|
+
source.objectIdentifier !== undefined
|
|
784
|
+
? el("cac:DocumentReference", null, [
|
|
785
|
+
schemedId("cbc:ID", source.objectIdentifier),
|
|
786
|
+
el("cbc:DocumentTypeCode", null, "130"),
|
|
787
|
+
])
|
|
788
|
+
: null,
|
|
789
|
+
...(source.allowanceCharges ?? []).map((entry, index) =>
|
|
790
|
+
allowanceCharge(
|
|
791
|
+
entry,
|
|
792
|
+
currency,
|
|
793
|
+
`lines[${source.id}].allowanceCharges[${index}]`,
|
|
794
|
+
"line",
|
|
795
|
+
),
|
|
796
|
+
),
|
|
797
|
+
item(source),
|
|
172
798
|
// BT-149's unit code must match the invoiced/credited quantity's
|
|
173
799
|
// (PEPPOL-EN16931-R130).
|
|
174
800
|
el("cac:Price", null, [
|
|
175
|
-
money("cbc:PriceAmount",
|
|
176
|
-
source.baseQuantity
|
|
177
|
-
? el(
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
801
|
+
money("cbc:PriceAmount", priceAmount, currency),
|
|
802
|
+
source.baseQuantity !== undefined
|
|
803
|
+
? el("cbc:BaseQuantity", { unitCode }, String(source.baseQuantity))
|
|
804
|
+
: null,
|
|
805
|
+
source.priceAllowance !== undefined
|
|
806
|
+
? el("cac:AllowanceCharge", null, [
|
|
807
|
+
el("cbc:ChargeIndicator", null, "false"),
|
|
808
|
+
money(
|
|
809
|
+
"cbc:Amount",
|
|
810
|
+
source.priceAllowance.amount ?? 0,
|
|
811
|
+
currency,
|
|
812
|
+
),
|
|
813
|
+
optionalMoney(
|
|
814
|
+
"cbc:BaseAmount",
|
|
815
|
+
source.priceAllowance.baseAmount,
|
|
816
|
+
currency,
|
|
817
|
+
),
|
|
818
|
+
])
|
|
182
819
|
: null,
|
|
183
820
|
]),
|
|
184
821
|
]);
|
|
@@ -186,60 +823,180 @@ const line = (
|
|
|
186
823
|
|
|
187
824
|
const attachmentReference = (attachment: UblAttachment): XmlElement =>
|
|
188
825
|
el("cac:AdditionalDocumentReference", null, [
|
|
189
|
-
el(
|
|
826
|
+
el(
|
|
827
|
+
"cbc:ID",
|
|
828
|
+
null,
|
|
829
|
+
attachment.id ?? attachment.filename ?? attachment.externalUri ?? "",
|
|
830
|
+
),
|
|
831
|
+
text("cbc:DocumentDescription", attachment.description),
|
|
190
832
|
el("cac:Attachment", null, [
|
|
191
|
-
|
|
192
|
-
"
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
833
|
+
isExternalOnly(attachment)
|
|
834
|
+
? el("cac:ExternalReference", null, [
|
|
835
|
+
el("cbc:URI", null, attachment.externalUri ?? ""),
|
|
836
|
+
])
|
|
837
|
+
: el(
|
|
838
|
+
"cbc:EmbeddedDocumentBinaryObject",
|
|
839
|
+
{
|
|
840
|
+
mimeCode: attachment.mimeCode ?? "",
|
|
841
|
+
filename: attachment.filename ?? "",
|
|
842
|
+
},
|
|
843
|
+
attachment.base64Content ?? "",
|
|
844
|
+
),
|
|
196
845
|
]),
|
|
197
846
|
]);
|
|
198
847
|
|
|
199
|
-
|
|
200
|
-
|
|
848
|
+
/** A typed `cac:AdditionalDocumentReference` without attachment (BT-17, BT-18, BT-11 on a credit note). */
|
|
849
|
+
const typedDocumentReference = (id: UblSchemedId, typeCode: string): XmlElement =>
|
|
850
|
+
el("cac:AdditionalDocumentReference", null, [
|
|
851
|
+
schemedId("cbc:ID", id),
|
|
852
|
+
el("cbc:DocumentTypeCode", null, typeCode),
|
|
853
|
+
]);
|
|
854
|
+
|
|
855
|
+
const documentReference = (name: string, id: string | undefined): XmlElement | null =>
|
|
856
|
+
id !== undefined ? el(name, null, [el("cbc:ID", null, id)]) : null;
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* `cac:OrderReference`. BT-13 (the buyer's order number) is the element's
|
|
860
|
+
* mandatory child, so a sales order id (BT-14) alone is not emitted.
|
|
861
|
+
*/
|
|
862
|
+
const orderReference = (doc: UblInvoice): XmlElement | null => {
|
|
863
|
+
if (doc.orderReference === undefined) return null;
|
|
864
|
+
return el("cac:OrderReference", null, [
|
|
865
|
+
el("cbc:ID", null, doc.orderReference),
|
|
866
|
+
text("cbc:SalesOrderID", doc.salesOrderId),
|
|
867
|
+
]);
|
|
868
|
+
};
|
|
869
|
+
|
|
870
|
+
const billingReference = (reference: UblBillingReference): XmlElement | null => {
|
|
871
|
+
if (reference.invoiceId === undefined) return null;
|
|
872
|
+
return el("cac:BillingReference", null, [
|
|
201
873
|
el("cac:InvoiceDocumentReference", null, [
|
|
202
|
-
el("cbc:ID", null,
|
|
874
|
+
el("cbc:ID", null, reference.invoiceId),
|
|
875
|
+
text("cbc:IssueDate", reference.invoiceIssueDate),
|
|
203
876
|
]),
|
|
204
877
|
]);
|
|
878
|
+
};
|
|
205
879
|
|
|
206
|
-
/**
|
|
207
|
-
|
|
208
|
-
|
|
880
|
+
/**
|
|
881
|
+
* Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.
|
|
882
|
+
*
|
|
883
|
+
* Writes every EN 16931 business term the model holds, at its position in the
|
|
884
|
+
* UBL 2.1 sequence: the header terms (`customizationId`, `profileId` and
|
|
885
|
+
* `invoiceTypeCode` default to the BIS values), the references (BT-10 to
|
|
886
|
+
* BT-19), the parties with identifications, legal form and contacts, the
|
|
887
|
+
* payee and tax representative, delivery, payment means, payment terms,
|
|
888
|
+
* document and line allowances and charges, the VAT breakdown (plus BT-111 in
|
|
889
|
+
* the accounting currency), the monetary totals, attachments and document
|
|
890
|
+
* references, and lines with their item identifiers, classifications,
|
|
891
|
+
* properties, price discount and classified VAT category. Line-level tax
|
|
892
|
+
* totals are not emitted: BIS Billing 3.0 forbids them.
|
|
893
|
+
*
|
|
894
|
+
* @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory
|
|
895
|
+
* is missing (naming the BT and the model path), or when the document's
|
|
896
|
+
* arithmetic breaks a business rule: BR-CO-3, BR-CO-10 to BR-CO-13, BR-CO-15,
|
|
897
|
+
* BR-CO-16, BR-53, the BR-S-08 family, PEPPOL-EN16931-R040 and R120.
|
|
898
|
+
*/
|
|
899
|
+
export const serializeUblInvoice = (doc: UblInvoice): string => {
|
|
900
|
+
validateInvoice(doc);
|
|
901
|
+
|
|
902
|
+
const isCreditNote = doc.documentType === "CreditNote";
|
|
209
903
|
const rootName = isCreditNote ? "CreditNote" : "Invoice";
|
|
210
904
|
const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
|
|
211
905
|
const typeCodeElement = isCreditNote
|
|
212
|
-
? el(
|
|
213
|
-
|
|
906
|
+
? el(
|
|
907
|
+
"cbc:CreditNoteTypeCode",
|
|
908
|
+
null,
|
|
909
|
+
doc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,
|
|
910
|
+
)
|
|
911
|
+
: el("cbc:InvoiceTypeCode", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);
|
|
912
|
+
const taxPointDate = text("cbc:TaxPointDate", doc.taxPointDate);
|
|
913
|
+
const means = paymentMeansList(doc);
|
|
914
|
+
// A credit note has no cbc:DueDate: BT-9 goes in the first PaymentMeans.
|
|
915
|
+
const creditNoteDueDate =
|
|
916
|
+
isCreditNote && means.length > 0 ? doc.dueDate : undefined;
|
|
214
917
|
|
|
215
918
|
const children: (XmlElement | null | false)[] = [
|
|
216
|
-
el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
|
|
217
|
-
el("cbc:ProfileID", null, UBL_PROFILE_ID),
|
|
919
|
+
el("cbc:CustomizationID", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),
|
|
920
|
+
el("cbc:ProfileID", null, doc.profileId ?? UBL_PROFILE_ID),
|
|
218
921
|
el("cbc:ID", null, doc.id),
|
|
219
922
|
el("cbc:IssueDate", null, doc.issueDate),
|
|
220
|
-
|
|
221
|
-
|
|
923
|
+
!isCreditNote ? text("cbc:DueDate", doc.dueDate) : null,
|
|
924
|
+
// The CreditNote sequence puts BT-7 before the type code, Invoice after the note.
|
|
925
|
+
isCreditNote ? taxPointDate : null,
|
|
222
926
|
typeCodeElement,
|
|
223
|
-
|
|
927
|
+
text("cbc:Note", doc.note),
|
|
928
|
+
!isCreditNote ? taxPointDate : null,
|
|
224
929
|
el("cbc:DocumentCurrencyCode", null, doc.currency),
|
|
225
|
-
|
|
930
|
+
text("cbc:TaxCurrencyCode", doc.taxCurrency),
|
|
931
|
+
text("cbc:AccountingCost", doc.accountingCost),
|
|
932
|
+
text("cbc:BuyerReference", doc.buyerReference),
|
|
226
933
|
invoicePeriod(doc.invoicePeriod),
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
934
|
+
orderReference(doc),
|
|
935
|
+
doc.billingReference ? billingReference(doc.billingReference) : null,
|
|
936
|
+
documentReference("cac:DespatchDocumentReference", doc.despatchReference),
|
|
937
|
+
documentReference("cac:ReceiptDocumentReference", doc.receivingAdviceReference),
|
|
938
|
+
documentReference("cac:ContractDocumentReference", doc.contractReference),
|
|
939
|
+
...(doc.attachments ?? []).map(attachmentReference),
|
|
940
|
+
...(doc.documentReferences ?? []).map((reference) =>
|
|
941
|
+
el("cac:AdditionalDocumentReference", null, [
|
|
942
|
+
el("cbc:ID", null, reference.id ?? ""),
|
|
943
|
+
text("cbc:DocumentDescription", reference.description),
|
|
944
|
+
]),
|
|
945
|
+
),
|
|
946
|
+
doc.invoicedObjectId !== undefined
|
|
947
|
+
? typedDocumentReference(doc.invoicedObjectId, "130")
|
|
948
|
+
: null,
|
|
949
|
+
!isCreditNote && doc.tenderReference !== undefined
|
|
950
|
+
? typedDocumentReference({ value: doc.tenderReference }, "50")
|
|
951
|
+
: null,
|
|
952
|
+
// UBL's CreditNote has no cac:ProjectReference; BIS uses type code 50.
|
|
953
|
+
isCreditNote && doc.projectReference !== undefined
|
|
954
|
+
? typedDocumentReference({ value: doc.projectReference }, "50")
|
|
955
|
+
: null,
|
|
956
|
+
!isCreditNote
|
|
957
|
+
? documentReference("cac:ProjectReference", doc.projectReference)
|
|
958
|
+
: null,
|
|
959
|
+
el("cac:AccountingSupplierParty", null, [
|
|
960
|
+
party(doc.seller, doc.seller.name ?? ""),
|
|
961
|
+
]),
|
|
962
|
+
el("cac:AccountingCustomerParty", null, [
|
|
963
|
+
party(doc.buyer, doc.buyer.name ?? ""),
|
|
964
|
+
]),
|
|
965
|
+
doc.payee ? payeeParty(doc.payee) : null,
|
|
966
|
+
doc.taxRepresentative ? taxRepresentativeParty(doc.taxRepresentative) : null,
|
|
967
|
+
doc.delivery ? delivery(doc.delivery) : null,
|
|
968
|
+
...means.map((entry, index) =>
|
|
969
|
+
paymentMeans(entry, index === 0 ? creditNoteDueDate : undefined),
|
|
970
|
+
),
|
|
971
|
+
// BT-20. In both sequences PaymentTerms sits after PaymentMeans and
|
|
972
|
+
// before AllowanceCharge and TaxTotal.
|
|
973
|
+
doc.paymentTermsNote !== undefined
|
|
235
974
|
? el("cac:PaymentTerms", null, [el("cbc:Note", null, doc.paymentTermsNote)])
|
|
236
975
|
: null,
|
|
976
|
+
...(doc.allowanceCharges ?? []).map((entry, index) =>
|
|
977
|
+
allowanceCharge(
|
|
978
|
+
entry,
|
|
979
|
+
doc.currency,
|
|
980
|
+
`allowanceCharges[${index}]`,
|
|
981
|
+
"document",
|
|
982
|
+
),
|
|
983
|
+
),
|
|
237
984
|
el("cac:TaxTotal", null, [
|
|
238
|
-
money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency),
|
|
239
|
-
...doc.taxTotal.subtotals.map((subtotal) =>
|
|
240
|
-
taxSubtotal(subtotal, doc.currency),
|
|
985
|
+
money("cbc:TaxAmount", doc.taxTotal.taxAmount ?? 0, doc.currency),
|
|
986
|
+
...doc.taxTotal.subtotals.map((subtotal, index) =>
|
|
987
|
+
taxSubtotal(subtotal, doc.currency, index),
|
|
241
988
|
),
|
|
242
989
|
]),
|
|
990
|
+
// BT-111: a second TaxTotal carrying only the VAT total in BT-6.
|
|
991
|
+
doc.taxCurrency !== undefined
|
|
992
|
+
? el("cac:TaxTotal", null, [
|
|
993
|
+
money(
|
|
994
|
+
"cbc:TaxAmount",
|
|
995
|
+
doc.taxTotal.taxAmountInTaxCurrency ?? 0,
|
|
996
|
+
doc.taxCurrency,
|
|
997
|
+
),
|
|
998
|
+
])
|
|
999
|
+
: null,
|
|
243
1000
|
el("cac:LegalMonetaryTotal", null, legalMonetaryTotalChildren(doc)),
|
|
244
1001
|
...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),
|
|
245
1002
|
];
|
|
@@ -256,3 +1013,6 @@ export const serializeUblDocument = (doc: UblDocument): string => {
|
|
|
256
1013
|
|
|
257
1014
|
return serializeDocument(root);
|
|
258
1015
|
};
|
|
1016
|
+
|
|
1017
|
+
/** Alias of {@link serializeUblInvoice}, kept under the historical name. */
|
|
1018
|
+
export const serializeUblDocument = serializeUblInvoice;
|