@formancy/report-runtime 0.1.0 → 0.3.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/NOTICE +8 -0
- package/README.md +615 -14
- package/dist/index.d.mts +794 -73
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3717 -564
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,30 @@
|
|
|
1
|
-
import { ASSET_MEDIA_TYPES, MAX_ERRORS, MAX_KEY_LENGTH, MAX_SCALE, isIdentifier, reportHash, validateReport } from "@formancy/report-spec";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
1
|
+
import { ASSET_MEDIA_TYPES, BASELINE_SHIFTS, BIDI_CONTROLS, CHART_PALETTE, EPC_CAPTION, EPC_CAPTION_MODULE, EPC_FRAME, EPC_MAX_BYTES, EPC_MAX_BYTES as EPC_MAX_BYTES$1, EPC_MAX_VERSION, EPC_MAX_VERSION as EPC_MAX_VERSION$1, EPC_TEXT_FIELDS, E_INVOICE_DATES, E_INVOICE_DECIMALS, E_INVOICE_KIND_TEXTS, E_INVOICE_LINE_CODES, E_INVOICE_LINE_COLUMNS, E_INVOICE_TEXTS, E_INVOICE_TEXT_TERMS, FACTUR_X, FACTUR_X as FACTUR_X$1, FACTUR_X_PROFILES, FACTUR_X_PROFILES as FACTUR_X_PROFILES$1, FONT_EMBEDDING_REFUSALS, FONT_FACE_KEYS, FONT_FACE_KEYS as FONT_FACE_KEYS$1, FONT_FORMATS, FONT_MEDIA_TYPES, FONT_REFUSAL_CODES, IMAGE_REFUSAL_CODES, MAX_ASSET_BYTES, MAX_ASSET_BYTES as MAX_ASSET_BYTES$1, MAX_ASSET_SIDE, MAX_CHART_SERIES, MAX_ERRORS, MAX_FONT_BYTES, MAX_FONT_BYTES as MAX_FONT_BYTES$1, MAX_FONT_CHARACTERS, MAX_FONT_LINE, MAX_FONT_SIZE, MAX_KEEP_WITH_ROWS, MAX_KEY_LENGTH, MAX_QR_BILL_ADDITIONAL_INFORMATION, MAX_QR_BILL_ADDITIONAL_INFORMATION as MAX_QR_BILL_ADDITIONAL_INFORMATION$1, MAX_SCALE, MAX_SCALE as MAX_SCALE$1, MAX_SVG_BYTES, MAX_SVG_BYTES as MAX_SVG_BYTES$1, MAX_SVG_COORDINATE, MAX_SVG_DEPTH, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS, MIN_FONT_LINE, MIN_FONT_SIZE, PRINTED_BLOCKS, QR_BILL_ADDRESS_RULES, QR_BILL_BILLING_RULE, QR_BILL_CURRENCIES, QR_BILL_CURRENCIES as QR_BILL_CURRENCIES$1, QR_BILL_MESSAGE_RULE, QR_BILL_SIZE, QR_BILL_TOP, SVG_ELEMENTS, SVG_REFUSAL_CODES, UNICODE_VERSION, XRECHNUNG, XRECHNUNG as XRECHNUNG$1, XRECHNUNG_VERSIONS, assetDigest, buyerIdentificationBreak, characterMap, checkEInvoiceDate, checkEInvoiceDecimal, checkEInvoiceText, checkElectronicAddress, checkEpcAmount, checkEpcField, checkEpcPayload, checkInvoicingPeriod, checkLineCategory, checkQrBillAccount, checkQrBillAdditionalInformation, checkQrBillAmount, checkQrBillAmount as checkQrBillAmount$1, checkQrBillReference, checkQrBillText, checkSvg, checkVatRate, cleanSvg, declaredLocales, eInvoiceBlank, en16931Rule, epcBlank, epcCaptionBreak, epcCaptionBreak as epcCaptionBreak$1, epcLeastVersion, epcLeastVersion as epcLeastVersion$1, epcModule, epcPairing, epcPayload, faceKey, imageHeader, isFontMediaType, isFontMediaType as isFontMediaType$1, isFormId, isIdentifier, isLocale, isSchemaHash, qrBillPageBreak, qrBillPageBreak as qrBillPageBreak$1, qrBillPairing, qrSymbolModules, readFont, readFont as readFont$1, refusedCharacter, renderLocale, reportHash, reportIn, sellerIdentificationBreaks, sniffImage, supplyBreak, utf8Length, validateReport, vatReasonBreak, walkComponents, xmlCharacterBreak } from "@formancy/report-spec";
|
|
2
|
+
import { encode } from "uqr";
|
|
3
|
+
import { DEFAULT_BUDGET, DEFAULT_VALUE_LIMITS, Decimal, addDecimal, compareDecimal, decimalFromString, decimalToString, evaluate, fixedCapabilities, multiplyDecimal, roundDecimal, subtractDecimal } from "@formancy/expressions";
|
|
4
|
+
import { compileReport, diagnose, expressionValues, seriesType } from "@formancy/report-core";
|
|
5
|
+
// src/document.ts
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* A run set below or above the line prints at this fraction of its
|
|
8
|
+
* paragraph's size, in the paragraph's face (0061). It is pdfmake 0.3.11's
|
|
9
|
+
* own figure (`TextInlines.js`), stated here as the document's, for any
|
|
10
|
+
* engine: the renderer counts such a run's line at it (`bound.ts`), the
|
|
11
|
+
* corpus reads a run at it as one of its line (`lines.ts`), and a PDF that
|
|
12
|
+
* draws another fails there.
|
|
10
13
|
*/
|
|
11
|
-
const
|
|
14
|
+
const SHIFTED_SIZE = .58;
|
|
15
|
+
/**
|
|
16
|
+
* How far such a run's baseline is moved from its line's, as a fraction of
|
|
17
|
+
* its paragraph's size, up positive: 0.75 of the reduced size up for a run
|
|
18
|
+
* set above the line, 0.35 of it down for one below, 0.435 and 0.203 of the
|
|
19
|
+
* paragraph's size. pdfmake 0.3.11's own figures (`Renderer.js`'s
|
|
20
|
+
* `offsetText`), as `SHIFTED_SIZE` is. The move itself takes no room in
|
|
21
|
+
* the line: what room a line makes for such a run, below or above it, is
|
|
22
|
+
* the engine's.
|
|
23
|
+
*/
|
|
24
|
+
const SHIFTED_RISE = {
|
|
25
|
+
superscript: .75 * SHIFTED_SIZE,
|
|
26
|
+
subscript: -.35 * SHIFTED_SIZE
|
|
27
|
+
};
|
|
12
28
|
const REFUSAL_CODES = [
|
|
13
29
|
"too-many-pages",
|
|
14
30
|
"content-too-large",
|
|
@@ -17,8 +33,9 @@ const REFUSAL_CODES = [
|
|
|
17
33
|
"unsupported"
|
|
18
34
|
];
|
|
19
35
|
/**
|
|
20
|
-
* Why an engine produced no PDF
|
|
21
|
-
*
|
|
36
|
+
* Why an engine produced no file: the PDF renderer no PDF, the Word writer
|
|
37
|
+
* no Word file (0068). An engine refuses rather than truncates: a report
|
|
38
|
+
* that cannot be printed, or written, whole is not, and the caller is told
|
|
22
39
|
* what stopped it. `subject` names the asset, table or block concerned, when
|
|
23
40
|
* the refusal is about one.
|
|
24
41
|
*/
|
|
@@ -32,8 +49,476 @@ var RenderRefusal = class extends Error {
|
|
|
32
49
|
this.subject = subject;
|
|
33
50
|
}
|
|
34
51
|
};
|
|
35
|
-
|
|
36
|
-
|
|
52
|
+
// src/qr-symbol.ts
|
|
53
|
+
/**
|
|
54
|
+
* A QR code's symbol (ISO/IEC 18004), and what refuses one: decided here
|
|
55
|
+
* once, below every engine, so that the PDF renderer and the Word writer
|
|
56
|
+
* draw one symbol of a code and refuse the same codes in the same words
|
|
57
|
+
* (0074). An engine draws the symbol it is handed, and decides nothing of
|
|
58
|
+
* it.
|
|
59
|
+
*
|
|
60
|
+
* uqr encodes the text as UTF-8 in byte mode -- or as digits or
|
|
61
|
+
* upper-case alphanumerics, when that is all it holds -- in the smallest
|
|
62
|
+
* version that holds it at the level asked, and never raises the level to
|
|
63
|
+
* fill a version. An engine encodes a code once, when it checks the
|
|
64
|
+
* document, and draws that symbol, so that what is refused and what is
|
|
65
|
+
* drawn are one decision (0020).
|
|
66
|
+
*
|
|
67
|
+
* The square a code stands in is its `size`, its quiet zone inside it:
|
|
68
|
+
* four modules on every side, white, the symbol between them, so a
|
|
69
|
+
* module is the size over the symbol's modules and eight.
|
|
70
|
+
*/
|
|
71
|
+
/** ISO/IEC 18004's quiet zone: four modules of white on every side of the symbol. */
|
|
72
|
+
const QR_QUIET_ZONE = 4;
|
|
73
|
+
/**
|
|
74
|
+
* The smallest module drawn: 0.4 mm, 1.13 pt. ISO/IEC 18004 leaves the
|
|
75
|
+
* module's size to the application; SIX's Swiss Implementation Guidelines
|
|
76
|
+
* for the QR-bill, version 2.3, section 6.3, require at least 0.4 mm when
|
|
77
|
+
* printing, and that is taken here as what a printer prints and a phone's
|
|
78
|
+
* camera reads reliably. A square too small for its text at that module is
|
|
79
|
+
* refused, naming the size it needs, never drawn finer. It is a borrowed
|
|
80
|
+
* minimum: the same guidelines draw their largest code finer (0020).
|
|
81
|
+
*/
|
|
82
|
+
const QR_MIN_MODULE = 28.8 / 25.4;
|
|
83
|
+
/**
|
|
84
|
+
* The most characters any QR code holds: 7089 digits, version 40 at level
|
|
85
|
+
* L (ISO/IEC 18004, table 7). A character is a code point, as a reader
|
|
86
|
+
* counts one: an emoji is one, though JavaScript holds it in two code
|
|
87
|
+
* units. Longer text fits no version in any mode, and is refused before it
|
|
88
|
+
* is encoded, which takes time and memory with the length of the text;
|
|
89
|
+
* within it, the encoder decides by the bytes the text takes.
|
|
90
|
+
*/
|
|
91
|
+
const QR_MAX_CHARACTERS = 7089;
|
|
92
|
+
const LEVELS = /* @__PURE__ */ new Set([
|
|
93
|
+
"L",
|
|
94
|
+
"M",
|
|
95
|
+
"Q",
|
|
96
|
+
"H"
|
|
97
|
+
]);
|
|
98
|
+
/** The version `symbol` is, from its modules a side (ISO/IEC 18004: 4 a version and 17). */
|
|
99
|
+
function qrSymbolVersion(symbol) {
|
|
100
|
+
return (symbol.modules.length - 17) / 4;
|
|
101
|
+
}
|
|
102
|
+
/** A code point as Unicode writes it: U+5C71. */
|
|
103
|
+
const codePoint = (point) => `U+${point.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
104
|
+
/** The lone half of a surrogate pair `text` holds, as a refusal names it, or undefined: with the u flag, a pair is one character and only a lone half is a surrogate. */
|
|
105
|
+
function loneSurrogate(text) {
|
|
106
|
+
const lone = /\p{Cs}/u.exec(text)?.[0];
|
|
107
|
+
return lone === void 0 ? void 0 : codePoint(lone.charCodeAt(0));
|
|
108
|
+
}
|
|
109
|
+
/** How many code points `text` holds, counted without building them into an array. */
|
|
110
|
+
function codePoints(text) {
|
|
111
|
+
let count = 0;
|
|
112
|
+
for (const _ of text) count++;
|
|
113
|
+
return count;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Refuses a code's square that is no size, as `unsupported`, or wider
|
|
117
|
+
* than the `width` it stands at, as `content-too-large`: a code is a
|
|
118
|
+
* square that stands where an image may. How tall a page's body is, is an
|
|
119
|
+
* engine's to know, and to refuse a square by.
|
|
120
|
+
*/
|
|
121
|
+
function refuseSquare(what, id, size, width) {
|
|
122
|
+
if (!(size > 0 && Number.isFinite(size))) throw new RenderRefusal("unsupported", `${what} is drawn ${size} pt a side`, id);
|
|
123
|
+
if (size > width) throw new RenderRefusal("content-too-large", `${what} is ${size} pt wide; it stands ${width.toFixed(2)} pt wide`, id);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* `code`'s symbol where it stands `width` points wide, or the refusal
|
|
127
|
+
* that says why it is not drawn: a square of no size, a level or text no
|
|
128
|
+
* encoder can draw, as `unsupported`; a square wider than where it
|
|
129
|
+
* stands, text no version holds, or a square too small for the version
|
|
130
|
+
* that holds it, as `content-too-large`. Each names the code by its id.
|
|
131
|
+
*/
|
|
132
|
+
function qrSymbol(code, width) {
|
|
133
|
+
const { id, text, size, errorCorrection } = code;
|
|
134
|
+
refuseSquare(`the QR code ${id}`, id, size, width);
|
|
135
|
+
if (!LEVELS.has(errorCorrection)) throw new RenderRefusal("unsupported", `the QR code ${id} asks for the error correction level '${String(errorCorrection)}'; the levels are L, M, Q and H`, id);
|
|
136
|
+
if (typeof text !== "string") throw new RenderRefusal("unsupported", `the QR code ${id} encodes something that is not text`, id);
|
|
137
|
+
const lone = loneSurrogate(text);
|
|
138
|
+
if (lone !== void 0) throw new RenderRefusal("unsupported", `the QR code ${id} holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`, id);
|
|
139
|
+
const characters = text.length > 7089 ? codePoints(text) : text.length;
|
|
140
|
+
if (characters > 7089) throw new RenderRefusal("content-too-large", `the QR code ${id} holds ${characters} characters; no QR code holds more than ${QR_MAX_CHARACTERS}`, id);
|
|
141
|
+
const modules = encoded(text, errorCorrection, id);
|
|
142
|
+
refuseFineModules({ modules }, size, `the QR code ${id}`, "its text", id);
|
|
143
|
+
return { modules };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Refuses `symbol` drawn in a square of `size` with its quiet zone when its
|
|
147
|
+
* modules would be finer than 0.4 mm, naming the square `holds` needs:
|
|
148
|
+
* the floor every code drawn with a quiet zone is held to (0020).
|
|
149
|
+
*/
|
|
150
|
+
function refuseFineModules(symbol, size, what, holds, id) {
|
|
151
|
+
const count = symbol.modules.length + 8;
|
|
152
|
+
const smallest = count * QR_MIN_MODULE;
|
|
153
|
+
if (size < smallest) throw new RenderRefusal("content-too-large", `${what} is ${size} pt a side, which makes the ${count} modules across its symbol and quiet zone ${(size / count).toFixed(2)} pt each; the smallest module is 0.4 mm (${QR_MIN_MODULE.toFixed(2)} pt), so ${holds} needs a square of at least ${(Math.ceil(smallest * 100) / 100).toFixed(2)} pt`, id);
|
|
154
|
+
}
|
|
155
|
+
/** Whether `error` is what uqr 0.1.3 says of text no version holds, and says of nothing else. */
|
|
156
|
+
function tooLong(error) {
|
|
157
|
+
return error instanceof RangeError && error.message === "Data too long";
|
|
158
|
+
}
|
|
159
|
+
/** The symbol uqr encodes, without its quiet zone; refused when no version holds the text. */
|
|
160
|
+
function encoded(text, level, id) {
|
|
161
|
+
try {
|
|
162
|
+
return encode(text, {
|
|
163
|
+
ecc: level,
|
|
164
|
+
border: 0,
|
|
165
|
+
boostEcc: false
|
|
166
|
+
}).data;
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (!tooLong(error)) throw error;
|
|
169
|
+
throw new RenderRefusal("content-too-large", `the QR code ${id} holds ${utf8Length(text)} bytes of text, more than a QR code at level ${level} holds`, id);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The most characters a Swiss QR Code holds, its line feeds included: 997
|
|
174
|
+
* (IG 6.2), which is what version 25 holds at level M in byte mode. A
|
|
175
|
+
* payload of more is refused before it is encoded.
|
|
176
|
+
*/
|
|
177
|
+
const SWISS_QR_MAX_CHARACTERS = 997;
|
|
178
|
+
/** The largest version SIX allows (IG 6.2): 117 modules a side. */
|
|
179
|
+
const SWISS_MAX_VERSION = 25;
|
|
180
|
+
/**
|
|
181
|
+
* A QR-bill's Swiss QR Code (IG 6), or the refusal that says why it is not
|
|
182
|
+
* drawn: its payload as UTF-8 at level M (6.1), in the smallest version that
|
|
183
|
+
* holds it (6.4), and never past version 25 (6.2). A payload of more than
|
|
184
|
+
* 997 characters is refused unencoded; one whose UTF-8 is more than version
|
|
185
|
+
* 25 holds, once the encoder finds none does. Every refusal names the
|
|
186
|
+
* payment part, and none quotes the payload: it holds names and accounts.
|
|
187
|
+
*
|
|
188
|
+
* SIX prints the code at 46 mm whatever its version, so a module is 46 mm
|
|
189
|
+
* over the symbol's modules, 0.393 mm at version 25: finer than the 0.4 mm
|
|
190
|
+
* a `qrCode` is held to, which is SIX's own figure for print (6.3). SIX's
|
|
191
|
+
* size is drawn, not the floor (0020's generic minimum does not apply).
|
|
192
|
+
*/
|
|
193
|
+
function swissSymbol(payload) {
|
|
194
|
+
const refuse = (code, what) => new RenderRefusal(code, `the payment part's Swiss QR Code ${what}`, "paymentPart");
|
|
195
|
+
if (typeof payload !== "string") throw refuse("unsupported", "holds something that is not text");
|
|
196
|
+
const lone = loneSurrogate(payload);
|
|
197
|
+
if (lone !== void 0) throw refuse("unsupported", `holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`);
|
|
198
|
+
const characters = payload.length > 997 ? codePoints(payload) : payload.length;
|
|
199
|
+
if (characters > 997) throw refuse("content-too-large", `holds ${characters} characters; SIX allows 997`);
|
|
200
|
+
try {
|
|
201
|
+
return { modules: encode(payload, {
|
|
202
|
+
ecc: "M",
|
|
203
|
+
border: 0,
|
|
204
|
+
boostEcc: false,
|
|
205
|
+
maxVersion: SWISS_MAX_VERSION
|
|
206
|
+
}).data };
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (!tooLong(error)) throw error;
|
|
209
|
+
throw refuse("content-too-large", `holds ${utf8Length(payload)} bytes, more than version ${SWISS_MAX_VERSION} holds at level M, the largest code SIX allows`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// src/bill-check.ts
|
|
213
|
+
/** The longest value a slip prints: a line of the additional information, which the message and the billing information share (IG Table 8). An address line is shorter. */
|
|
214
|
+
const MAX_VALUE = MAX_QR_BILL_ADDITIONAL_INFORMATION$1;
|
|
215
|
+
/** An amount as the slip prints it: a space between thousands, a point and two decimals (IG 3.5.3). Which amounts a bill pays is report-spec's `checkQrBillAmount`. */
|
|
216
|
+
const AMOUNT = /^\d{1,3}(?: \d{3})*\.\d{2}$/;
|
|
217
|
+
/** The lines an address prints: its name, its street and building number, its postal code and town (IG 3.5.4). */
|
|
218
|
+
const ADDRESS_LINES = 3;
|
|
219
|
+
/** The message and the billing information, each on its line. */
|
|
220
|
+
const ADDITIONAL_LINES = 2;
|
|
221
|
+
function refuse$5(what) {
|
|
222
|
+
return new RenderRefusal("unsupported", `the payment part's ${what}`, "paymentPart");
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Refuses `page` for a slip by report-spec's rule, the one the editor
|
|
226
|
+
* refuses it by (`qrBillPageBreak`): a page that is not A4 in portrait,
|
|
227
|
+
* which has no foot the slip spans, and one whose top margin, with `above`
|
|
228
|
+
* printed under it, reaches into the slip, which no layout can undo.
|
|
229
|
+
*/
|
|
230
|
+
function refuseBillPage(page, above = 0) {
|
|
231
|
+
const broken = qrBillPageBreak$1(page, above);
|
|
232
|
+
if (broken !== void 0) throw new RenderRefusal(broken.field === "page" ? "unsupported" : "content-too-large", broken.rule, "paymentPart");
|
|
233
|
+
}
|
|
234
|
+
/** Refuses what no engine draws of `bill` on `page`, the top margin alone before anything above the slip is measured, and encodes its code. */
|
|
235
|
+
function checkQrBill(bill, page, undrawn) {
|
|
236
|
+
const { kind } = bill;
|
|
237
|
+
if (kind !== "swissQrBill") throw new RenderRefusal("unsupported", `the payment part is a '${String(kind)}', which a report does not know`, "paymentPart");
|
|
238
|
+
refuseBillPage(page);
|
|
239
|
+
const text = (value, what, face) => {
|
|
240
|
+
if (typeof value !== "string") throw refuse$5(`${what} holds something that is not text`);
|
|
241
|
+
if (value.length > MAX_VALUE) throw refuse$5(`${what} holds a value longer than any SIX allows, ${MAX_VALUE} characters`);
|
|
242
|
+
const missing = undrawn(value, face);
|
|
243
|
+
if (missing !== void 0) throw refuse$5(`${what} ${missing}`);
|
|
244
|
+
};
|
|
245
|
+
const lines = (value, what, most, least) => {
|
|
246
|
+
if (!Array.isArray(value)) throw refuse$5(`${what} is not lines of text`);
|
|
247
|
+
if (value.length > most || value.length < least) throw refuse$5(`${what} has the wrong number of lines: a slip prints ${least} to ${most}`);
|
|
248
|
+
for (const line of value) text(line, what, "normal");
|
|
249
|
+
};
|
|
250
|
+
const headings = bill.headings ?? {};
|
|
251
|
+
for (const [key, face] of Object.entries(BILL_HEADING_FACES)) text(headings[key], `heading '${key}'`, face);
|
|
252
|
+
text(bill.account, "account", "normal");
|
|
253
|
+
lines(bill.creditor, "creditor's address", ADDRESS_LINES, 2);
|
|
254
|
+
if (bill.reference !== null) text(bill.reference, "reference", "normal");
|
|
255
|
+
lines(bill.additionalInformation, "additional information", ADDITIONAL_LINES, 0);
|
|
256
|
+
if (bill.debtor !== null) lines(bill.debtor, "debtor's address", ADDRESS_LINES, 2);
|
|
257
|
+
if (!QR_BILL_CURRENCIES$1.includes(bill.currency)) throw refuse$5(`currency is not one SIX allows: ${QR_BILL_CURRENCIES$1.join(" or ")}`);
|
|
258
|
+
text(bill.currency, "currency", "normal");
|
|
259
|
+
if (bill.amount !== null) {
|
|
260
|
+
if (typeof bill.amount !== "string" || !AMOUNT.test(bill.amount)) throw refuse$5("amount is not written as the slip prints one: its thousands apart and two decimals");
|
|
261
|
+
const paid = checkQrBillAmount$1(bill.amount.replaceAll(" ", ""));
|
|
262
|
+
if (!paid.ok) throw refuse$5(`amount ${paid.rule}`);
|
|
263
|
+
text(bill.amount, "amount", "normal");
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
bill,
|
|
267
|
+
symbol: swissSymbol(bill.payload)
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The face each heading of a slip prints in, which an engine's glyphs
|
|
272
|
+
* and widths are held to: `separate` regular, the rest bold. A table
|
|
273
|
+
* over every heading, so that one added to the document's
|
|
274
|
+
* `QrBillHeadings` without its face does not compile, rather than going
|
|
275
|
+
* unchecked.
|
|
276
|
+
*/
|
|
277
|
+
const BILL_HEADING_FACES = {
|
|
278
|
+
paymentPart: "bold",
|
|
279
|
+
receipt: "bold",
|
|
280
|
+
account: "bold",
|
|
281
|
+
reference: "bold",
|
|
282
|
+
additionalInformation: "bold",
|
|
283
|
+
payableBy: "bold",
|
|
284
|
+
currency: "bold",
|
|
285
|
+
amount: "bold",
|
|
286
|
+
acceptancePoint: "bold",
|
|
287
|
+
separate: "normal"
|
|
288
|
+
};
|
|
289
|
+
// src/slip-print.ts
|
|
290
|
+
/**
|
|
291
|
+
* Where SIX puts each part of a QR-bill's slip, the receipt and the
|
|
292
|
+
* payment part, and at what size: stated here once, below every engine,
|
|
293
|
+
* so that the PDF renderer and the Word writer lay one slip out (0075).
|
|
294
|
+
* An engine draws by these, in its own way, and decides none of them.
|
|
295
|
+
* Nothing here formats a value: the runtime hands every text as it
|
|
296
|
+
* prints (`QrBill`).
|
|
297
|
+
*
|
|
298
|
+
* The numbers are SIX's: "IG" is the Swiss Implementation Guidelines for
|
|
299
|
+
* the QR-bill, version 2.4, and "SG" its Style Guide, version 1.1, whose
|
|
300
|
+
* page 6 gives every section's place and size in millimetres, page 7 the
|
|
301
|
+
* blank fields', and page 15 the sizes and line spacing. What neither gives
|
|
302
|
+
* is taken from manuelbl's SwissQRBill generator, which matches SG 7 drawn
|
|
303
|
+
* to scale: where the blank amount fields stand, and 2 pt between a
|
|
304
|
+
* debtor's heading and its field.
|
|
305
|
+
*
|
|
306
|
+
* Positions are in points from the slip's top left. The slip is
|
|
307
|
+
* report-spec's `QR_BILL_SIZE`, 210 by 105 mm.
|
|
308
|
+
*/
|
|
309
|
+
/** Millimetres in points. */
|
|
310
|
+
const mm = (value) => value * 72 / 25.4;
|
|
311
|
+
/** The receipt is 62 mm wide, and the payment part starts there (IG 3.3). */
|
|
312
|
+
const SLIP_RECEIPT_WIDTH = mm(62);
|
|
313
|
+
/**
|
|
314
|
+
* "Separate before paying in", above the line along the slip's top, outside
|
|
315
|
+
* the payment part, which a slip may print instead of a scissors symbol
|
|
316
|
+
* (IG 3.7, SG 4): 8 pt, the payment part's heading size, centred over the
|
|
317
|
+
* slip, its baseline 3 pt above the line. SIX gives neither.
|
|
318
|
+
*/
|
|
319
|
+
const SLIP_INSTRUCTION = {
|
|
320
|
+
size: 8,
|
|
321
|
+
gap: 3
|
|
322
|
+
};
|
|
323
|
+
/** The lines the slip is cut along (IG 3.7): solid, half a point. SIX gives no weight. */
|
|
324
|
+
const SLIP_SEPARATION = .5;
|
|
325
|
+
/** A blank field's corner marks: 3 mm arms, 0.75 pt (IG 3.5.3, SG 7). */
|
|
326
|
+
const SLIP_CORNER = {
|
|
327
|
+
arm: mm(3),
|
|
328
|
+
weight: .75
|
|
329
|
+
};
|
|
330
|
+
/** Between a debtor's heading's line and its blank field. */
|
|
331
|
+
const SLIP_FIELD_GAP = 2;
|
|
332
|
+
/** The titles, "Receipt" and "Payment part": 11 pt bold (IG 3.5.1, 3.6.1). */
|
|
333
|
+
const SLIP_TITLE = 11;
|
|
334
|
+
/** The receipt, 62 by 105 mm (SG 6): 5 mm margins, its title, 56 mm of information, 14 of amount, 18 of acceptance point. */
|
|
335
|
+
const SLIP_RECEIPT = {
|
|
336
|
+
name: "the receipt",
|
|
337
|
+
lettering: {
|
|
338
|
+
heading: 6,
|
|
339
|
+
value: 8,
|
|
340
|
+
pitch: 9
|
|
341
|
+
},
|
|
342
|
+
title: {
|
|
343
|
+
x: mm(5),
|
|
344
|
+
top: mm(5),
|
|
345
|
+
heading: "receipt"
|
|
346
|
+
},
|
|
347
|
+
additionalInformation: false,
|
|
348
|
+
information: {
|
|
349
|
+
x: mm(5),
|
|
350
|
+
top: mm(12),
|
|
351
|
+
width: mm(52),
|
|
352
|
+
height: mm(56),
|
|
353
|
+
millimetres: 56
|
|
354
|
+
},
|
|
355
|
+
amount: {
|
|
356
|
+
x: mm(5),
|
|
357
|
+
top: mm(68),
|
|
358
|
+
indent: mm(12),
|
|
359
|
+
pitch: 11
|
|
360
|
+
},
|
|
361
|
+
amountField: {
|
|
362
|
+
x: mm(27),
|
|
363
|
+
width: mm(30),
|
|
364
|
+
height: mm(10),
|
|
365
|
+
onAmountLine: false
|
|
366
|
+
},
|
|
367
|
+
debtorField: {
|
|
368
|
+
width: mm(52),
|
|
369
|
+
height: mm(20)
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
/** The payment part, 148 by 105 mm (SG 6): the code's 46 mm and the amount's 22 mm beside 87 by 85 mm of information. */
|
|
373
|
+
const SLIP_PAYMENT_PART = {
|
|
374
|
+
name: "the payment part",
|
|
375
|
+
lettering: {
|
|
376
|
+
heading: 8,
|
|
377
|
+
value: 10,
|
|
378
|
+
pitch: 11
|
|
379
|
+
},
|
|
380
|
+
title: {
|
|
381
|
+
x: SLIP_RECEIPT_WIDTH + mm(5),
|
|
382
|
+
top: mm(5),
|
|
383
|
+
heading: "paymentPart"
|
|
384
|
+
},
|
|
385
|
+
additionalInformation: true,
|
|
386
|
+
information: {
|
|
387
|
+
x: SLIP_RECEIPT_WIDTH + mm(56),
|
|
388
|
+
top: mm(5),
|
|
389
|
+
width: mm(87),
|
|
390
|
+
height: mm(85),
|
|
391
|
+
millimetres: 85
|
|
392
|
+
},
|
|
393
|
+
amount: {
|
|
394
|
+
x: SLIP_RECEIPT_WIDTH + mm(5),
|
|
395
|
+
top: mm(68),
|
|
396
|
+
indent: mm(15),
|
|
397
|
+
pitch: 13
|
|
398
|
+
},
|
|
399
|
+
amountField: {
|
|
400
|
+
x: SLIP_RECEIPT_WIDTH + mm(16),
|
|
401
|
+
width: mm(40),
|
|
402
|
+
height: mm(15),
|
|
403
|
+
onAmountLine: true
|
|
404
|
+
},
|
|
405
|
+
debtorField: {
|
|
406
|
+
width: mm(65),
|
|
407
|
+
height: mm(25)
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
/** The Swiss QR Code's place: 5 mm in, below the title section and 5 mm of quiet zone (IG 3.5.2, SG 6). */
|
|
411
|
+
const SLIP_CODE = {
|
|
412
|
+
x: SLIP_RECEIPT_WIDTH + mm(5),
|
|
413
|
+
top: mm(17)
|
|
414
|
+
};
|
|
415
|
+
/** The acceptance point, right-aligned to the receipt's text at the top of its section (IG 3.6.4, SG 6). */
|
|
416
|
+
const SLIP_ACCEPTANCE = {
|
|
417
|
+
right: mm(57),
|
|
418
|
+
top: mm(82)
|
|
419
|
+
};
|
|
420
|
+
/** The blocks a part's information holds, in SIX's order (IG 3.5.4, 3.6.2): the additional information in the payment part alone. */
|
|
421
|
+
function slipBlocks(bill, part) {
|
|
422
|
+
const { headings } = bill;
|
|
423
|
+
return [
|
|
424
|
+
{
|
|
425
|
+
heading: headings.account,
|
|
426
|
+
values: [bill.account, ...bill.creditor]
|
|
427
|
+
},
|
|
428
|
+
...bill.reference === null ? [] : [{
|
|
429
|
+
heading: headings.reference,
|
|
430
|
+
values: [bill.reference]
|
|
431
|
+
}],
|
|
432
|
+
...part.additionalInformation && bill.additionalInformation.length > 0 ? [{
|
|
433
|
+
heading: headings.additionalInformation,
|
|
434
|
+
values: bill.additionalInformation
|
|
435
|
+
}] : [],
|
|
436
|
+
bill.debtor === null ? {
|
|
437
|
+
heading: headings.payableBy,
|
|
438
|
+
field: part.debtorField
|
|
439
|
+
} : {
|
|
440
|
+
heading: headings.payableBy,
|
|
441
|
+
values: bill.debtor
|
|
442
|
+
}
|
|
443
|
+
];
|
|
444
|
+
}
|
|
445
|
+
/** A Swiss QR Code's side, without a quiet zone, whatever its version (IG 6.4): its modules are this over theirs. */
|
|
446
|
+
const SWISS_CODE_SIZE = mm(46);
|
|
447
|
+
/**
|
|
448
|
+
* The Swiss cross over the code's centre (IG 6.4.2), in millimetres: SIX's
|
|
449
|
+
* logo, as schoero's generator draws it, is a white square of 7 mm, a black
|
|
450
|
+
* square of 6 mm on it, and a white cross on that, its arms 7/6 mm wide and
|
|
451
|
+
* 35/9 mm from end to end. manuelbl's draws the same black square and cross
|
|
452
|
+
* on modules it clears, rather than on a white square.
|
|
453
|
+
*/
|
|
454
|
+
const SWISS_CROSS = {
|
|
455
|
+
white: 7,
|
|
456
|
+
black: 6,
|
|
457
|
+
arm: 7 / 6,
|
|
458
|
+
span: 35 / 9
|
|
459
|
+
};
|
|
460
|
+
// src/epc-symbol.ts
|
|
461
|
+
/**
|
|
462
|
+
* An EPC QR code's symbol (EPC069-12 v3.1), and what refuses one: decided
|
|
463
|
+
* here once, below every engine, as a QR code's is (`qr-symbol.ts`, 0074).
|
|
464
|
+
* Its payload as UTF-8 at level M, in a symbol of version 13 at most,
|
|
465
|
+
* which an engine encodes once, when it checks the document.
|
|
466
|
+
*
|
|
467
|
+
* Without a caption it is a QR code's symbol, in a square with a quiet
|
|
468
|
+
* zone of four modules inside it, held to the 0.4 mm floor. With
|
|
469
|
+
* Austria's caption it is the PSA's (PSA v3.0 5), by report-spec's
|
|
470
|
+
* `epc-print.ts`, the one place those rules are decided: modules of 15 to
|
|
471
|
+
* 20 mil, and a symbol as tall as the caption beside it. In a square the
|
|
472
|
+
* author sized, the version that just holds a payload may have modules
|
|
473
|
+
* over 20 mil: the symbol is the least version that prints there
|
|
474
|
+
* (`epcLeastVersion`), a larger symbol of the same payload at the same
|
|
475
|
+
* level.
|
|
476
|
+
*
|
|
477
|
+
* Every refusal names the code by its id, and none quotes the payload: it
|
|
478
|
+
* holds a name and an account.
|
|
479
|
+
*/
|
|
480
|
+
/**
|
|
481
|
+
* `code`'s symbol where it stands `width` points wide, or the refusal
|
|
482
|
+
* that says why it is not drawn: a square of no size, a caption no engine
|
|
483
|
+
* knows, or a payload that is not text, as `unsupported`; a square wider
|
|
484
|
+
* than where it stands, a payload past 331 bytes, refused unencoded when
|
|
485
|
+
* it is longer than that in characters, or modules the square cannot
|
|
486
|
+
* print, as `content-too-large`.
|
|
487
|
+
*/
|
|
488
|
+
function epcSymbol(code, width) {
|
|
489
|
+
const { id, payload, size, caption } = code;
|
|
490
|
+
const what = `the EPC QR code ${id}`;
|
|
491
|
+
refuseSquare(what, id, size, width);
|
|
492
|
+
if (caption !== void 0 && caption !== "zahlenMitCode") throw new RenderRefusal("unsupported", `${what} asks for the caption '${String(caption)}', which a report does not know`, id);
|
|
493
|
+
if (typeof payload !== "string") throw new RenderRefusal("unsupported", `${what} holds something that is not text`, id);
|
|
494
|
+
const lone = loneSurrogate(payload);
|
|
495
|
+
if (lone !== void 0) throw new RenderRefusal("unsupported", `${what} holds ${lone}, half of a surrogate pair without the other, which has no UTF-8`, id);
|
|
496
|
+
if (payload.length > EPC_MAX_BYTES$1) throw new RenderRefusal("content-too-large", `${what} holds more than the ${EPC_MAX_BYTES$1} bytes the EPC allows`, id);
|
|
497
|
+
const square = caption === void 0 ? void 0 : epcCaptionBreak$1(size);
|
|
498
|
+
if (square !== void 0) throw new RenderRefusal("content-too-large", `${what} cannot be printed as the PSA prints it: ${square}`, id);
|
|
499
|
+
const least = epcLeastVersion$1(size, caption);
|
|
500
|
+
let symbol;
|
|
501
|
+
try {
|
|
502
|
+
symbol = { modules: encode(payload, {
|
|
503
|
+
ecc: "M",
|
|
504
|
+
border: 0,
|
|
505
|
+
boostEcc: false,
|
|
506
|
+
minVersion: least,
|
|
507
|
+
maxVersion: EPC_MAX_VERSION$1
|
|
508
|
+
}).data };
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (!tooLong(error)) throw error;
|
|
511
|
+
throw new RenderRefusal("content-too-large", `${what} holds ${utf8Length(payload)} bytes, more than version ${EPC_MAX_VERSION$1} holds at level M, the largest code the EPC allows`, id);
|
|
512
|
+
}
|
|
513
|
+
if (caption === void 0) {
|
|
514
|
+
refuseFineModules(symbol, size, what, "its payload", id);
|
|
515
|
+
return symbol;
|
|
516
|
+
}
|
|
517
|
+
const version = epcCaptionBreak$1(size, qrSymbolVersion(symbol));
|
|
518
|
+
if (version !== void 0) throw new RenderRefusal("content-too-large", `${what} cannot be printed as the PSA prints it: ${version}`, id);
|
|
519
|
+
return symbol;
|
|
520
|
+
}
|
|
521
|
+
// src/input.ts
|
|
37
522
|
/** Stands in a read list where an item could not be read; its problem says why. */
|
|
38
523
|
const UNREADABLE = Symbol("unreadable");
|
|
39
524
|
const ACCESSOR = "a getter or setter is not data, and is not run";
|
|
@@ -140,8 +625,7 @@ function readList(value, max) {
|
|
|
140
625
|
};
|
|
141
626
|
}
|
|
142
627
|
}
|
|
143
|
-
|
|
144
|
-
//#region src/values.ts
|
|
628
|
+
// src/values.ts
|
|
145
629
|
/**
|
|
146
630
|
* One value read as the type a dataset field or a parameter declares, and
|
|
147
631
|
* held as the runtime computes with it.
|
|
@@ -209,7 +693,7 @@ function wrongType(expected, raw) {
|
|
|
209
693
|
/** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */
|
|
210
694
|
const INTEGER = /^(?:0|-?[1-9]\d*)$/;
|
|
211
695
|
/** An exact decimal: an integer, optionally a point and at least one digit; no negative zero (report-spec's `DECIMAL`). */
|
|
212
|
-
const DECIMAL = /^(?:-?[1-9]\d*(?:\.\d+)?|0(?:\.\d+)?|-0
|
|
696
|
+
const DECIMAL = /^(?:-?[1-9]\d*(?:\.\d+)?|0(?:\.\d+)?|-0\.0*[1-9]\d*)$/;
|
|
213
697
|
/** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */
|
|
214
698
|
const DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
215
699
|
/** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */
|
|
@@ -283,7 +767,7 @@ function readDecimal(raw, scale) {
|
|
|
283
767
|
if (typeof raw !== "string") return wrongType("a decimal, written as a string of its exact digits", raw);
|
|
284
768
|
if (raw.length > MAX_STRING_LENGTH || !DECIMAL.test(raw)) return refused$1("invalid-decimal", "a decimal is written as its digits, with \".\" before any places, \"-\" for a negative one, no leading zero and no \"-0\"");
|
|
285
769
|
const places = raw.length - raw.indexOf(".") - 1;
|
|
286
|
-
const allowed = scale ?? MAX_SCALE;
|
|
770
|
+
const allowed = scale ?? MAX_SCALE$1;
|
|
287
771
|
if (raw.includes(".") && places > allowed) return refused$1("decimal-scale", `a decimal with ${places} places, more than the ${allowed} ${scale === void 0 ? "a decimal holds" : "the field declares"}; rounding it here would print another number than the source holds`);
|
|
288
772
|
return {
|
|
289
773
|
ok: true,
|
|
@@ -387,8 +871,7 @@ const READERS = {
|
|
|
387
871
|
instant: readInstant,
|
|
388
872
|
image: readImage
|
|
389
873
|
};
|
|
390
|
-
|
|
391
|
-
//#region src/data-errors.ts
|
|
874
|
+
// src/data-errors.ts
|
|
392
875
|
/**
|
|
393
876
|
* What the runtime can say is wrong with the data and parameters it is
|
|
394
877
|
* given, as stable codes, and the bounded list one check collects.
|
|
@@ -412,6 +895,8 @@ const DATA_ERROR_CODES = [
|
|
|
412
895
|
"completeness-mismatch",
|
|
413
896
|
"invalid-completeness",
|
|
414
897
|
"invalid-consistency",
|
|
898
|
+
"invalid-source",
|
|
899
|
+
"labels-locale-differs",
|
|
415
900
|
"missing-parameter",
|
|
416
901
|
"undeclared-parameter",
|
|
417
902
|
"too-many-errors"
|
|
@@ -465,8 +950,245 @@ function isLongKey(key) {
|
|
|
465
950
|
function keyAt(path, key) {
|
|
466
951
|
return isLongKey(key) ? path : at(path, key);
|
|
467
952
|
}
|
|
468
|
-
|
|
469
|
-
|
|
953
|
+
// src/languages.ts
|
|
954
|
+
/**
|
|
955
|
+
* The locale a render of `report` prints in -- `requested`, or the
|
|
956
|
+
* report's own where nothing is requested -- or the error that refuses
|
|
957
|
+
* it: `undeclared-locale`, at the options, naming the locales the report
|
|
958
|
+
* is written in. `requested` is the host's, whatever its type says.
|
|
959
|
+
*/
|
|
960
|
+
function printLocale(report, requested) {
|
|
961
|
+
const choice = requested === void 0 || typeof requested === "string" ? renderLocale(report, requested) : {
|
|
962
|
+
ok: false,
|
|
963
|
+
message: `a render names its locale as a tag; this report is written in ${declaredLocales(report).join(", ")}`
|
|
964
|
+
};
|
|
965
|
+
return choice.ok ? choice : {
|
|
966
|
+
ok: false,
|
|
967
|
+
error: {
|
|
968
|
+
stage: "resolve",
|
|
969
|
+
code: "undeclared-locale",
|
|
970
|
+
path: "",
|
|
971
|
+
message: choice.message
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
/** Whether `diagnostic` refuses a render in `locale`: an error that names no language refuses every render, one that names a language a render in it alone. */
|
|
976
|
+
const refuses = (diagnostic, locale) => diagnostic.severity === "error" && (diagnostic.language === void 0 || diagnostic.language === locale);
|
|
977
|
+
/** Where `locale`, one `report` is written in, stands in it: the report's own at `/locale`, a translation's at the translation that declares it. */
|
|
978
|
+
function localePath(report, locale) {
|
|
979
|
+
const index = (report.translations ?? []).findIndex((translation) => translation.locale === locale);
|
|
980
|
+
return index === -1 ? "/locale" : `/translations/${index}/locale`;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Reports form data whose labels were read in another locale than
|
|
984
|
+
* `printed`, the one the render prints in: a source that names none was
|
|
985
|
+
* read in `own`, the report's own. Data of no form, or of Formancy Data,
|
|
986
|
+
* holds no label of a form's.
|
|
987
|
+
*/
|
|
988
|
+
function checkLabels(errors, source, own, printed) {
|
|
989
|
+
if (source?.provider !== "formancy-form" || (source.locale ?? own) === printed) return;
|
|
990
|
+
const read = source.locale === void 0 ? "the report's own locale" : "another locale";
|
|
991
|
+
errors.report(source.locale === void 0 ? "/source" : "/source/locale", "labels-locale-differs", `the form's labels were read in ${read}, and this render prints in ${printed}: read them again in ${printed}, or render in the locale they were read in, since labels are never printed in a language the render does not name`);
|
|
992
|
+
}
|
|
993
|
+
// src/source.ts
|
|
994
|
+
/**
|
|
995
|
+
* Where a report's data came from, as its provider names it, and the check
|
|
996
|
+
* that admits it (0041). The render's manifest carries it, so that a PDF
|
|
997
|
+
* kept for years can be traced to what collected its data: plan 13.2's
|
|
998
|
+
* identity and provenance, as far as identifiers say them.
|
|
999
|
+
*
|
|
1000
|
+
* - **A formancy form**: each submission the data was read from, with the
|
|
1001
|
+
* form's id and the `schemaHash` of the version that collected it -- one
|
|
1002
|
+
* for a report of one submission, one a row for a report of many,
|
|
1003
|
+
* whatever versions they answered. The form's id is a submission's too,
|
|
1004
|
+
* since formancy lets a new version change it. And the locale a
|
|
1005
|
+
* choice's labels were read in, where it is not the report's own (0063).
|
|
1006
|
+
* - **Formancy Data**: the published form each dataset was read from. Never
|
|
1007
|
+
* a record's token, which spells the record's key (formancy.ai-data
|
|
1008
|
+
* 0012), and a key can be the customer's own data.
|
|
1009
|
+
*
|
|
1010
|
+
* A source names identifiers and nothing else. It is held to their syntax,
|
|
1011
|
+
* bounded in count and length, and refused rather than cut short; a key
|
|
1012
|
+
* its shape does not name is refused by its container's path, since the
|
|
1013
|
+
* key may be the answer, and a provider the runtime does not know is
|
|
1014
|
+
* refused, never read as one it does. The syntax keeps out a space, an
|
|
1015
|
+
* `@`, a `/`, a `:`, a letter beyond ASCII and anything past 128
|
|
1016
|
+
* characters; it cannot tell a single word, a personal number or a digest
|
|
1017
|
+
* of an answer from an identifier, which 0041 says is its cost. Whether a
|
|
1018
|
+
* source is true -- that the host read what it names -- is the provider's
|
|
1019
|
+
* statement, as its completeness is; the runtime holds its form.
|
|
1020
|
+
*
|
|
1021
|
+
* As `data.ts` does, the check reports every problem and returns what it
|
|
1022
|
+
* read; `checkData` refuses the data when any was reported, so what a
|
|
1023
|
+
* render keeps is a source read whole.
|
|
1024
|
+
*/
|
|
1025
|
+
/** Who handed the data over: a formancy form's submissions, or Formancy Data's forms. */
|
|
1026
|
+
const SOURCE_PROVIDERS = ["formancy-form", "formancy-data"];
|
|
1027
|
+
const ROLES = ["header", "detail"];
|
|
1028
|
+
/** The characters a form's id and a submission's may hold, as a refusal says them. */
|
|
1029
|
+
const ID_SYNTAX = "letters, digits, '.', '_' and '-', starting with a letter or a digit, at most 128 characters";
|
|
1030
|
+
/**
|
|
1031
|
+
* A submission's id. The same characters as a form's id, by choice and not
|
|
1032
|
+
* by rule: report-spec's `FORM_ID` is formancy's syntax for a form, which
|
|
1033
|
+
* formancy may change, and a submission's id is the host's, which formancy's
|
|
1034
|
+
* server makes as a UUID. A UUID, a ULID or a number fits, and so does a
|
|
1035
|
+
* single word or a personal number, which a syntax cannot tell from an id.
|
|
1036
|
+
*/
|
|
1037
|
+
const SUBMISSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
1038
|
+
/**
|
|
1039
|
+
* Whether `value` is a submission's id as a source names one: what the form
|
|
1040
|
+
* bridge holds an id to before it reads a submission, so that the two
|
|
1041
|
+
* cannot read an id differently (0042).
|
|
1042
|
+
*/
|
|
1043
|
+
function isSubmissionId(value) {
|
|
1044
|
+
return typeof value === "string" && SUBMISSION_ID.test(value);
|
|
1045
|
+
}
|
|
1046
|
+
/** What `isSubmissionId` accepts, in the words a refusal says it: the form bridge says them when it refuses an id, so the two cannot describe one rule two ways. */
|
|
1047
|
+
const SUBMISSION_ID_SYNTAX = ID_SYNTAX;
|
|
1048
|
+
const FORM_ID = `a form's id as formancy writes one: ${ID_SYNTAX}`;
|
|
1049
|
+
const NOTHING_ELSE = "and nothing else: a source names identifiers, and no answer rides into the manifest a PDF is kept with";
|
|
1050
|
+
const SUBMISSION = "a submission is { \"id\": its id, \"form\": the form's id, \"formHash\": the schemaHash of the version that collected it }";
|
|
1051
|
+
/** What each provider's source names besides its provider. */
|
|
1052
|
+
const NAMES = {
|
|
1053
|
+
"formancy-form": ["submissions", "locale"],
|
|
1054
|
+
"formancy-data": ["forms"]
|
|
1055
|
+
};
|
|
1056
|
+
/** What each provider's source names, as a refusal says it. */
|
|
1057
|
+
const SHAPES = {
|
|
1058
|
+
"formancy-form": "a formancy-form source names submissions, and the locale its labels were read in where that is not the report's own",
|
|
1059
|
+
"formancy-data": "a formancy-data source names forms"
|
|
1060
|
+
};
|
|
1061
|
+
/** A container that could not be read, as a source's error: what is not data stays `not-data`. */
|
|
1062
|
+
const container = (code) => code === "not-data" ? "not-data" : "invalid-source";
|
|
1063
|
+
/**
|
|
1064
|
+
* Reports a record's properties that are not data: a key of `known` where
|
|
1065
|
+
* it stands, any other by the record's own path, since a key the shape
|
|
1066
|
+
* does not name may be the answer. Returns the known keys reported.
|
|
1067
|
+
*/
|
|
1068
|
+
function notData(errors, path, problems, known) {
|
|
1069
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1070
|
+
for (const { key, message } of problems) {
|
|
1071
|
+
const named = key !== void 0 && known.includes(key);
|
|
1072
|
+
if (named) keys.add(key);
|
|
1073
|
+
errors.report(named ? at(path, key) : path, "not-data", message);
|
|
1074
|
+
}
|
|
1075
|
+
return keys;
|
|
1076
|
+
}
|
|
1077
|
+
/** Refuses, once and by the record's own path, the keys of `entries` that `known` does not hold. */
|
|
1078
|
+
function onlyKnown(errors, path, entries, known, shape) {
|
|
1079
|
+
if ([...entries.keys()].some((key) => !known.includes(key))) errors.report(path, "invalid-source", `${shape}, ${NOTHING_ELSE}`);
|
|
1080
|
+
}
|
|
1081
|
+
/** One submission, or undefined when it cannot be read at all; `seen` holds the ids read before it. */
|
|
1082
|
+
function readSubmission(errors, raw, path, seen) {
|
|
1083
|
+
const read = readRecord(raw);
|
|
1084
|
+
if (!read.ok) {
|
|
1085
|
+
errors.report(path, container(read.code), SUBMISSION);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
const known = [
|
|
1089
|
+
"id",
|
|
1090
|
+
"form",
|
|
1091
|
+
"formHash"
|
|
1092
|
+
];
|
|
1093
|
+
const unreadable = notData(errors, path, read.problems, known);
|
|
1094
|
+
onlyKnown(errors, path, read.entries, known, SUBMISSION);
|
|
1095
|
+
const [id, form, formHash] = known.map((key) => read.entries.get(key));
|
|
1096
|
+
if (!unreadable.has("id")) {
|
|
1097
|
+
if (!isSubmissionId(id)) errors.report(at(path, "id"), "invalid-source", `a submission's id: ${ID_SYNTAX}; never a name, an address or an answer`);
|
|
1098
|
+
else if (seen.has(id)) errors.report(at(path, "id"), "invalid-source", "a source names each submission once, and an earlier entry names this one");
|
|
1099
|
+
else seen.add(id);
|
|
1100
|
+
}
|
|
1101
|
+
if (!unreadable.has("form") && !isFormId(form)) errors.report(at(path, "form"), "invalid-source", `the form the submission answered: ${FORM_ID}`);
|
|
1102
|
+
if (!unreadable.has("formHash") && !isSchemaHash(formHash)) errors.report(at(path, "formHash"), "invalid-source", "the schemaHash of the form version that collected the submission: 64 lower-case hex digits");
|
|
1103
|
+
return Object.freeze({
|
|
1104
|
+
id,
|
|
1105
|
+
form,
|
|
1106
|
+
formHash
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
/** A formancy form's source: each submission, read after the bound is checked. */
|
|
1110
|
+
function readFormSource(errors, entries, max) {
|
|
1111
|
+
const list = readList(entries.get("submissions"), max);
|
|
1112
|
+
if (!list.ok) {
|
|
1113
|
+
const message = list.code === "too-many" ? `${list.message}: a source names no more submissions than the data gives detail rows, or one where it gives none, since a report of one submission reads its repeater's rows and a report of many one a row` : "submissions is a list of { \"id\", \"form\", \"formHash\" }, one for each submission the data was read from";
|
|
1114
|
+
errors.report("/source/submissions", container(list.code), message);
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
if (list.items.length === 0) errors.report("/source/submissions", "invalid-source", "a form source names at least one submission the data was read from");
|
|
1118
|
+
const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]));
|
|
1119
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1120
|
+
const submissions = [];
|
|
1121
|
+
for (const [index, item] of list.items.entries()) {
|
|
1122
|
+
if (errors.full) break;
|
|
1123
|
+
const path = at("/source/submissions", index);
|
|
1124
|
+
if (item === UNREADABLE) {
|
|
1125
|
+
errors.report(path, "not-data", unreadable.get(index));
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
const submission = readSubmission(errors, item, path, seen);
|
|
1129
|
+
if (submission !== void 0) submissions.push(submission);
|
|
1130
|
+
}
|
|
1131
|
+
const locale = entries.get("locale");
|
|
1132
|
+
if (entries.has("locale") && !isLocale(locale)) errors.report("/source/locale", "invalid-source", "the locale the form's labels were read in, as a report writes its locale: a BCP 47 tag such as fr-CH");
|
|
1133
|
+
return Object.freeze({
|
|
1134
|
+
provider: "formancy-form",
|
|
1135
|
+
submissions: Object.freeze(submissions),
|
|
1136
|
+
...isLocale(locale) ? { locale } : {}
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
/** Formancy Data's source: a form for each dataset the report declares, for no other, and at least one. */
|
|
1140
|
+
function readDataSource(errors, entries, datasets) {
|
|
1141
|
+
const read = readRecord(entries.get("forms"));
|
|
1142
|
+
if (!read.ok) {
|
|
1143
|
+
errors.report("/source/forms", container(read.code), "forms is { \"header\", \"detail\" }: the published form each dataset the report declares was read from");
|
|
1144
|
+
return;
|
|
1145
|
+
}
|
|
1146
|
+
const unreadable = notData(errors, "/source/forms", read.problems, ROLES);
|
|
1147
|
+
if (read.entries.size === 0 && read.problems.length === 0) {
|
|
1148
|
+
errors.report("/source/forms", "invalid-source", "a Formancy Data source names the form each dataset was read from, and data read from no form names no source");
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
onlyKnown(errors, "/source/forms", read.entries, ROLES, "forms is keyed by the datasets a report declares, header and detail");
|
|
1152
|
+
for (const role of ROLES) {
|
|
1153
|
+
if (unreadable.has(role)) continue;
|
|
1154
|
+
const declared = datasets[role] !== void 0;
|
|
1155
|
+
if (!read.entries.has(role)) {
|
|
1156
|
+
if (declared) errors.report("/source/forms", "invalid-source", `the report declares a ${role} dataset, and the source names no form it was read from`);
|
|
1157
|
+
} else if (!declared) errors.report(at("/source/forms", role), "invalid-source", `the report declares no ${role} dataset, so none was read from a form`);
|
|
1158
|
+
else if (!isFormId(read.entries.get(role))) errors.report(at("/source/forms", role), "invalid-source", `the published form the ${role} dataset was read from: ${FORM_ID}`);
|
|
1159
|
+
}
|
|
1160
|
+
const forms = Object.fromEntries(ROLES.filter((role) => read.entries.has(role)).map((role) => [role, read.entries.get(role)]));
|
|
1161
|
+
return Object.freeze({
|
|
1162
|
+
provider: "formancy-data",
|
|
1163
|
+
forms: Object.freeze(forms)
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* The source `raw` names, held to its provider's shape and to `datasets`,
|
|
1168
|
+
* as a frozen copy, with every problem reported to `errors`; undefined when
|
|
1169
|
+
* it cannot be read at all. No more than `maxSubmissions` submissions are
|
|
1170
|
+
* read, and a list past it is refused before any of its items is.
|
|
1171
|
+
*/
|
|
1172
|
+
function checkSource(errors, raw, datasets, maxSubmissions) {
|
|
1173
|
+
const shape = `a source is { "provider": one of ${SOURCE_PROVIDERS.map((provider) => `"${provider}"`).join(", ")}, and what that provider names }`;
|
|
1174
|
+
const read = readRecord(raw);
|
|
1175
|
+
if (!read.ok) {
|
|
1176
|
+
errors.report("/source", container(read.code), shape);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
const unreadable = notData(errors, "/source", read.problems, ["provider", ...new Set(Object.values(NAMES).flat())]);
|
|
1180
|
+
if (unreadable.has("provider")) return void 0;
|
|
1181
|
+
const provider = SOURCE_PROVIDERS.find((each) => each === read.entries.get("provider"));
|
|
1182
|
+
if (provider === void 0) {
|
|
1183
|
+
errors.report("/source/provider", "invalid-source", shape);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
const names = NAMES[provider];
|
|
1187
|
+
onlyKnown(errors, "/source", read.entries, ["provider", ...names], SHAPES[provider]);
|
|
1188
|
+
if (names.some((name) => unreadable.has(name))) return void 0;
|
|
1189
|
+
return provider === "formancy-form" ? readFormSource(errors, read.entries, maxSubmissions) : readDataSource(errors, read.entries, datasets);
|
|
1190
|
+
}
|
|
1191
|
+
// src/data.ts
|
|
470
1192
|
/**
|
|
471
1193
|
* The data a report is rendered from, and the check that admits it.
|
|
472
1194
|
*
|
|
@@ -492,6 +1214,12 @@ function keyAt(path, key) {
|
|
|
492
1214
|
* that disagrees with the rows given.
|
|
493
1215
|
* - **Bounded.** The rows and every string are bounded before they are
|
|
494
1216
|
* read, and so is the error list; once it is full, nothing more is read.
|
|
1217
|
+
* - **Its source, by the syntax of identifiers.** Where the provider names
|
|
1218
|
+
* where the data came from -- a formancy form's submissions and their
|
|
1219
|
+
* versions, or Formancy Data's forms -- it is held to `source.ts`'s
|
|
1220
|
+
* rules, no more submissions than the rows given, and the render's
|
|
1221
|
+
* manifest carries it (0041). A formancy form's labels were read in the
|
|
1222
|
+
* locale the report prints in, or are refused (0063).
|
|
495
1223
|
*
|
|
496
1224
|
* What is held afterwards is a frozen copy, read once from the host's
|
|
497
1225
|
* objects, which no later change to them reaches.
|
|
@@ -525,7 +1253,8 @@ const ENVELOPE = [
|
|
|
525
1253
|
"header",
|
|
526
1254
|
"detail",
|
|
527
1255
|
"completeness",
|
|
528
|
-
"consistency"
|
|
1256
|
+
"consistency",
|
|
1257
|
+
"source"
|
|
529
1258
|
];
|
|
530
1259
|
const COMPLETENESS = [
|
|
531
1260
|
"complete",
|
|
@@ -730,6 +1459,10 @@ function checkData(report, data, options) {
|
|
|
730
1459
|
const detail = checkDetail(c, report.datasets.detail, top.entries);
|
|
731
1460
|
const completeness = checkCompleteness(c, top.entries.get("completeness"), detail.given);
|
|
732
1461
|
const consistency = checkConsistency(c, top.entries.get("consistency"));
|
|
1462
|
+
const rows = top.entries.has("detail") ? detail.given : 0;
|
|
1463
|
+
const submissions = rows === void 0 ? MAX_DETAIL_ROWS : Math.max(1, rows);
|
|
1464
|
+
const source = top.entries.has("source") ? checkSource(c.errors, top.entries.get("source"), report.datasets, submissions) : void 0;
|
|
1465
|
+
checkLabels(c.errors, source, options.reportLocale ?? report.locale, report.locale);
|
|
733
1466
|
if (!c.errors.empty || completeness === void 0 || consistency === void 0) return {
|
|
734
1467
|
ok: false,
|
|
735
1468
|
errors: c.errors.errors()
|
|
@@ -739,7 +1472,8 @@ function checkData(report, data, options) {
|
|
|
739
1472
|
...header === void 0 ? {} : { header },
|
|
740
1473
|
detail: Object.freeze(detail.rows),
|
|
741
1474
|
completeness,
|
|
742
|
-
consistency
|
|
1475
|
+
consistency,
|
|
1476
|
+
...source === void 0 ? {} : { source }
|
|
743
1477
|
};
|
|
744
1478
|
return {
|
|
745
1479
|
ok: true,
|
|
@@ -747,8 +1481,7 @@ function checkData(report, data, options) {
|
|
|
747
1481
|
warnings: c.warnings
|
|
748
1482
|
};
|
|
749
1483
|
}
|
|
750
|
-
|
|
751
|
-
//#region src/parameters.ts
|
|
1484
|
+
// src/parameters.ts
|
|
752
1485
|
/**
|
|
753
1486
|
* The values a person supplies before rendering, held to the report's
|
|
754
1487
|
* parameters.
|
|
@@ -842,8 +1575,7 @@ function checkParameters(report, values) {
|
|
|
842
1575
|
values: Object.freeze(checked)
|
|
843
1576
|
};
|
|
844
1577
|
}
|
|
845
|
-
|
|
846
|
-
//#region src/decimal.ts
|
|
1578
|
+
// src/decimal.ts
|
|
847
1579
|
/**
|
|
848
1580
|
* Exact totals and declared rounding, over `@formancy/expressions`'
|
|
849
1581
|
* `Decimal`: a value as an integer of units at a scale, so that nothing here
|
|
@@ -888,6 +1620,11 @@ function roundRatio(numerator, denominator, rounding) {
|
|
|
888
1620
|
const steps = roundQuotient(numerator * 10n ** BigInt(step.scale), denominator * step.units, rounding.mode);
|
|
889
1621
|
return new Decimal(steps * step.units * 10n ** BigInt(rounding.scale - step.scale), rounding.scale);
|
|
890
1622
|
}
|
|
1623
|
+
/** The exact ratio of two decimals rounded once as `rounding` declares: a share, never computed through a double. Throws a RangeError for a denominator of 0 or less, which `roundQuotient` does not divide by. */
|
|
1624
|
+
function ratioRounded(numerator, denominator, rounding) {
|
|
1625
|
+
if (denominator.units <= 0n) throw new RangeError("a ratio is of a denominator more than 0");
|
|
1626
|
+
return roundRatio(numerator.units * 10n ** BigInt(denominator.scale), denominator.units * 10n ** BigInt(numerator.scale), rounding);
|
|
1627
|
+
}
|
|
891
1628
|
/**
|
|
892
1629
|
* `value` rounded as `rounding` declares, at exactly its scale. A negative
|
|
893
1630
|
* value that rounds to nothing is zero, never minus zero. Throws a
|
|
@@ -931,8 +1668,7 @@ function averageDecimals(values, rounding) {
|
|
|
931
1668
|
}
|
|
932
1669
|
return count === 0n ? null : roundRatio(total.units, count * 10n ** BigInt(total.scale), rounding);
|
|
933
1670
|
}
|
|
934
|
-
|
|
935
|
-
//#region src/format.ts
|
|
1671
|
+
// src/format.ts
|
|
936
1672
|
/**
|
|
937
1673
|
* A value as the text a report prints, for the report's locale: report-spec's
|
|
938
1674
|
* number, currency, date and text formats, through Intl.
|
|
@@ -944,7 +1680,9 @@ function averageDecimals(values, rounding) {
|
|
|
944
1680
|
* handed a double and never rounds. Up to a bound: ECMA-402 reads a
|
|
945
1681
|
* string whose double would be infinite as infinity, and prints '∞'. A
|
|
946
1682
|
* number with more than `MAX_FORMATTED_DIGITS` integer digits is refused
|
|
947
|
-
* instead; printed without a format, it prints whole.
|
|
1683
|
+
* instead; printed without a format, it prints whole. `percent` is held
|
|
1684
|
+
* to both: a share at more places than it keeps is refused, never rounded
|
|
1685
|
+
* by Intl.
|
|
948
1686
|
* - **The locale's conventions.** Grouping, separators, currency symbols,
|
|
949
1687
|
* month names and case are the locale's, as the engine's ICU has them.
|
|
950
1688
|
* ICU versions can differ -- which mark Swiss German groups digits with is
|
|
@@ -967,7 +1705,8 @@ const FORMAT_ERROR_CODES = [
|
|
|
967
1705
|
"format-type-mismatch",
|
|
968
1706
|
"no-currency",
|
|
969
1707
|
"invalid-currency",
|
|
970
|
-
"number-too-large"
|
|
1708
|
+
"number-too-large",
|
|
1709
|
+
"percent-rounds-again"
|
|
971
1710
|
];
|
|
972
1711
|
/**
|
|
973
1712
|
* The most integer digits a number or currency format prints: 308. A double
|
|
@@ -976,6 +1715,10 @@ const FORMAT_ERROR_CODES = [
|
|
|
976
1715
|
* number of 308 digits or fewer prints exactly and one of 309 may not.
|
|
977
1716
|
*/
|
|
978
1717
|
const MAX_FORMATTED_DIGITS = 308;
|
|
1718
|
+
/** Whether `digits`, a number as `decimalToString` writes it, has more integer digits than Intl prints: it would print them as infinity. */
|
|
1719
|
+
const tooManyDigits = (digits) => digits.replace(/^-/, "").split(".")[0].length > 308;
|
|
1720
|
+
/** A count of places as a message says it: "1 place", "3 places". */
|
|
1721
|
+
const placesOf = (count) => `${count} ${count === 1 ? "place" : "places"}`;
|
|
979
1722
|
function refused(code, message) {
|
|
980
1723
|
return {
|
|
981
1724
|
ok: false,
|
|
@@ -1078,7 +1821,7 @@ function currencyOf(source, scope) {
|
|
|
1078
1821
|
return refused("invalid-currency", `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`);
|
|
1079
1822
|
}
|
|
1080
1823
|
/** The Intl formatter `cache` keeps for `options`, made by `make` the first time they are asked for: a table formats a column with one. */
|
|
1081
|
-
function kept(cache, options, make) {
|
|
1824
|
+
function kept$1(cache, options, make) {
|
|
1082
1825
|
const key = JSON.stringify(options);
|
|
1083
1826
|
const found = cache.get(key);
|
|
1084
1827
|
if (found !== void 0) return found;
|
|
@@ -1114,6 +1857,20 @@ var LocaleFormatter = class {
|
|
|
1114
1857
|
default: return this.#number(value, format, scope);
|
|
1115
1858
|
}
|
|
1116
1859
|
}
|
|
1860
|
+
percent(fraction, places) {
|
|
1861
|
+
if (fraction.scale > places + 2) return refused("percent-rounds-again", `a share of ${placesOf(fraction.scale)}, printed as a percentage at ${placesOf(places)}, would be rounded again by Intl; round it to ${placesOf(places + 2)} first`);
|
|
1862
|
+
const digits = decimalToString(fraction);
|
|
1863
|
+
if (tooManyDigits(digits)) return refused("number-too-large", `a share of more than 308 integer digits, which Intl would print as infinity`);
|
|
1864
|
+
const options = {
|
|
1865
|
+
style: "percent",
|
|
1866
|
+
minimumFractionDigits: places,
|
|
1867
|
+
maximumFractionDigits: places
|
|
1868
|
+
};
|
|
1869
|
+
return {
|
|
1870
|
+
ok: true,
|
|
1871
|
+
text: kept$1(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(digits)
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1117
1874
|
#transformed(text, transform) {
|
|
1118
1875
|
if (transform === "upper") return text.toLocaleUpperCase(this.locale);
|
|
1119
1876
|
return transform === "lower" ? text.toLocaleLowerCase(this.locale) : text;
|
|
@@ -1127,7 +1884,7 @@ var LocaleFormatter = class {
|
|
|
1127
1884
|
scale: format.scale,
|
|
1128
1885
|
mode: "half-away-from-zero"
|
|
1129
1886
|
}));
|
|
1130
|
-
if (rounded
|
|
1887
|
+
if (tooManyDigits(rounded)) return refused("number-too-large", `a number of more than 308 digits, which Intl would print as infinity; printed without a format, it prints whole`);
|
|
1131
1888
|
const options = {
|
|
1132
1889
|
minimumFractionDigits: format.scale,
|
|
1133
1890
|
maximumFractionDigits: format.scale,
|
|
@@ -1138,7 +1895,7 @@ var LocaleFormatter = class {
|
|
|
1138
1895
|
};
|
|
1139
1896
|
return {
|
|
1140
1897
|
ok: true,
|
|
1141
|
-
text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded)
|
|
1898
|
+
text: kept$1(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded)
|
|
1142
1899
|
};
|
|
1143
1900
|
}
|
|
1144
1901
|
#date(value, style) {
|
|
@@ -1151,7 +1908,7 @@ var LocaleFormatter = class {
|
|
|
1151
1908
|
};
|
|
1152
1909
|
return {
|
|
1153
1910
|
ok: true,
|
|
1154
|
-
text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs)
|
|
1911
|
+
text: kept$1(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs)
|
|
1155
1912
|
};
|
|
1156
1913
|
}
|
|
1157
1914
|
};
|
|
@@ -1172,8 +1929,7 @@ function createFormatter(context) {
|
|
|
1172
1929
|
formatter: new LocaleFormatter(context)
|
|
1173
1930
|
};
|
|
1174
1931
|
}
|
|
1175
|
-
|
|
1176
|
-
//#region src/sort-group.ts
|
|
1932
|
+
// src/sort-group.ts
|
|
1177
1933
|
/**
|
|
1178
1934
|
* The order of a table's rows and its groups, decided once, here (0007).
|
|
1179
1935
|
*
|
|
@@ -1258,6 +2014,23 @@ function sameKey(type, a, b) {
|
|
|
1258
2014
|
return type === "decimal" ? compareDecimal(a, b) === 0 : a === b;
|
|
1259
2015
|
}
|
|
1260
2016
|
/**
|
|
2017
|
+
* One value a Map can find a group key by: equal for two keys of a type
|
|
2018
|
+
* exactly when `sameKey` holds them one (a test holds the two to each other).
|
|
2019
|
+
* A decimal is normalised -- trailing zeros stripped while it has a scale (zero ends at 0),
|
|
2020
|
+
* so 1.0 and 1.00 meet; text, integers and booleans are
|
|
2021
|
+
* their own keys, which a Map compares by value; null is null.
|
|
2022
|
+
*/
|
|
2023
|
+
function canonicalKey(type, value) {
|
|
2024
|
+
if (value === null) return null;
|
|
2025
|
+
if (type !== "decimal") return value;
|
|
2026
|
+
let { units, scale } = value;
|
|
2027
|
+
while (scale > 0 && units % 10n === 0n) {
|
|
2028
|
+
units /= 10n;
|
|
2029
|
+
scale -= 1;
|
|
2030
|
+
}
|
|
2031
|
+
return `${units}/${scale}`;
|
|
2032
|
+
}
|
|
2033
|
+
/**
|
|
1261
2034
|
* Rows already in order, as consecutive groups of equal keys: the groups in
|
|
1262
2035
|
* the order of their rows, each keyed by its first row's value. A missing
|
|
1263
2036
|
* value groups with null.
|
|
@@ -1279,6 +2052,37 @@ function groupRows(rows, by) {
|
|
|
1279
2052
|
}));
|
|
1280
2053
|
}
|
|
1281
2054
|
/**
|
|
2055
|
+
* A chart's categories, grouped as a table's rows are: sorted by the
|
|
2056
|
+
* category's key, nulls last, then grouped; or, in the data's order, each
|
|
2057
|
+
* distinct key once at its first row's place, holding every row with that
|
|
2058
|
+
* key in the provider's order. Rows without a category are one group.
|
|
2059
|
+
*/
|
|
2060
|
+
function categoryGroups(rows, by, order, locale) {
|
|
2061
|
+
if (order !== "data") return groupRows(orderRows(rows, [{
|
|
2062
|
+
...by,
|
|
2063
|
+
direction: order
|
|
2064
|
+
}], locale), by);
|
|
2065
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2066
|
+
for (const [index, record] of rows.entries()) {
|
|
2067
|
+
const value = record[by.field] ?? null;
|
|
2068
|
+
const row = Object.freeze({
|
|
2069
|
+
index,
|
|
2070
|
+
record
|
|
2071
|
+
});
|
|
2072
|
+
const id = canonicalKey(by.type, value);
|
|
2073
|
+
const found = groups.get(id);
|
|
2074
|
+
if (found !== void 0) found.rows.push(row);
|
|
2075
|
+
else groups.set(id, {
|
|
2076
|
+
key: value,
|
|
2077
|
+
rows: [row]
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
return [...groups.values()].map((group) => Object.freeze({
|
|
2081
|
+
key: group.key,
|
|
2082
|
+
rows: Object.freeze(group.rows)
|
|
2083
|
+
}));
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
1282
2086
|
* The keys `table` orders its rows by: its group's key first, then its sort
|
|
1283
2087
|
* keys (0007), each typed by the report's detail contract. Throws a
|
|
1284
2088
|
* RangeError for a key on a field that has no order -- an image, or one the
|
|
@@ -1297,252 +2101,105 @@ function orderKeys(report, table) {
|
|
|
1297
2101
|
};
|
|
1298
2102
|
return [...table.group === void 0 ? [] : [typed(table.group.by.field, table.group.direction)], ...(table.sort ?? []).map(({ field, direction }) => typed(field.field, direction))];
|
|
1299
2103
|
}
|
|
1300
|
-
/** `
|
|
1301
|
-
function
|
|
2104
|
+
/** `selected`, in the data's order, as `orderRows` orders them: each the very row selected, at its index in the data, not in the selection. */
|
|
2105
|
+
function selectedInOrder(selected, keys, locale) {
|
|
2106
|
+
return orderRows(selected.map(({ record }) => record), keys, locale).map(({ index }) => selected[index]);
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* `detail` -- the report's checked detail rows -- in `table`'s order, and in
|
|
2110
|
+
* its groups when it has one. Given `selected`, the rows a table's
|
|
2111
|
+
* condition selected, in the data's order (0062), those alone, each still
|
|
2112
|
+
* at its index in `detail`: a total over a group reads a row's value by
|
|
2113
|
+
* that index, and an error names the row by it. Ties keep the data's order
|
|
2114
|
+
* among them.
|
|
2115
|
+
*/
|
|
2116
|
+
function orderTable(report, table, detail, selected) {
|
|
1302
2117
|
const keys = orderKeys(report, table);
|
|
1303
|
-
const rows = orderRows(detail, keys, report.locale);
|
|
2118
|
+
const rows = selected === void 0 ? orderRows(detail, keys, report.locale) : selectedInOrder(selected, keys, report.locale);
|
|
1304
2119
|
if (table.group === void 0) return { rows };
|
|
1305
2120
|
return {
|
|
1306
2121
|
rows,
|
|
1307
2122
|
groups: groupRows(rows, keys[0])
|
|
1308
2123
|
};
|
|
1309
2124
|
}
|
|
1310
|
-
|
|
1311
|
-
//#region src/evaluate.ts
|
|
2125
|
+
// src/chart-ticks.ts
|
|
1312
2126
|
/**
|
|
1313
|
-
* A
|
|
1314
|
-
* within a budget, each failure an error that says where.
|
|
1315
|
-
*
|
|
1316
|
-
* - **One compilation.** `@formancy/report-core`'s `compileReport` compiles
|
|
1317
|
-
* every expression where it stands, and the editor's diagnostics come
|
|
1318
|
-
* from the same function (0009). A report its diagnostics give an error
|
|
1319
|
-
* for is refused before anything is evaluated, so the runtime never runs
|
|
1320
|
-
* what the editor refuses. Each expression is compiled once per render,
|
|
1321
|
-
* never once per row -- twice, in fact, since `diagnose` does not hand
|
|
1322
|
-
* back the compilation it made.
|
|
1323
|
-
* - **One binding.** Each program's values are made by report-core's
|
|
1324
|
-
* `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,
|
|
1325
|
-
* an instant as a moment, a date as its ISO string. A value missing, or of
|
|
1326
|
-
* another type, fails the evaluation, naming the member and never quoting
|
|
1327
|
-
* the value.
|
|
1328
|
-
* - **Nothing differs between renders.** The diagnostics refuse `now()`,
|
|
1329
|
-
* `today()` and `random()`; the capabilities an evaluation is handed are
|
|
1330
|
-
* fixed besides, so that one reached anyway would answer the same in every
|
|
1331
|
-
* render.
|
|
1332
|
-
* - **Bounded.** Each evaluation has a budget of steps, and a render has one
|
|
1333
|
-
* for all its evaluations together. Past either, the evaluation is refused.
|
|
1334
|
-
* - **A failure is an error, never a blank.** It names the component, the
|
|
1335
|
-
* table column or the aggregate, and the detail row, and gives upstream's
|
|
1336
|
-
* code for what went wrong, never upstream's message, which can quote the
|
|
1337
|
-
* values it was computing with.
|
|
2127
|
+
* A chart's value axis: ticks a reader takes in at a glance, found exactly.
|
|
1338
2128
|
*
|
|
1339
|
-
*
|
|
1340
|
-
*
|
|
1341
|
-
*
|
|
1342
|
-
*
|
|
1343
|
-
* evaluated (report-core's `exactness.ts`), since upstream hands an integer
|
|
1344
|
-
* and a double back alike, as a JavaScript number, and `int()` of a double
|
|
1345
|
-
* would otherwise print as an exact integer. A number that is not a safe
|
|
1346
|
-
* integer is still refused here, rather than printed.
|
|
1347
|
-
*/
|
|
1348
|
-
/**
|
|
1349
|
-
* Steps one evaluation may take: upstream's default for a formancy form's
|
|
1350
|
-
* expression (`DEFAULT_BUDGET`). A report expression reads single values, so
|
|
1351
|
-
* the only way to spend many steps is a comprehension over a list literal;
|
|
1352
|
-
* the deepest the structural limits allow, 64 by 64, measured 8,385 steps,
|
|
1353
|
-
* and `evaluate.test.ts` holds that it fits while one reading three values
|
|
1354
|
-
* in each turn (28,865 steps) does not.
|
|
2129
|
+
* The step is 1, 2 or 5 times a power of ten, the finest that covers every
|
|
2130
|
+
* value in at most `MAX_TICK_INTERVALS` intervals and no finer than one unit
|
|
2131
|
+
* of the value format's last place. Everything is BigInt division on a
|
|
2132
|
+
* decimal's units, never a double, so a 40-digit total ticks exactly (0010).
|
|
1355
2133
|
*/
|
|
1356
|
-
|
|
2134
|
+
/** Intervals an axis may hold: six labels down it, chosen as what a reader takes in at a glance. */
|
|
2135
|
+
const MAX_TICK_INTERVALS = 5;
|
|
2136
|
+
/** `numerator / denominator` rounded down, denominator more than 0. */
|
|
2137
|
+
function floorDiv(numerator, denominator) {
|
|
2138
|
+
const quotient = numerator / denominator;
|
|
2139
|
+
return numerator % denominator < 0n ? quotient - 1n : quotient;
|
|
2140
|
+
}
|
|
1357
2141
|
/**
|
|
1358
|
-
*
|
|
1359
|
-
*
|
|
1360
|
-
*
|
|
1361
|
-
* 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`
|
|
1362
|
-
* 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00
|
|
1363
|
-
* microseconds a step) and of `row.amount * dec("1.081") > dec("10")` 13.0
|
|
1364
|
-
* (1.30). An earlier measurement, of upstream's `evaluate` alone, had put
|
|
1365
|
-
* that budget at 8.5 seconds and missed the binding. So the budget is five
|
|
1366
|
-
* million: about 5 to 6.5 seconds of evaluation on that machine, against
|
|
1367
|
-
* the plan's investigation target of ten seconds in all for a hundred-page
|
|
1368
|
-
* report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read
|
|
1369
|
-
* expressions per row spends 2,000,000.
|
|
2142
|
+
* The decimal of `units` at `scale`, without trailing zeros: a tick is
|
|
2143
|
+
* written as its value needs, and printed at the value format's scale, to
|
|
2144
|
+
* which the formatter pads it back -- 11 prints as 11.00 at two places.
|
|
1370
2145
|
*/
|
|
1371
|
-
|
|
2146
|
+
function tick(units, scale) {
|
|
2147
|
+
let kept = units;
|
|
2148
|
+
let places = scale;
|
|
2149
|
+
while (places > 0 && kept % 10n === 0n) {
|
|
2150
|
+
kept /= 10n;
|
|
2151
|
+
places--;
|
|
2152
|
+
}
|
|
2153
|
+
return new Decimal(kept, places);
|
|
2154
|
+
}
|
|
1372
2155
|
/**
|
|
1373
|
-
*
|
|
1374
|
-
*
|
|
1375
|
-
*
|
|
2156
|
+
* The ticks of an axis over `values` (non-empty, not null) at the value
|
|
2157
|
+
* format's `scale`, ascending, evenly spaced and holding every value; a bar
|
|
2158
|
+
* chart's axis, and a flat line's, hold zero as well. Zero is a tick whenever
|
|
2159
|
+
* the axis holds it.
|
|
1376
2160
|
*/
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
"unbound-value",
|
|
1386
|
-
"expression-failed",
|
|
1387
|
-
"expression-budget",
|
|
1388
|
-
"render-budget",
|
|
1389
|
-
"inexact-value",
|
|
1390
|
-
"unprintable-value",
|
|
1391
|
-
"not-a-condition"
|
|
1392
|
-
];
|
|
1393
|
-
/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */
|
|
1394
|
-
function typed(result, resultType) {
|
|
1395
|
-
if (result === null) return null;
|
|
1396
|
-
if (result instanceof Decimal) return {
|
|
1397
|
-
type: "decimal",
|
|
1398
|
-
value: result
|
|
1399
|
-
};
|
|
1400
|
-
switch (typeof result) {
|
|
1401
|
-
case "boolean": return {
|
|
1402
|
-
type: "boolean",
|
|
1403
|
-
value: result
|
|
1404
|
-
};
|
|
1405
|
-
case "string": {
|
|
1406
|
-
const instant = resultType === "timestamp" ? canonicalInstant(result) : void 0;
|
|
1407
|
-
return instant === void 0 ? {
|
|
1408
|
-
type: "string",
|
|
1409
|
-
value: result
|
|
1410
|
-
} : {
|
|
1411
|
-
type: "instant",
|
|
1412
|
-
value: instant
|
|
1413
|
-
};
|
|
1414
|
-
}
|
|
1415
|
-
case "number":
|
|
1416
|
-
if (Number.isSafeInteger(result)) return {
|
|
1417
|
-
type: "integer",
|
|
1418
|
-
value: BigInt(result)
|
|
1419
|
-
};
|
|
1420
|
-
return {
|
|
1421
|
-
code: "inexact-value",
|
|
1422
|
-
what: "the expression gives a double, which is not exact; dec() keeps a number exact"
|
|
1423
|
-
};
|
|
1424
|
-
default: return {
|
|
1425
|
-
code: "unprintable-value",
|
|
1426
|
-
what: "the expression gives a list or a map, which has no text"
|
|
1427
|
-
};
|
|
1428
|
-
}
|
|
1429
|
-
}
|
|
1430
|
-
/** One render's evaluations of a report's expressions. */
|
|
1431
|
-
var Evaluator = class {
|
|
1432
|
-
compilation;
|
|
1433
|
-
#aggregates;
|
|
1434
|
-
#spent = 0;
|
|
1435
|
-
constructor(report, compilation) {
|
|
1436
|
-
this.compilation = compilation;
|
|
1437
|
-
this.#aggregates = report.aggregates.map(({ id }) => id);
|
|
1438
|
-
}
|
|
1439
|
-
get spent() {
|
|
1440
|
-
return this.#spent;
|
|
1441
|
-
}
|
|
1442
|
-
evaluate(path, values, row) {
|
|
1443
|
-
const compiled = this.compilation.expressions.get(path);
|
|
1444
|
-
if (compiled === void 0) return {
|
|
1445
|
-
ok: false,
|
|
1446
|
-
error: {
|
|
1447
|
-
code: "unknown-expression",
|
|
1448
|
-
message: `the report has no expression at ${path}`,
|
|
1449
|
-
path
|
|
1450
|
-
}
|
|
1451
|
-
};
|
|
1452
|
-
const fail = (code, what) => ({
|
|
1453
|
-
ok: false,
|
|
1454
|
-
error: this.#error(compiled, code, what, row)
|
|
1455
|
-
});
|
|
1456
|
-
for (const read of compiled.reads) {
|
|
1457
|
-
const scope = values[read.name];
|
|
1458
|
-
if (scope === void 0 || !Object.hasOwn(scope, read.member)) return fail("missing-value", `${read.name}.${read.member} has no value: it is missing, which is not null`);
|
|
1459
|
-
}
|
|
1460
|
-
let bound;
|
|
1461
|
-
try {
|
|
1462
|
-
bound = expressionValues(compiled, values);
|
|
1463
|
-
} catch (error) {
|
|
1464
|
-
return fail("unbound-value", error.message);
|
|
1465
|
-
}
|
|
1466
|
-
if (this.#spent >= 5e6) return fail("render-budget", `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`);
|
|
1467
|
-
const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1);
|
|
1468
|
-
const outcome = evaluate(compiled.program, bound, {
|
|
1469
|
-
capabilities: CAPABILITIES,
|
|
1470
|
-
budget: { maxSteps }
|
|
1471
|
-
});
|
|
1472
|
-
if (!outcome.ok) {
|
|
1473
|
-
const exhausted = outcome.error.kind === "budget";
|
|
1474
|
-
this.#spent += (exhausted ? maxSteps : 0) + 1;
|
|
1475
|
-
if (!exhausted) return fail("expression-failed", `the expression failed (${outcome.error.code})`);
|
|
1476
|
-
if (maxSteps < EXPRESSION_STEP_BUDGET) return fail("render-budget", `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`);
|
|
1477
|
-
return fail("expression-budget", `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`);
|
|
1478
|
-
}
|
|
1479
|
-
this.#spent += outcome.steps + 1;
|
|
1480
|
-
const value = typed(outcome.value, compiled.program.resultType);
|
|
1481
|
-
return value !== null && "code" in value ? fail(value.code, value.what) : {
|
|
1482
|
-
ok: true,
|
|
1483
|
-
value
|
|
1484
|
-
};
|
|
1485
|
-
}
|
|
1486
|
-
condition(path, values, row) {
|
|
1487
|
-
const outcome = this.evaluate(path, values, row);
|
|
1488
|
-
if (!outcome.ok) return outcome;
|
|
1489
|
-
if (outcome.value?.type === "boolean") return {
|
|
1490
|
-
ok: true,
|
|
1491
|
-
value: outcome.value.value
|
|
1492
|
-
};
|
|
1493
|
-
const compiled = this.compilation.expressions.get(path);
|
|
1494
|
-
return {
|
|
1495
|
-
ok: false,
|
|
1496
|
-
error: this.#error(compiled, "not-a-condition", "a condition gives true or false, and this expression gives something else", row)
|
|
1497
|
-
};
|
|
2161
|
+
function chartTicks(values, chart, scale) {
|
|
2162
|
+
const common = values.reduce((most, value) => Math.max(most, value.scale), scale);
|
|
2163
|
+
const units = values.map((value) => value.units * 10n ** BigInt(common - value.scale));
|
|
2164
|
+
let lo = units.reduce((least, value) => value < least ? value : least);
|
|
2165
|
+
let hi = units.reduce((most, value) => value > most ? value : most);
|
|
2166
|
+
if (chart === "bar" || lo === hi) {
|
|
2167
|
+
if (lo > 0n) lo = 0n;
|
|
2168
|
+
if (hi < 0n) hi = 0n;
|
|
1498
2169
|
}
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
path: site.path,
|
|
1512
|
-
...site.componentId === void 0 ? {} : { componentId: site.componentId },
|
|
1513
|
-
...site.columnId === void 0 ? {} : { columnId: site.columnId },
|
|
1514
|
-
...aggregateId === void 0 ? {} : { aggregateId },
|
|
1515
|
-
...row === void 0 ? {} : { row }
|
|
1516
|
-
};
|
|
2170
|
+
if (lo === hi) hi = 10n ** BigInt(common);
|
|
2171
|
+
const e = (hi - lo).toString().length - 1 - common;
|
|
2172
|
+
for (let k = Math.max(-scale, e - 1);; k++) for (const m of [
|
|
2173
|
+
1n,
|
|
2174
|
+
2n,
|
|
2175
|
+
5n
|
|
2176
|
+
]) {
|
|
2177
|
+
const step = m * 10n ** BigInt(k + common);
|
|
2178
|
+
const first = floorDiv(lo, step);
|
|
2179
|
+
const intervals = -floorDiv(-hi, step) - first;
|
|
2180
|
+
if (intervals > BigInt(5)) continue;
|
|
2181
|
+
return Array.from({ length: Number(intervals) + 1 }, (_, i) => tick((first + BigInt(i)) * step, common));
|
|
1517
2182
|
}
|
|
1518
|
-
};
|
|
1519
|
-
/**
|
|
1520
|
-
* `report`'s expressions compiled for one render, or the diagnostics that
|
|
1521
|
-
* refuse it: every error `diagnose` gives, which the editor shows too.
|
|
1522
|
-
* `report` is one the validator accepts. The evaluations of one render
|
|
1523
|
-
* share one budget, so a render prepares its own.
|
|
1524
|
-
*/
|
|
1525
|
-
function prepareExpressions(report) {
|
|
1526
|
-
const errors = diagnose(report).filter(({ severity }) => severity === "error");
|
|
1527
|
-
if (errors.length > 0) return {
|
|
1528
|
-
ok: false,
|
|
1529
|
-
diagnostics: errors
|
|
1530
|
-
};
|
|
1531
|
-
return {
|
|
1532
|
-
ok: true,
|
|
1533
|
-
expressions: new Evaluator(report, compileReport(report))
|
|
1534
|
-
};
|
|
1535
2183
|
}
|
|
1536
|
-
|
|
1537
|
-
//#region src/resolve-errors.ts
|
|
2184
|
+
// src/resolve-errors.ts
|
|
1538
2185
|
/** What lowering a report can find wrong besides what each earlier stage finds. */
|
|
1539
2186
|
const RESOLVE_ERROR_CODES = [
|
|
1540
2187
|
"invalid-creation-date",
|
|
2188
|
+
"undeclared-locale",
|
|
1541
2189
|
"missing-asset",
|
|
1542
2190
|
"invalid-asset",
|
|
1543
2191
|
"asset-lookup-failed",
|
|
1544
2192
|
"rounding-not-decimal",
|
|
1545
2193
|
"aggregate-value-type",
|
|
2194
|
+
"no-qr-value",
|
|
2195
|
+
"empty-qr-code",
|
|
2196
|
+
"invalid-qr-bill",
|
|
2197
|
+
"invalid-epc-qr-code",
|
|
2198
|
+
"invalid-e-invoice",
|
|
2199
|
+
"e-invoice-preview",
|
|
2200
|
+
"no-e-invoice-copy",
|
|
2201
|
+
"chart-too-many-categories",
|
|
2202
|
+
"chart-negative-share",
|
|
1546
2203
|
"too-many-errors"
|
|
1547
2204
|
];
|
|
1548
2205
|
/** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */
|
|
@@ -1553,6 +2210,10 @@ function placed(place) {
|
|
|
1553
2210
|
...place.row === void 0 ? {} : { row: place.row }
|
|
1554
2211
|
};
|
|
1555
2212
|
}
|
|
2213
|
+
/** A type as a message says what a value is: "a decimal", "an integer". */
|
|
2214
|
+
function aType(type) {
|
|
2215
|
+
return `${/^[aeiou]/.test(type) ? "an" : "a"} ${type}`;
|
|
2216
|
+
}
|
|
1556
2217
|
function fromReport(error) {
|
|
1557
2218
|
return {
|
|
1558
2219
|
stage: "report",
|
|
@@ -1629,23 +2290,27 @@ var Problems = class {
|
|
|
1629
2290
|
return [...this.#warnings.values()];
|
|
1630
2291
|
}
|
|
1631
2292
|
};
|
|
1632
|
-
|
|
1633
|
-
//#region src/render-context.ts
|
|
2293
|
+
// src/render-context.ts
|
|
1634
2294
|
/** Each aggregate's value as an expression is handed it: the typed value's own, or null. */
|
|
1635
2295
|
function raw(values) {
|
|
1636
2296
|
return Object.fromEntries([...values].map(([id, value]) => [id, value === null ? null : value.value]));
|
|
1637
2297
|
}
|
|
1638
2298
|
/** The header record, or none when the report declares no header dataset. */
|
|
1639
|
-
function headerOf(render) {
|
|
2299
|
+
function headerOf$1(render) {
|
|
1640
2300
|
return render.data.header ?? {};
|
|
1641
2301
|
}
|
|
2302
|
+
/** The e-invoice's names, read wherever `totals` is, once they are computed; none in a report that is no e-invoice. */
|
|
2303
|
+
function invoiceNames$1(render) {
|
|
2304
|
+
return render.invoice?.names ?? {};
|
|
2305
|
+
}
|
|
1642
2306
|
function reportScope(render, totals) {
|
|
1643
|
-
const header = headerOf(render);
|
|
2307
|
+
const header = headerOf$1(render);
|
|
1644
2308
|
return {
|
|
1645
2309
|
values: {
|
|
1646
2310
|
params: render.params,
|
|
1647
2311
|
header,
|
|
1648
|
-
totals: raw(totals)
|
|
2312
|
+
totals: raw(totals),
|
|
2313
|
+
...invoiceNames$1(render)
|
|
1649
2314
|
},
|
|
1650
2315
|
currency: {
|
|
1651
2316
|
params: render.params,
|
|
@@ -1653,43 +2318,59 @@ function reportScope(render, totals) {
|
|
|
1653
2318
|
}
|
|
1654
2319
|
};
|
|
1655
2320
|
}
|
|
2321
|
+
/** A table's total rows: the report's values, and the table's aggregates, over the rows it prints, as `table`. */
|
|
2322
|
+
function tableScope(render, table) {
|
|
2323
|
+
const scope = reportScope(render, render.totals.report);
|
|
2324
|
+
return {
|
|
2325
|
+
...scope,
|
|
2326
|
+
values: {
|
|
2327
|
+
...scope.values,
|
|
2328
|
+
table: raw(table)
|
|
2329
|
+
},
|
|
2330
|
+
table
|
|
2331
|
+
};
|
|
2332
|
+
}
|
|
1656
2333
|
/**
|
|
1657
|
-
* A group's header and footer: the
|
|
2334
|
+
* A group's header and footer: the table's scope, and the group's
|
|
1658
2335
|
* aggregates and key as `group`. `by` is the field grouped by; where a
|
|
1659
2336
|
* preview's rows lack it the key is missing, as the field is, not null.
|
|
1660
2337
|
*/
|
|
1661
|
-
function groupScope(render, group, aggregates, by) {
|
|
2338
|
+
function groupScope(render, group, aggregates, table, by) {
|
|
1662
2339
|
const record = group.rows[0].record;
|
|
1663
|
-
const header = headerOf(render);
|
|
2340
|
+
const header = headerOf$1(render);
|
|
1664
2341
|
const key = Object.hasOwn(record, by) ? { key: group.key } : {};
|
|
1665
2342
|
return {
|
|
1666
2343
|
values: {
|
|
1667
2344
|
params: render.params,
|
|
1668
2345
|
header,
|
|
1669
2346
|
totals: raw(render.totals.report),
|
|
2347
|
+
table: raw(table),
|
|
1670
2348
|
group: {
|
|
1671
2349
|
...raw(aggregates),
|
|
1672
2350
|
...key
|
|
1673
|
-
}
|
|
2351
|
+
},
|
|
2352
|
+
...invoiceNames$1(render)
|
|
1674
2353
|
},
|
|
1675
2354
|
currency: {
|
|
1676
2355
|
params: render.params,
|
|
1677
2356
|
header,
|
|
1678
2357
|
row: record
|
|
1679
2358
|
},
|
|
2359
|
+
table,
|
|
1680
2360
|
group: aggregates,
|
|
1681
2361
|
record
|
|
1682
2362
|
};
|
|
1683
2363
|
}
|
|
1684
2364
|
/** One detail row: the report's values, and the row's as `row`. */
|
|
1685
2365
|
function rowScope(render, totals, row) {
|
|
1686
|
-
const header = headerOf(render);
|
|
2366
|
+
const header = headerOf$1(render);
|
|
1687
2367
|
return {
|
|
1688
2368
|
values: {
|
|
1689
2369
|
params: render.params,
|
|
1690
2370
|
header,
|
|
1691
2371
|
totals: raw(totals),
|
|
1692
|
-
row: row.record
|
|
2372
|
+
row: row.record,
|
|
2373
|
+
...invoiceNames$1(render)
|
|
1693
2374
|
},
|
|
1694
2375
|
currency: {
|
|
1695
2376
|
params: render.params,
|
|
@@ -1723,36 +2404,2446 @@ function valueOf(render, scope, path) {
|
|
|
1723
2404
|
function holds(render, scope, path) {
|
|
1724
2405
|
const outcome = render.expressions.condition(path, scope.values, scope.row);
|
|
1725
2406
|
if (outcome.ok) return outcome.value;
|
|
1726
|
-
return failed(render, outcome) ? false : void 0;
|
|
2407
|
+
return failed(render, outcome) ? false : void 0;
|
|
2408
|
+
}
|
|
2409
|
+
/** The type the report's contract gives `ref`'s field; the validator has checked that it declares one. */
|
|
2410
|
+
function fieldType(report, ref) {
|
|
2411
|
+
return report.datasets[ref.dataset]?.fields.find(({ id }) => id === ref.field)?.type;
|
|
2412
|
+
}
|
|
2413
|
+
function parameterType(report, parameter) {
|
|
2414
|
+
return report.parameters.find(({ id }) => id === parameter)?.type;
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* The value of `ref`, typed by its contract: a header field's from the
|
|
2418
|
+
* header, a detail field's from `record`. Null where it is null, and where
|
|
2419
|
+
* a preview's data lacks it, which the data check has already warned of. An
|
|
2420
|
+
* image field is drawn, never printed (0007), and reads as null here.
|
|
2421
|
+
*/
|
|
2422
|
+
function fieldValue(render, record, ref) {
|
|
2423
|
+
const value = (ref.dataset === "header" ? render.data.header : record)?.[ref.field] ?? null;
|
|
2424
|
+
const type = fieldType(render.report, ref);
|
|
2425
|
+
if (value === null || type === "image") return null;
|
|
2426
|
+
return {
|
|
2427
|
+
type,
|
|
2428
|
+
value
|
|
2429
|
+
};
|
|
2430
|
+
}
|
|
2431
|
+
/** An image field's value in the header: an approved asset, or null when there is none to draw. */
|
|
2432
|
+
function imageValue(render, ref) {
|
|
2433
|
+
return render.data.header?.[ref.field] ?? null;
|
|
2434
|
+
}
|
|
2435
|
+
// src/totals.ts
|
|
2436
|
+
/**
|
|
2437
|
+
* The report's aggregates, computed exactly, once, here (0007): over every
|
|
2438
|
+
* detail row for `totals`, over a group's rows for `group`, and over the
|
|
2439
|
+
* rows a table's condition selects for `table` (0062).
|
|
2440
|
+
*
|
|
2441
|
+
* - **In report-core's order.** An aggregate's expression may read another
|
|
2442
|
+
* aggregate's total, so each is computed after every one it reads, in the
|
|
2443
|
+
* order `compileReport` gives (0009); an aggregate that could never be
|
|
2444
|
+
* computed has already refused the report.
|
|
2445
|
+
* - **Each row read once.** What an aggregate reads from a row is read once
|
|
2446
|
+
* per render, with the report's totals, and kept by the row's index; a
|
|
2447
|
+
* group's aggregate, and a table's, is the same function over its rows'
|
|
2448
|
+
* values. So a group's subtotal and the report's total are totals of the
|
|
2449
|
+
* same values, and the subtotals of a sum that declares no rounding add
|
|
2450
|
+
* up to the total. A declared rounding is applied to each group's exact
|
|
2451
|
+
* sum and to the report's, once each, so rounded subtotals need not add
|
|
2452
|
+
* up to the rounded total: two groups of 0.02, rounded to 0.05, print
|
|
2453
|
+
* 0.00 and 0.00 over 0.05.
|
|
2454
|
+
* - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,
|
|
2455
|
+
* through `decimal.ts`; nothing passes through a JavaScript number. A
|
|
2456
|
+
* total report-core compiled as a decimal is a decimal, its 0 too, and so
|
|
2457
|
+
* is one whose kind the compiler could not tell (`dyn`) once it declares a
|
|
2458
|
+
* rounding or meets a decimal; a group's total, and a table's, is of the
|
|
2459
|
+
* report total's kind, so an expression reading `group.<id>` or
|
|
2460
|
+
* `table.<id>` meets one type.
|
|
2461
|
+
* - **Nulls are skipped**, and so is a value a preview's data lacks. Over no
|
|
2462
|
+
* values a count and a sum are 0 and the rest null (0007).
|
|
2463
|
+
* - **Declared rounding is applied once**, to the exact result: an average
|
|
2464
|
+
* always declares one, and a sum, a minimum or a maximum of decimals may.
|
|
2465
|
+
* A rounding on a total that is an integer or a moment is refused, never
|
|
2466
|
+
* ignored.
|
|
2467
|
+
*/
|
|
2468
|
+
const isRefusal = (value) => value !== null && "code" in value;
|
|
2469
|
+
const integer = (value) => ({
|
|
2470
|
+
type: "integer",
|
|
2471
|
+
value
|
|
2472
|
+
});
|
|
2473
|
+
const decimal = (value) => ({
|
|
2474
|
+
type: "decimal",
|
|
2475
|
+
value
|
|
2476
|
+
});
|
|
2477
|
+
/** A number as a decimal: an integer at no places. */
|
|
2478
|
+
const asDecimal = (value) => value.type === "integer" ? new Decimal(value.value, 0) : value.value;
|
|
2479
|
+
/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */
|
|
2480
|
+
function numbers(values, decimals) {
|
|
2481
|
+
if (!decimals && values.every((value) => value.type === "integer")) return { integers: values.map((value) => value.value) };
|
|
2482
|
+
if (!values.every((value) => value.type === "integer" || value.type === "decimal")) return void 0;
|
|
2483
|
+
return { decimals: values.map(asDecimal) };
|
|
2484
|
+
}
|
|
2485
|
+
const NOT_NUMBERS = {
|
|
2486
|
+
code: "aggregate-value-type",
|
|
2487
|
+
message: "totals integers and decimals, and a value it read is neither"
|
|
2488
|
+
};
|
|
2489
|
+
function sum$1(values, decimals) {
|
|
2490
|
+
const read = numbers(values, decimals);
|
|
2491
|
+
if (read === void 0) return NOT_NUMBERS;
|
|
2492
|
+
return "integers" in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals));
|
|
2493
|
+
}
|
|
2494
|
+
function average(values, rounding) {
|
|
2495
|
+
const read = numbers(values, true);
|
|
2496
|
+
if (read === void 0) return NOT_NUMBERS;
|
|
2497
|
+
const result = averageDecimals(read.decimals, rounding);
|
|
2498
|
+
return result === null ? null : decimal(result);
|
|
2499
|
+
}
|
|
2500
|
+
const ordered = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2501
|
+
/**
|
|
2502
|
+
* -1, 0 or 1 for two values of one kind: numbers by value, text as the
|
|
2503
|
+
* report's language sorts it, through `collator`, dates as days, moments in
|
|
2504
|
+
* time order. Text met without a collator is a defect: a total handed none
|
|
2505
|
+
* -- a chart's series, which totals numbers alone -- would otherwise order
|
|
2506
|
+
* it by code unit, which no reader takes for their language's order.
|
|
2507
|
+
*/
|
|
2508
|
+
function comparator(values, collator) {
|
|
2509
|
+
const types = new Set(values.map(({ type }) => type));
|
|
2510
|
+
if ([...types].every((type) => type === "integer" || type === "decimal")) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b));
|
|
2511
|
+
const only = types.size === 1 ? [...types][0] : void 0;
|
|
2512
|
+
if (only === "string") {
|
|
2513
|
+
if (collator === void 0) throw new RangeError("a least or greatest of text is ordered by the report's collator, and none was handed: a defect");
|
|
2514
|
+
return (a, b) => collator.compare(a.value, b.value);
|
|
2515
|
+
}
|
|
2516
|
+
if (only === "date") return (a, b) => ordered(a.value, b.value);
|
|
2517
|
+
if (only === "datetime" || only === "instant") return (a, b) => ordered(fixedWidth(a.value), fixedWidth(b.value));
|
|
2518
|
+
}
|
|
2519
|
+
/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */
|
|
2520
|
+
function extreme(values, sign, decimals, collator) {
|
|
2521
|
+
const compare = comparator(values, collator);
|
|
2522
|
+
if (compare === void 0) return {
|
|
2523
|
+
code: "aggregate-value-type",
|
|
2524
|
+
message: "takes the least or greatest of values of one kind, and the values it read are of several"
|
|
2525
|
+
};
|
|
2526
|
+
const found = values.reduce((kept, value) => kept === null || Math.sign(compare(value, kept)) === sign ? value : kept, null);
|
|
2527
|
+
return found?.type === "integer" && decimals ? decimal(asDecimal(found)) : found;
|
|
2528
|
+
}
|
|
2529
|
+
/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */
|
|
2530
|
+
function rounded(total, rounding) {
|
|
2531
|
+
if (rounding === void 0 || total === null || isRefusal(total)) return total;
|
|
2532
|
+
if (total.type === "decimal") return decimal(roundDecimalAs(total.value, rounding));
|
|
2533
|
+
return {
|
|
2534
|
+
code: "rounding-not-decimal",
|
|
2535
|
+
message: `declares a rounding, and its total is ${total.type === "integer" ? "an integer" : `a ${total.type}`}, which has no places to round`
|
|
2536
|
+
};
|
|
2537
|
+
}
|
|
2538
|
+
/** Whether a total the compiler typed as `type` is totalled in decimals: one it typed a decimal, or could not tell and declares a rounding. */
|
|
2539
|
+
function totalsInDecimals(type, rounding) {
|
|
2540
|
+
return type === "decimal" || type === "dyn" && rounding !== void 0;
|
|
2541
|
+
}
|
|
2542
|
+
/**
|
|
2543
|
+
* The aggregate over the values read from some rows -- each null or typed --
|
|
2544
|
+
* or over `rows` rows when it reads nothing: the one rule every total is
|
|
2545
|
+
* computed by, the report's, a group's and a chart's series'. `collator`
|
|
2546
|
+
* orders text, for a least or a greatest of it; a total of numbers needs none.
|
|
2547
|
+
*/
|
|
2548
|
+
function totalOf(aggregate, decimals, read, rows, collator) {
|
|
2549
|
+
const values = (read ?? []).filter((value) => value !== null);
|
|
2550
|
+
let total;
|
|
2551
|
+
switch (aggregate.fn) {
|
|
2552
|
+
case "count":
|
|
2553
|
+
total = rounded(integer(BigInt(read === void 0 ? rows : values.length)), aggregate.rounding);
|
|
2554
|
+
break;
|
|
2555
|
+
case "avg":
|
|
2556
|
+
total = values.length === 0 ? null : average(values, aggregate.rounding);
|
|
2557
|
+
break;
|
|
2558
|
+
case "sum":
|
|
2559
|
+
total = rounded(sum$1(values, decimals), aggregate.rounding);
|
|
2560
|
+
break;
|
|
2561
|
+
case "min":
|
|
2562
|
+
total = rounded(extreme(values, -1, decimals, collator), aggregate.rounding);
|
|
2563
|
+
break;
|
|
2564
|
+
case "max": total = rounded(extreme(values, 1, decimals, collator), aggregate.rounding);
|
|
2565
|
+
}
|
|
2566
|
+
return isRefusal(total) ? {
|
|
2567
|
+
ok: false,
|
|
2568
|
+
...total
|
|
2569
|
+
} : {
|
|
2570
|
+
ok: true,
|
|
2571
|
+
value: total
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Every aggregate of `render`'s report, over its detail rows and, through
|
|
2576
|
+
* `over`, over any of them; or undefined when one could not be computed,
|
|
2577
|
+
* each reason recorded. `render` has every input but the totals.
|
|
2578
|
+
*/
|
|
2579
|
+
function computeTotals(render) {
|
|
2580
|
+
const { report, expressions, data, problems } = render;
|
|
2581
|
+
const collator = new Intl.Collator(report.locale, { usage: "sort" });
|
|
2582
|
+
const rows = data.detail.map((record, index) => ({
|
|
2583
|
+
index,
|
|
2584
|
+
record
|
|
2585
|
+
}));
|
|
2586
|
+
const read = /* @__PURE__ */ new Map();
|
|
2587
|
+
const totals = /* @__PURE__ */ new Map();
|
|
2588
|
+
const inDecimals = /* @__PURE__ */ new Map();
|
|
2589
|
+
const refuse = (index, refusal) => {
|
|
2590
|
+
problems.error({
|
|
2591
|
+
stage: "resolve",
|
|
2592
|
+
code: refusal.code,
|
|
2593
|
+
path: `/aggregates/${index}`,
|
|
2594
|
+
message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}`
|
|
2595
|
+
});
|
|
2596
|
+
};
|
|
2597
|
+
let computed = true;
|
|
2598
|
+
for (const id of expressions.compilation.aggregateOrder) {
|
|
2599
|
+
const index = report.aggregates.findIndex((aggregate) => aggregate.id === id);
|
|
2600
|
+
const aggregate = report.aggregates[index];
|
|
2601
|
+
const compiled = expressions.compilation.members.totals.get(id)?.type;
|
|
2602
|
+
const decimals = totalsInDecimals(compiled, aggregate.rounding);
|
|
2603
|
+
const of = aggregate.of;
|
|
2604
|
+
if (of !== void 0) {
|
|
2605
|
+
const path = `/aggregates/${index}/of/expression/cel`;
|
|
2606
|
+
const values = rows.map((row) => of.kind === "field" ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path));
|
|
2607
|
+
if (values.some((value) => value === void 0)) {
|
|
2608
|
+
computed = false;
|
|
2609
|
+
continue;
|
|
2610
|
+
}
|
|
2611
|
+
read.set(id, values);
|
|
2612
|
+
}
|
|
2613
|
+
const outcome = totalOf(aggregate, decimals, read.get(id), rows.length, collator);
|
|
2614
|
+
if (!outcome.ok) {
|
|
2615
|
+
computed = false;
|
|
2616
|
+
refuse(index, outcome);
|
|
2617
|
+
continue;
|
|
2618
|
+
}
|
|
2619
|
+
const total = outcome.value;
|
|
2620
|
+
totals.set(id, total);
|
|
2621
|
+
inDecimals.set(id, decimals || total?.type === "decimal");
|
|
2622
|
+
}
|
|
2623
|
+
if (!computed) return void 0;
|
|
2624
|
+
return {
|
|
2625
|
+
report: totals,
|
|
2626
|
+
over(group) {
|
|
2627
|
+
const values = /* @__PURE__ */ new Map();
|
|
2628
|
+
for (const aggregate of report.aggregates) {
|
|
2629
|
+
const each = read.get(aggregate.id);
|
|
2630
|
+
const grouped = totalOf(aggregate, inDecimals.get(aggregate.id), each && group.map((row) => each[row.index]), group.length, collator);
|
|
2631
|
+
if (!grouped.ok) throw new RangeError(`a total of some rows of aggregate ${aggregate.id} was refused as ${grouped.code} after the report's was not: a defect, refused rather than printed as nothing`);
|
|
2632
|
+
values.set(aggregate.id, grouped.value);
|
|
2633
|
+
}
|
|
2634
|
+
return values;
|
|
2635
|
+
}
|
|
2636
|
+
};
|
|
2637
|
+
}
|
|
2638
|
+
// src/lower-chart.ts
|
|
2639
|
+
/**
|
|
2640
|
+
* The most categories a chart groups its rows into: 200, chosen as a bound
|
|
2641
|
+
* on one chart's work, totalling every series at every category. How many
|
|
2642
|
+
* a box draws legibly is the renderer's to say, and so is how many charts
|
|
2643
|
+
* a render draws together: the renderer's `MAX_CHART_DRAWING` (0058) weighs
|
|
2644
|
+
* a render's charts and refuses them past it.
|
|
2645
|
+
*
|
|
2646
|
+
* What the costliest of eight chart forms tried costs a render, at one
|
|
2647
|
+
* packing, measured on 2026-11-15 on a Mac (Apple M2) under Node 22.23.4,
|
|
2648
|
+
* ECharts 6.1.0, with the machine at a load average of about 5 from other
|
|
2649
|
+
* work: three charts to an A4 landscape page, zero margins, each as wide
|
|
2650
|
+
* as the page and a third of its height, eight series where it has them,
|
|
2651
|
+
* value labels off, and `renderPdf` run seven times to each page after a
|
|
2652
|
+
* warm-up. Each form is the largest `drawChart` does not refuse: a line
|
|
2653
|
+
* chart of 8 series and the full 200 categories, whose empty labels are no
|
|
2654
|
+
* word, took a median of 586 ms (549 to 849) against 4.6 ms for the same
|
|
2655
|
+
* page without charts; the same chart with one-letter labels, refused past
|
|
2656
|
+
* 123 categories, 430 ms; the most categories a bar chart draws, 186 of
|
|
2657
|
+
* one series, 77 ms. The bound stays, for one chart's work; how many
|
|
2658
|
+
* charts a render draws, and so what a page costs, is the renderer's
|
|
2659
|
+
* `MAX_CHART_DRAWING`, which refuses that page of three 8 × 200 lines at
|
|
2660
|
+
* its third chart, at 5,016 units, and admits two. The renderer's word
|
|
2661
|
+
* checks took under 1 ms of any page.
|
|
2662
|
+
*/
|
|
2663
|
+
const MAX_CHART_CATEGORIES = 200;
|
|
2664
|
+
/** The places of a percentage a pie's share prints at: 12.5 %. */
|
|
2665
|
+
const SHARE_PLACES = 1;
|
|
2666
|
+
/** Records a refusal of the chart at `at`; undefined, for its caller to return. */
|
|
2667
|
+
function refuse$4(c, code, at, message) {
|
|
2668
|
+
c.render.problems.error({
|
|
2669
|
+
stage: "resolve",
|
|
2670
|
+
code,
|
|
2671
|
+
path: at,
|
|
2672
|
+
message,
|
|
2673
|
+
componentId: c.chart.id
|
|
2674
|
+
});
|
|
2675
|
+
}
|
|
2676
|
+
/** `formatted`'s text, or undefined when the formatter refused it, which is recorded at `at`. */
|
|
2677
|
+
function said(c, formatted, at) {
|
|
2678
|
+
if (formatted.ok) return formatted.text;
|
|
2679
|
+
c.render.problems.error({
|
|
2680
|
+
stage: "format",
|
|
2681
|
+
code: formatted.code,
|
|
2682
|
+
path: at,
|
|
2683
|
+
message: `chart ${c.chart.id}: ${formatted.message}`,
|
|
2684
|
+
componentId: c.chart.id
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
/** A value as the block holds it: its exact digits, and its text in the chart's value format. */
|
|
2688
|
+
function charted(c, value) {
|
|
2689
|
+
const text = said(c, c.render.formatter.format(value, c.chart.valueFormat, c.currency), `${c.path}/valueFormat`);
|
|
2690
|
+
return text === void 0 ? void 0 : {
|
|
2691
|
+
exact: plainText(value),
|
|
2692
|
+
text
|
|
2693
|
+
};
|
|
2694
|
+
}
|
|
2695
|
+
/** Each of `values` as the block holds it, null as null; undefined once one could not be printed, which is recorded, and nothing after it is tried. */
|
|
2696
|
+
function chartedAll(c, values) {
|
|
2697
|
+
const found = [];
|
|
2698
|
+
for (const value of values) {
|
|
2699
|
+
const each = value === null ? null : charted(c, value);
|
|
2700
|
+
if (each === void 0) return void 0;
|
|
2701
|
+
found.push(each);
|
|
2702
|
+
}
|
|
2703
|
+
return found;
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* Each category's label, in order: its key, of the category field's `type`,
|
|
2707
|
+
* as `categoryGroups` read it once, in the category's format; undefined
|
|
2708
|
+
* when one could not be printed, which is recorded.
|
|
2709
|
+
*/
|
|
2710
|
+
function labels(c, groups, type) {
|
|
2711
|
+
const { format, nullLabel } = c.chart.category;
|
|
2712
|
+
const found = [];
|
|
2713
|
+
for (const { key } of groups) {
|
|
2714
|
+
const typed = {
|
|
2715
|
+
type,
|
|
2716
|
+
value: key
|
|
2717
|
+
};
|
|
2718
|
+
const label = key === null ? nullLabel ?? "" : said(c, c.render.formatter.format(typed, format, c.currency), `${c.path}/category`);
|
|
2719
|
+
if (label === void 0) return void 0;
|
|
2720
|
+
found.push(label);
|
|
2721
|
+
}
|
|
2722
|
+
return found;
|
|
2723
|
+
}
|
|
2724
|
+
/** `series` as the aggregate of its definition: the same function, over the same field, rounded as it declares. */
|
|
2725
|
+
function asAggregate(series) {
|
|
2726
|
+
return {
|
|
2727
|
+
id: series.id,
|
|
2728
|
+
fn: series.fn,
|
|
2729
|
+
...series.of === void 0 ? {} : { of: {
|
|
2730
|
+
kind: "field",
|
|
2731
|
+
field: series.of
|
|
2732
|
+
} },
|
|
2733
|
+
...series.rounding === void 0 ? {} : { rounding: series.rounding }
|
|
2734
|
+
};
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* Each series' total at each category, null where it has none; undefined
|
|
2738
|
+
* when a series could not be totalled, which is recorded once for it. The
|
|
2739
|
+
* validator types every field a series reads, and report-core refuses a
|
|
2740
|
+
* rounding with no places to round before anything renders; one refused
|
|
2741
|
+
* here all the same is refused as an aggregate's is, never drawn.
|
|
2742
|
+
*/
|
|
2743
|
+
function totals(c, groups) {
|
|
2744
|
+
const { render, chart } = c;
|
|
2745
|
+
let refused = false;
|
|
2746
|
+
const found = chart.series.map((series, index) => {
|
|
2747
|
+
const aggregate = asAggregate(series);
|
|
2748
|
+
const decimals = totalsInDecimals(seriesType(render.report, series).type, series.rounding);
|
|
2749
|
+
const of = series.of;
|
|
2750
|
+
const values = [];
|
|
2751
|
+
for (const group of groups) {
|
|
2752
|
+
const outcome = totalOf(aggregate, decimals, of === void 0 ? void 0 : group.rows.map((row) => fieldValue(render, row.record, of)), group.rows.length);
|
|
2753
|
+
if (!outcome.ok) {
|
|
2754
|
+
refused = true;
|
|
2755
|
+
refuse$4(c, outcome.code, `${c.path}/series/${index}`, `series ${series.id} of chart ${chart.id} ${outcome.message}`);
|
|
2756
|
+
break;
|
|
2757
|
+
}
|
|
2758
|
+
values.push(outcome.value);
|
|
2759
|
+
}
|
|
2760
|
+
return values;
|
|
2761
|
+
});
|
|
2762
|
+
return refused ? void 0 : found;
|
|
2763
|
+
}
|
|
2764
|
+
/** A bar or a line chart over `values`, one list for each series; with no value at all, its empty text. */
|
|
2765
|
+
function axisChart(c, frame, categories, values) {
|
|
2766
|
+
const { chart } = c;
|
|
2767
|
+
const kind = chart.chart;
|
|
2768
|
+
const valueLabels = chart.valueLabels === true;
|
|
2769
|
+
const exact = values.flat().flatMap((total) => total === null ? [] : [asDecimal(total)]);
|
|
2770
|
+
if (exact.length === 0) return {
|
|
2771
|
+
...frame,
|
|
2772
|
+
chart: kind,
|
|
2773
|
+
legend: [],
|
|
2774
|
+
empty: chart.emptyText,
|
|
2775
|
+
categories: [],
|
|
2776
|
+
series: [],
|
|
2777
|
+
ticks: [],
|
|
2778
|
+
valueLabels
|
|
2779
|
+
};
|
|
2780
|
+
const series = [];
|
|
2781
|
+
for (const [index, each] of values.entries()) {
|
|
2782
|
+
const printed = chartedAll(c, each);
|
|
2783
|
+
if (printed === void 0) return void 0;
|
|
2784
|
+
series.push({
|
|
2785
|
+
color: c.palette[index],
|
|
2786
|
+
values: printed
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
const ticks = chartedAll(c, chartTicks(exact, kind, chart.valueFormat.scale).map((tick) => ({
|
|
2790
|
+
type: "decimal",
|
|
2791
|
+
value: tick
|
|
2792
|
+
})));
|
|
2793
|
+
if (ticks === void 0) return void 0;
|
|
2794
|
+
const legend = chart.series.length > 1 ? chart.series.map(({ label }, index) => ({
|
|
2795
|
+
text: label,
|
|
2796
|
+
color: c.palette[index]
|
|
2797
|
+
})) : [];
|
|
2798
|
+
return {
|
|
2799
|
+
...frame,
|
|
2800
|
+
chart: kind,
|
|
2801
|
+
...chart.categoryTitle === void 0 ? {} : { categoryTitle: chart.categoryTitle },
|
|
2802
|
+
...chart.valueTitle === void 0 ? {} : { valueTitle: chart.valueTitle },
|
|
2803
|
+
legend,
|
|
2804
|
+
categories,
|
|
2805
|
+
series,
|
|
2806
|
+
ticks,
|
|
2807
|
+
valueLabels
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
/**
|
|
2811
|
+
* A pie over `values`, a sum or a count at each category, which is never
|
|
2812
|
+
* null: a negative one refused; all zero, its empty text; otherwise a
|
|
2813
|
+
* slice and a legend entry for each, its share in the entry where the
|
|
2814
|
+
* chart labels its values.
|
|
2815
|
+
*/
|
|
2816
|
+
function pieChart(c, frame, categories, values) {
|
|
2817
|
+
const { chart, path } = c;
|
|
2818
|
+
const exact = values.map(asDecimal);
|
|
2819
|
+
if (exact.some((value) => value.units < 0n)) return refuse$4(c, "chart-negative-share", `${path}/series/0`, `chart ${chart.id} is a pie, and a category of it totals less than nothing, which is no share of a whole`);
|
|
2820
|
+
const total = sumDecimals(exact);
|
|
2821
|
+
if (total.units === 0n) return {
|
|
2822
|
+
...frame,
|
|
2823
|
+
chart: "pie",
|
|
2824
|
+
legend: [],
|
|
2825
|
+
empty: chart.emptyText,
|
|
2826
|
+
slices: []
|
|
2827
|
+
};
|
|
2828
|
+
const printed = chartedAll(c, values);
|
|
2829
|
+
if (printed === void 0) return void 0;
|
|
2830
|
+
const legend = [];
|
|
2831
|
+
for (const [index, value] of printed.entries()) {
|
|
2832
|
+
const label = categories[index];
|
|
2833
|
+
let text = label;
|
|
2834
|
+
if (chart.valueLabels === true) {
|
|
2835
|
+
const share = ratioRounded(exact[index], total, {
|
|
2836
|
+
scale: 3,
|
|
2837
|
+
mode: "half-away-from-zero"
|
|
2838
|
+
});
|
|
2839
|
+
const percent = said(c, c.render.formatter.percent(share, 1), `${path}/series/0`);
|
|
2840
|
+
if (percent === void 0) return void 0;
|
|
2841
|
+
text = `${label}: ${value.text} (${percent})`;
|
|
2842
|
+
}
|
|
2843
|
+
legend.push({
|
|
2844
|
+
text,
|
|
2845
|
+
color: c.palette[index]
|
|
2846
|
+
});
|
|
2847
|
+
}
|
|
2848
|
+
return {
|
|
2849
|
+
...frame,
|
|
2850
|
+
chart: "pie",
|
|
2851
|
+
legend,
|
|
2852
|
+
slices: printed.map((value, index) => ({
|
|
2853
|
+
color: c.palette[index],
|
|
2854
|
+
value
|
|
2855
|
+
}))
|
|
2856
|
+
};
|
|
2857
|
+
}
|
|
2858
|
+
/**
|
|
2859
|
+
* `chart`, at `path`, as the block a renderer draws, `style` its words'
|
|
2860
|
+
* resolved style; undefined when it is refused, the reason recorded.
|
|
2861
|
+
*/
|
|
2862
|
+
function chartBlock(render, chart, path, style) {
|
|
2863
|
+
const c = {
|
|
2864
|
+
render,
|
|
2865
|
+
chart,
|
|
2866
|
+
path,
|
|
2867
|
+
currency: reportScope(render, render.totals.report).currency,
|
|
2868
|
+
palette: chart.palette ?? CHART_PALETTE
|
|
2869
|
+
};
|
|
2870
|
+
const by = {
|
|
2871
|
+
field: chart.category.field.field,
|
|
2872
|
+
type: fieldType(render.report, chart.category.field)
|
|
2873
|
+
};
|
|
2874
|
+
const groups = categoryGroups(render.data.detail, by, chart.category.order, render.report.locale);
|
|
2875
|
+
if (groups.length > 200) {
|
|
2876
|
+
const message = `chart ${chart.id} groups its rows into ${groups.length} categories, and a chart groups at most 200`;
|
|
2877
|
+
return refuse$4(c, "chart-too-many-categories", `${path}/category`, message);
|
|
2878
|
+
}
|
|
2879
|
+
if (chart.chart === "pie" && groups.length > c.palette.length) {
|
|
2880
|
+
const message = `chart ${chart.id} is a pie of ${groups.length} categories; a pie colours each slice apart, and its palette has ${c.palette.length} colours`;
|
|
2881
|
+
return refuse$4(c, "chart-too-many-categories", `${path}/category`, message);
|
|
2882
|
+
}
|
|
2883
|
+
const categories = labels(c, groups, by.type);
|
|
2884
|
+
const values = categories && totals(c, groups);
|
|
2885
|
+
if (categories === void 0 || values === void 0) return void 0;
|
|
2886
|
+
const frame = {
|
|
2887
|
+
kind: "chart",
|
|
2888
|
+
id: chart.id,
|
|
2889
|
+
width: chart.width,
|
|
2890
|
+
height: chart.height,
|
|
2891
|
+
...style === void 0 ? {} : { style },
|
|
2892
|
+
...chart.title === void 0 ? {} : { title: chart.title }
|
|
2893
|
+
};
|
|
2894
|
+
return chart.chart === "pie" ? pieChart(c, frame, categories, values[0] ?? []) : axisChart(c, frame, categories, values);
|
|
2895
|
+
}
|
|
2896
|
+
// src/evaluate.ts
|
|
2897
|
+
/**
|
|
2898
|
+
* A report's expressions, compiled once and evaluated against checked data,
|
|
2899
|
+
* within a budget, each failure an error that says where.
|
|
2900
|
+
*
|
|
2901
|
+
* - **One compilation.** `@formancy/report-core`'s `compileReport` compiles
|
|
2902
|
+
* every expression where it stands, and the editor's diagnostics come
|
|
2903
|
+
* from the same function (0009). A report its diagnostics give an error
|
|
2904
|
+
* for is refused before anything is evaluated, so the runtime never runs
|
|
2905
|
+
* what the editor refuses. Each expression is compiled once per render,
|
|
2906
|
+
* never once per row -- twice, in fact, since `diagnose` does not hand
|
|
2907
|
+
* back the compilation it made.
|
|
2908
|
+
* - **One binding.** Each program's values are made by report-core's
|
|
2909
|
+
* `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,
|
|
2910
|
+
* an instant as a moment, a date as its ISO string. A value missing, or of
|
|
2911
|
+
* another type, fails the evaluation, naming the member and never quoting
|
|
2912
|
+
* the value.
|
|
2913
|
+
* - **Nothing differs between renders.** The diagnostics refuse `now()`,
|
|
2914
|
+
* `today()` and `random()`; the capabilities an evaluation is handed are
|
|
2915
|
+
* fixed besides, so that one reached anyway would answer the same in every
|
|
2916
|
+
* render.
|
|
2917
|
+
* - **Bounded.** Each evaluation has a budget of steps, and a render has one
|
|
2918
|
+
* for all its evaluations together. Past either, the evaluation is refused.
|
|
2919
|
+
* - **A failure is an error, never a blank.** It names the component, the
|
|
2920
|
+
* table column or the aggregate, and the detail row, and gives upstream's
|
|
2921
|
+
* code for what went wrong, never upstream's message, which can quote the
|
|
2922
|
+
* values it was computing with.
|
|
2923
|
+
*
|
|
2924
|
+
* What an expression gives is handed back typed as the runtime holds values:
|
|
2925
|
+
* an integer as a BigInt, an instant in UTC. A list or a map, which has no
|
|
2926
|
+
* text, is refused. A double never arrives: the diagnostics refuse every
|
|
2927
|
+
* double literal, every `double()` and every `/` before anything is
|
|
2928
|
+
* evaluated (report-core's `exactness.ts`), since upstream hands an integer
|
|
2929
|
+
* and a double back alike, as a JavaScript number, and `int()` of a double
|
|
2930
|
+
* would otherwise print as an exact integer. A number that is not a safe
|
|
2931
|
+
* integer is still refused here, rather than printed.
|
|
2932
|
+
*/
|
|
2933
|
+
/**
|
|
2934
|
+
* Steps one evaluation may take: upstream's default for a formancy form's
|
|
2935
|
+
* expression (`DEFAULT_BUDGET`). A report expression reads single values, so
|
|
2936
|
+
* the only way to spend many steps is a comprehension over a list literal;
|
|
2937
|
+
* the deepest the structural limits allow, 64 by 64, measured 8,385 steps,
|
|
2938
|
+
* and `evaluate.test.ts` holds that it fits while one reading three values
|
|
2939
|
+
* in each turn (28,865 steps) does not.
|
|
2940
|
+
*/
|
|
2941
|
+
const EXPRESSION_STEP_BUDGET = DEFAULT_BUDGET.maxSteps;
|
|
2942
|
+
/**
|
|
2943
|
+
* Steps every evaluation of one render may take together, each charged its
|
|
2944
|
+
* steps and one more for itself. Measured as a render spends them, through
|
|
2945
|
+
* `condition()` with each evaluation's binding included, on 15 October
|
|
2946
|
+
* 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`
|
|
2947
|
+
* 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00
|
|
2948
|
+
* microseconds a step) and of `row.amount * dec("1.081") > dec("10")` 13.0
|
|
2949
|
+
* (1.30). An earlier measurement, of upstream's `evaluate` alone, had put
|
|
2950
|
+
* that budget at 8.5 seconds and missed the binding. So the budget is five
|
|
2951
|
+
* million: about 5 to 6.5 seconds of evaluation on that machine, against
|
|
2952
|
+
* the plan's investigation target of ten seconds in all for a hundred-page
|
|
2953
|
+
* report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read
|
|
2954
|
+
* expressions per row spends 2,000,000.
|
|
2955
|
+
*/
|
|
2956
|
+
const RENDER_STEP_BUDGET = 5e6;
|
|
2957
|
+
/**
|
|
2958
|
+
* What `now()`, `today()` and `random()` would give: nothing a report may
|
|
2959
|
+
* read (0009), fixed so that one reached anyway gives the same answer in
|
|
2960
|
+
* every render.
|
|
2961
|
+
*/
|
|
2962
|
+
const CAPABILITIES = fixedCapabilities({
|
|
2963
|
+
nowMs: 0,
|
|
2964
|
+
today: "1970-01-01",
|
|
2965
|
+
random: 0
|
|
2966
|
+
});
|
|
2967
|
+
const EVALUATION_ERROR_CODES = [
|
|
2968
|
+
"unknown-expression",
|
|
2969
|
+
"missing-value",
|
|
2970
|
+
"unbound-value",
|
|
2971
|
+
"expression-failed",
|
|
2972
|
+
"expression-budget",
|
|
2973
|
+
"render-budget",
|
|
2974
|
+
"inexact-value",
|
|
2975
|
+
"unprintable-value",
|
|
2976
|
+
"not-a-condition"
|
|
2977
|
+
];
|
|
2978
|
+
/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */
|
|
2979
|
+
function typed(result, resultType) {
|
|
2980
|
+
if (result === null) return null;
|
|
2981
|
+
if (result instanceof Decimal) return {
|
|
2982
|
+
type: "decimal",
|
|
2983
|
+
value: result
|
|
2984
|
+
};
|
|
2985
|
+
switch (typeof result) {
|
|
2986
|
+
case "boolean": return {
|
|
2987
|
+
type: "boolean",
|
|
2988
|
+
value: result
|
|
2989
|
+
};
|
|
2990
|
+
case "string": {
|
|
2991
|
+
const instant = resultType === "timestamp" ? canonicalInstant(result) : void 0;
|
|
2992
|
+
return instant === void 0 ? {
|
|
2993
|
+
type: "string",
|
|
2994
|
+
value: result
|
|
2995
|
+
} : {
|
|
2996
|
+
type: "instant",
|
|
2997
|
+
value: instant
|
|
2998
|
+
};
|
|
2999
|
+
}
|
|
3000
|
+
case "number":
|
|
3001
|
+
if (Number.isSafeInteger(result)) return {
|
|
3002
|
+
type: "integer",
|
|
3003
|
+
value: BigInt(result)
|
|
3004
|
+
};
|
|
3005
|
+
return {
|
|
3006
|
+
code: "inexact-value",
|
|
3007
|
+
what: "the expression gives a double, which is not exact; dec() keeps a number exact"
|
|
3008
|
+
};
|
|
3009
|
+
default: return {
|
|
3010
|
+
code: "unprintable-value",
|
|
3011
|
+
what: "the expression gives a list or a map, which has no text"
|
|
3012
|
+
};
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
/** One render's evaluations of a report's expressions. */
|
|
3016
|
+
var Evaluator = class {
|
|
3017
|
+
compilation;
|
|
3018
|
+
#aggregates;
|
|
3019
|
+
#spent = 0;
|
|
3020
|
+
constructor(report, compilation) {
|
|
3021
|
+
this.compilation = compilation;
|
|
3022
|
+
this.#aggregates = report.aggregates.map(({ id }) => id);
|
|
3023
|
+
}
|
|
3024
|
+
get spent() {
|
|
3025
|
+
return this.#spent;
|
|
3026
|
+
}
|
|
3027
|
+
evaluate(path, values, row) {
|
|
3028
|
+
const compiled = this.compilation.expressions.get(path);
|
|
3029
|
+
if (compiled === void 0) return {
|
|
3030
|
+
ok: false,
|
|
3031
|
+
error: {
|
|
3032
|
+
code: "unknown-expression",
|
|
3033
|
+
message: `the report has no expression at ${path}`,
|
|
3034
|
+
path
|
|
3035
|
+
}
|
|
3036
|
+
};
|
|
3037
|
+
const fail = (code, what) => ({
|
|
3038
|
+
ok: false,
|
|
3039
|
+
error: this.#error(compiled, code, what, row)
|
|
3040
|
+
});
|
|
3041
|
+
for (const read of compiled.reads) {
|
|
3042
|
+
const scope = values[read.name];
|
|
3043
|
+
if (scope === void 0 || !Object.hasOwn(scope, read.member)) return fail("missing-value", `${read.name}.${read.member} has no value: it is missing, which is not null`);
|
|
3044
|
+
}
|
|
3045
|
+
let bound;
|
|
3046
|
+
try {
|
|
3047
|
+
bound = expressionValues(compiled, values);
|
|
3048
|
+
} catch (error) {
|
|
3049
|
+
return fail("unbound-value", error.message);
|
|
3050
|
+
}
|
|
3051
|
+
if (this.#spent >= 5e6) return fail("render-budget", `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`);
|
|
3052
|
+
const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1);
|
|
3053
|
+
const outcome = evaluate(compiled.program, bound, {
|
|
3054
|
+
capabilities: CAPABILITIES,
|
|
3055
|
+
budget: { maxSteps }
|
|
3056
|
+
});
|
|
3057
|
+
if (!outcome.ok) {
|
|
3058
|
+
const exhausted = outcome.error.kind === "budget";
|
|
3059
|
+
this.#spent += (exhausted ? maxSteps : 0) + 1;
|
|
3060
|
+
if (!exhausted) return fail("expression-failed", `the expression failed (${outcome.error.code})`);
|
|
3061
|
+
if (maxSteps < EXPRESSION_STEP_BUDGET) return fail("render-budget", `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`);
|
|
3062
|
+
return fail("expression-budget", `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`);
|
|
3063
|
+
}
|
|
3064
|
+
this.#spent += outcome.steps + 1;
|
|
3065
|
+
const value = typed(outcome.value, compiled.program.resultType);
|
|
3066
|
+
return value !== null && "code" in value ? fail(value.code, value.what) : {
|
|
3067
|
+
ok: true,
|
|
3068
|
+
value
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
condition(path, values, row) {
|
|
3072
|
+
const outcome = this.evaluate(path, values, row);
|
|
3073
|
+
if (!outcome.ok) return outcome;
|
|
3074
|
+
if (outcome.value?.type === "boolean") return {
|
|
3075
|
+
ok: true,
|
|
3076
|
+
value: outcome.value.value
|
|
3077
|
+
};
|
|
3078
|
+
const compiled = this.compilation.expressions.get(path);
|
|
3079
|
+
return {
|
|
3080
|
+
ok: false,
|
|
3081
|
+
error: this.#error(compiled, "not-a-condition", "a condition gives true or false, and this expression gives something else", row)
|
|
3082
|
+
};
|
|
3083
|
+
}
|
|
3084
|
+
/** An error about `compiled`, naming where it stands and the row it read. */
|
|
3085
|
+
#error(compiled, code, what, row) {
|
|
3086
|
+
const { site } = compiled;
|
|
3087
|
+
const aggregateId = site.path.startsWith("/aggregates/") ? this.#aggregates[Number(site.path.split("/")[2])] : void 0;
|
|
3088
|
+
return {
|
|
3089
|
+
code,
|
|
3090
|
+
message: `${[
|
|
3091
|
+
site.path.startsWith("/paymentPart/") ? "the payment part" : site.path.startsWith("/eInvoice/") ? "the e-invoice" : void 0,
|
|
3092
|
+
site.componentId === void 0 ? void 0 : `component ${site.componentId}`,
|
|
3093
|
+
site.columnId === void 0 ? void 0 : `column ${site.columnId}`,
|
|
3094
|
+
aggregateId === void 0 ? void 0 : `aggregate ${aggregateId}`,
|
|
3095
|
+
row === void 0 ? void 0 : `detail row ${row}`
|
|
3096
|
+
].filter((part) => part !== void 0).join(", ")}: ${what}`,
|
|
3097
|
+
path: site.path,
|
|
3098
|
+
...site.componentId === void 0 ? {} : { componentId: site.componentId },
|
|
3099
|
+
...site.columnId === void 0 ? {} : { columnId: site.columnId },
|
|
3100
|
+
...aggregateId === void 0 ? {} : { aggregateId },
|
|
3101
|
+
...row === void 0 ? {} : { row }
|
|
3102
|
+
};
|
|
3103
|
+
}
|
|
3104
|
+
};
|
|
3105
|
+
/**
|
|
3106
|
+
* `report`'s expressions compiled for one render in `locale`, or the
|
|
3107
|
+
* diagnostics that refuse it: every error `diagnose` gives, which the
|
|
3108
|
+
* editor shows too, that names no language or names `locale` (0063). What
|
|
3109
|
+
* is compiled is `report` written in `locale`, which the render prints.
|
|
3110
|
+
* `report` is one the validator accepts, and `locale` the report's own or
|
|
3111
|
+
* one it declares, as `printLocale` holds it. The evaluations of one
|
|
3112
|
+
* render share one budget, so a render prepares its own.
|
|
3113
|
+
*/
|
|
3114
|
+
function prepareExpressions(report, locale = report.locale) {
|
|
3115
|
+
const errors = diagnose(report).filter((diagnostic) => refuses(diagnostic, locale));
|
|
3116
|
+
if (errors.length > 0) return {
|
|
3117
|
+
ok: false,
|
|
3118
|
+
diagnostics: errors
|
|
3119
|
+
};
|
|
3120
|
+
const printed = reportIn(report, locale);
|
|
3121
|
+
return {
|
|
3122
|
+
ok: true,
|
|
3123
|
+
report: printed,
|
|
3124
|
+
expressions: new Evaluator(printed, compileReport(printed))
|
|
3125
|
+
};
|
|
3126
|
+
}
|
|
3127
|
+
// src/page-label.ts
|
|
3128
|
+
/**
|
|
3129
|
+
* A label, as the runtime heads every page with one -- a preview's, an
|
|
3130
|
+
* XRechnung's copy's (0038), a copy of an e-invoice's (0077): the text
|
|
3131
|
+
* alone, small, bold and red, in a paragraph of its own.
|
|
3132
|
+
*/
|
|
3133
|
+
const label = (text) => ({
|
|
3134
|
+
kind: "paragraph",
|
|
3135
|
+
runs: [{ text }],
|
|
3136
|
+
style: {
|
|
3137
|
+
size: 8,
|
|
3138
|
+
bold: true,
|
|
3139
|
+
color: "#b00020"
|
|
3140
|
+
}
|
|
3141
|
+
});
|
|
3142
|
+
/** `paragraph` frozen through: its runs, each run, and its style. */
|
|
3143
|
+
function frozen(paragraph) {
|
|
3144
|
+
for (const run of paragraph.runs) Object.freeze(run);
|
|
3145
|
+
Object.freeze(paragraph.runs);
|
|
3146
|
+
Object.freeze(paragraph.style);
|
|
3147
|
+
return Object.freeze(paragraph);
|
|
3148
|
+
}
|
|
3149
|
+
// src/e-invoice-copy.ts
|
|
3150
|
+
/**
|
|
3151
|
+
* The label of a copy of an e-invoice (0077): what every page of a final
|
|
3152
|
+
* render says where a host asked for the copy and not the invoice
|
|
3153
|
+
* (`ResolveOptions.eInvoice`). A copy is what a Word file is written of:
|
|
3154
|
+
* a file a person may change is no invoice, so its every page says that
|
|
3155
|
+
* it is a copy, that it is not the invoice, and what the invoice is --
|
|
3156
|
+
* the PDF that embeds its XML, of a Factur-X, or its XML, of an
|
|
3157
|
+
* XRechnung. It carries no XML itself.
|
|
3158
|
+
*
|
|
3159
|
+
* The words are the runtime's, in the language the render prints in
|
|
3160
|
+
* (0063): the label is the one thing that tells a reader what the page
|
|
3161
|
+
* is, and in a language the page does not speak it tells them nothing.
|
|
3162
|
+
* So a copy in a language no label is written in is refused, never
|
|
3163
|
+
* labelled in another. It says "this document", not "this Word file":
|
|
3164
|
+
* the copy is a resolved document, and whatever is made of it is no
|
|
3165
|
+
* invoice. A preview's label and an XRechnung's PDF's stay English, as
|
|
3166
|
+
* they were (0038).
|
|
3167
|
+
*
|
|
3168
|
+
* One decision, here: the runtime writes the label, and an engine reads
|
|
3169
|
+
* it with `readCopyLabel` and decides no word of it.
|
|
3170
|
+
*/
|
|
3171
|
+
/** The languages a copy is labelled in: those the starters print in. A locale's language is its first subtag. */
|
|
3172
|
+
const E_INVOICE_COPY_LANGUAGES = [
|
|
3173
|
+
"de",
|
|
3174
|
+
"en",
|
|
3175
|
+
"es",
|
|
3176
|
+
"fr",
|
|
3177
|
+
"it",
|
|
3178
|
+
"nl"
|
|
3179
|
+
];
|
|
3180
|
+
/** What every page of a copy says, by the e-invoice's kind and the render's language. */
|
|
3181
|
+
const E_INVOICE_COPY_LABELS = Object.freeze({
|
|
3182
|
+
facturX: Object.freeze({
|
|
3183
|
+
de: "Kopie einer E-Rechnung: Die Rechnung ist das PDF, das ihr XML einbettet, und dieses Dokument ist nicht die Rechnung",
|
|
3184
|
+
en: "Copy of an e-invoice: the invoice is the PDF that embeds its XML, and this document is not the invoice",
|
|
3185
|
+
es: "Copia de una factura electrónica: la factura es el PDF que incorpora su XML, y este documento no es la factura",
|
|
3186
|
+
fr: "Copie d'une facture électronique\xA0: la facture est le PDF qui intègre son XML, et ce document n'est pas la facture",
|
|
3187
|
+
it: "Copia di una fattura elettronica: la fattura è il PDF che incorpora il suo XML, e questo documento non è la fattura",
|
|
3188
|
+
nl: "Kopie van een e-factuur: de factuur is de pdf waarin haar XML is ingebed, en dit document is niet de factuur"
|
|
3189
|
+
}),
|
|
3190
|
+
xrechnung: Object.freeze({
|
|
3191
|
+
de: "Kopie einer XRechnung: Die Rechnung ist ihr XML, und dieses Dokument ist nicht die Rechnung",
|
|
3192
|
+
en: "Copy of an XRechnung: the invoice is its XML, and this document is not the invoice",
|
|
3193
|
+
es: "Copia de una XRechnung: la factura es su XML, y este documento no es la factura",
|
|
3194
|
+
fr: "Copie d'une XRechnung\xA0: la facture est son XML, et ce document n'est pas la facture",
|
|
3195
|
+
it: "Copia di una XRechnung: la fattura è il suo XML, e questo documento non è la fattura",
|
|
3196
|
+
nl: "Kopie van een XRechnung: de factuur is haar XML, en dit document is niet de factuur"
|
|
3197
|
+
})
|
|
3198
|
+
});
|
|
3199
|
+
/** Every label's paragraph, made once and frozen: what a document's own paragraph is held to. */
|
|
3200
|
+
const PARAGRAPHS = ["facturX", "xrechnung"].flatMap((kind) => E_INVOICE_COPY_LANGUAGES.map((language) => ({
|
|
3201
|
+
kind,
|
|
3202
|
+
language,
|
|
3203
|
+
paragraph: frozen(label(E_INVOICE_COPY_LABELS[kind][language]))
|
|
3204
|
+
})));
|
|
3205
|
+
/**
|
|
3206
|
+
* The paragraph a copy of an e-invoice of `kind` is labelled with in a
|
|
3207
|
+
* render that prints in `locale`, as the runtime writes it; undefined
|
|
3208
|
+
* where no label is written in that locale's language. Frozen, and the
|
|
3209
|
+
* same object each time: a document carries a paragraph of its own.
|
|
3210
|
+
*/
|
|
3211
|
+
function eInvoiceCopyParagraph(kind, locale) {
|
|
3212
|
+
const language = locale.split("-")[0].toLowerCase();
|
|
3213
|
+
return PARAGRAPHS.find((each) => each.kind === kind && each.language === language)?.paragraph;
|
|
3214
|
+
}
|
|
3215
|
+
/**
|
|
3216
|
+
* The copy's label `header` opens with, or undefined where it opens with
|
|
3217
|
+
* none: a paragraph of one run whose text is a label's, whatever its
|
|
3218
|
+
* style, as a preview's label is read (0057). `asWritten` says whether
|
|
3219
|
+
* the paragraph is the runtime's whole -- its size, bold and its colour,
|
|
3220
|
+
* and nothing else -- which an engine that writes a copy holds it to:
|
|
3221
|
+
* the words in white say nothing to a reader. A label among other runs,
|
|
3222
|
+
* or below another block, heads nothing and is not found.
|
|
3223
|
+
*/
|
|
3224
|
+
function readCopyLabel(header) {
|
|
3225
|
+
const first = header[0];
|
|
3226
|
+
if (first?.kind !== "paragraph" || first.runs.length !== 1) return void 0;
|
|
3227
|
+
const run = first.runs[0];
|
|
3228
|
+
if (!("text" in run)) return void 0;
|
|
3229
|
+
const known = PARAGRAPHS.find(({ paragraph }) => paragraph.runs[0].text === run.text);
|
|
3230
|
+
return known === void 0 ? void 0 : {
|
|
3231
|
+
...known,
|
|
3232
|
+
asWritten: samePlain(first, known.paragraph)
|
|
3233
|
+
};
|
|
3234
|
+
}
|
|
3235
|
+
/** Whether two values of a resolved document are the same data: equal primitives, or two arrays, or two objects that are not, of the same keys holding the same values. */
|
|
3236
|
+
function samePlain(a, b) {
|
|
3237
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return a === b;
|
|
3238
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
3239
|
+
const [left, right] = [Object.keys(a), Object.keys(b)];
|
|
3240
|
+
return left.length === right.length && left.every((key) => right.includes(key) && samePlain(a[key], b[key]));
|
|
3241
|
+
}
|
|
3242
|
+
// src/xml.ts
|
|
3243
|
+
/**
|
|
3244
|
+
* XML, written one way: a tree of elements serialised with the same bytes
|
|
3245
|
+
* for the same tree, every text escaped so that a parser gives back exactly
|
|
3246
|
+
* what was written. The e-invoice's CII is built as such a tree
|
|
3247
|
+
* (`cii.ts`), and this is the one place it becomes text.
|
|
3248
|
+
*
|
|
3249
|
+
* Exactly, to a parser: a reader that applies the schema reads an element
|
|
3250
|
+
* the XSD types as xs:token -- an identifier, a code -- with its white
|
|
3251
|
+
* space collapsed. report-spec's rules refuse such a text that holds any
|
|
3252
|
+
* (`token` in `en16931.ts`), so what such a reader reads is what was
|
|
3253
|
+
* written too.
|
|
3254
|
+
*
|
|
3255
|
+
* - **Deterministic.** `<?xml version="1.0" encoding="UTF-8"?>`, no byte
|
|
3256
|
+
* order mark, a line feed after every line, two spaces a level, an empty
|
|
3257
|
+
* element closed at once, attributes in the order given. Nothing reads a
|
|
3258
|
+
* clock or the machine.
|
|
3259
|
+
* - **Escaped.** In text `&`, `<` and `>`, and a carriage return as
|
|
3260
|
+
* ` `, which a parser would otherwise read as a line feed (XML 1.0,
|
|
3261
|
+
* 2.11). In an attribute the double quote too, and a tab, a line feed and
|
|
3262
|
+
* a carriage return as references, which a parser would otherwise read
|
|
3263
|
+
* as spaces (3.3.3).
|
|
3264
|
+
* - **Never a character XML 1.0 cannot hold.** report-spec's
|
|
3265
|
+
* `xmlCharacterBreak` decides which: the e-invoice's rules refuse a text
|
|
3266
|
+
* that holds one where it is read, naming its term. One that reaches the
|
|
3267
|
+
* writer anyway is a defect, thrown as a RangeError, never dropped, since
|
|
3268
|
+
* dropping it would change what the invoice says.
|
|
3269
|
+
*/
|
|
3270
|
+
/** An element holding `children`, in order; an undefined child is a term the document leaves out. */
|
|
3271
|
+
function element(name, children, attributes = []) {
|
|
3272
|
+
return {
|
|
3273
|
+
name,
|
|
3274
|
+
attributes,
|
|
3275
|
+
content: children.filter((child) => child !== void 0)
|
|
3276
|
+
};
|
|
3277
|
+
}
|
|
3278
|
+
/** An element holding the text `text`. */
|
|
3279
|
+
function leaf(name, text, attributes = []) {
|
|
3280
|
+
return {
|
|
3281
|
+
name,
|
|
3282
|
+
attributes,
|
|
3283
|
+
content: text
|
|
3284
|
+
};
|
|
3285
|
+
}
|
|
3286
|
+
/** `text` with no character XML 1.0 cannot write; a RangeError when it holds one, which the rules refuse before. */
|
|
3287
|
+
function writable(text) {
|
|
3288
|
+
const broken = xmlCharacterBreak(text);
|
|
3289
|
+
if (broken !== void 0) throw new RangeError(`a text ${broken}; the e-invoice's rules refuse it where it is read`);
|
|
3290
|
+
return text;
|
|
3291
|
+
}
|
|
3292
|
+
const TEXT = /[&<>\r]/g;
|
|
3293
|
+
const ATTRIBUTE = /[&<>"\t\n\r]/g;
|
|
3294
|
+
const REFERENCES = {
|
|
3295
|
+
"&": "&",
|
|
3296
|
+
"<": "<",
|
|
3297
|
+
">": ">",
|
|
3298
|
+
"\"": """,
|
|
3299
|
+
" ": "	",
|
|
3300
|
+
"\n": " ",
|
|
3301
|
+
"\r": " "
|
|
3302
|
+
};
|
|
3303
|
+
const escaped = (pattern) => (text) => writable(text).replace(pattern, (character) => REFERENCES[character]);
|
|
3304
|
+
const text$1 = escaped(TEXT);
|
|
3305
|
+
const attribute = escaped(ATTRIBUTE);
|
|
3306
|
+
/** `node` written into `lines`, at `depth` levels. */
|
|
3307
|
+
function write(node, depth, lines) {
|
|
3308
|
+
const indent = " ".repeat(depth);
|
|
3309
|
+
const open = `${indent}<${node.name}${node.attributes.map(([name, value]) => ` ${name}="${attribute(value)}"`).join("")}`;
|
|
3310
|
+
if (typeof node.content === "string") {
|
|
3311
|
+
lines.push(`${open}>${text$1(node.content)}</${node.name}>`);
|
|
3312
|
+
return;
|
|
3313
|
+
}
|
|
3314
|
+
if (node.content.length === 0) {
|
|
3315
|
+
lines.push(`${open}/>`);
|
|
3316
|
+
return;
|
|
3317
|
+
}
|
|
3318
|
+
lines.push(`${open}>`);
|
|
3319
|
+
for (const child of node.content) write(child, depth + 1, lines);
|
|
3320
|
+
lines.push(`${indent}</${node.name}>`);
|
|
3321
|
+
}
|
|
3322
|
+
/** The document whose root is `root`, as UTF-8 XML text: its declaration first, a line feed after every line. */
|
|
3323
|
+
function xmlDocument(root) {
|
|
3324
|
+
const lines = ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
|
|
3325
|
+
write(root, 0, lines);
|
|
3326
|
+
return `${lines.join("\n")}\n`;
|
|
3327
|
+
}
|
|
3328
|
+
// src/cii-parties.ts
|
|
3329
|
+
/** `make` of `value` where there is one; nothing where the term is left out. */
|
|
3330
|
+
function optional$1(value, make) {
|
|
3331
|
+
return value === void 0 ? void 0 : make(value);
|
|
3332
|
+
}
|
|
3333
|
+
/** BG-5 or BG-8: the post code, the lines, the city and the country (BT-38, 35, 36, 37, 40; BT-53, 50, 51, 52, 55). */
|
|
3334
|
+
function postalAddress(address) {
|
|
3335
|
+
return element("ram:PostalTradeAddress", [
|
|
3336
|
+
leaf("ram:PostcodeCode", address.postalCode),
|
|
3337
|
+
leaf("ram:LineOne", address.line1),
|
|
3338
|
+
optional$1(address.line2, (line) => leaf("ram:LineTwo", line)),
|
|
3339
|
+
leaf("ram:CityName", address.city),
|
|
3340
|
+
leaf("ram:CountryID", address.country)
|
|
3341
|
+
]);
|
|
3342
|
+
}
|
|
3343
|
+
/** BG-6: the contact point (BT-41), the telephone number (BT-42) and the email address (BT-43), all three, as a contact gives them; no element where the seller names none. */
|
|
3344
|
+
function tradeContact(contact) {
|
|
3345
|
+
if (contact === void 0) return void 0;
|
|
3346
|
+
return element("ram:DefinedTradeContact", [
|
|
3347
|
+
leaf("ram:PersonName", contact.name),
|
|
3348
|
+
element("ram:TelephoneUniversalCommunication", [leaf("ram:CompleteNumber", contact.telephone)]),
|
|
3349
|
+
element("ram:EmailURIUniversalCommunication", [leaf("ram:URIID", contact.email)])
|
|
3350
|
+
]);
|
|
3351
|
+
}
|
|
3352
|
+
/**
|
|
3353
|
+
* The seller or the buyer: its name (BT-27, BT-44), its legal registration
|
|
3354
|
+
* and its scheme (BT-30, BT-47), the seller's contact (BG-6), its address,
|
|
3355
|
+
* its electronic address and its scheme (BT-34, BT-49), its VAT
|
|
3356
|
+
* identifier (BT-31, BT-48) and, the seller's, its tax number (BT-32).
|
|
3357
|
+
*/
|
|
3358
|
+
function tradeParty(name, party) {
|
|
3359
|
+
const registration = party.legalId;
|
|
3360
|
+
const reached = party.electronicAddress;
|
|
3361
|
+
return element(name, [
|
|
3362
|
+
leaf("ram:Name", party.name),
|
|
3363
|
+
registration === void 0 ? void 0 : element("ram:SpecifiedLegalOrganization", [leaf("ram:ID", registration.id, registration.scheme === void 0 ? [] : [["schemeID", registration.scheme]])]),
|
|
3364
|
+
tradeContact(party.contact),
|
|
3365
|
+
postalAddress(party.address),
|
|
3366
|
+
reached === void 0 ? void 0 : element("ram:URIUniversalCommunication", [leaf("ram:URIID", reached.id, [["schemeID", reached.scheme]])]),
|
|
3367
|
+
optional$1(party.vatId, (id) => element("ram:SpecifiedTaxRegistration", [leaf("ram:ID", id, [["schemeID", "VA"]])])),
|
|
3368
|
+
optional$1(party.taxNumber, (id) => element("ram:SpecifiedTaxRegistration", [leaf("ram:ID", id, [["schemeID", "FC"]])]))
|
|
3369
|
+
]);
|
|
3370
|
+
}
|
|
3371
|
+
/**
|
|
3372
|
+
* BG-16: the means (BT-81), the account by its IBAN (BT-84) and its name
|
|
3373
|
+
* (BT-85), and the BIC of its bank (BT-86). The remittance information
|
|
3374
|
+
* (BT-83) is the settlement's `PaymentReference`, which `cii.ts` writes.
|
|
3375
|
+
*/
|
|
3376
|
+
function paymentMeans(payment) {
|
|
3377
|
+
return element("ram:SpecifiedTradeSettlementPaymentMeans", [
|
|
3378
|
+
leaf("ram:TypeCode", payment.means),
|
|
3379
|
+
element("ram:PayeePartyCreditorFinancialAccount", [leaf("ram:IBANID", payment.account), optional$1(payment.accountName, (name) => leaf("ram:AccountName", name))]),
|
|
3380
|
+
optional$1(payment.bic, (bic) => element("ram:PayeeSpecifiedCreditorFinancialInstitution", [leaf("ram:BICID", bic)]))
|
|
3381
|
+
]);
|
|
3382
|
+
}
|
|
3383
|
+
// src/cii.ts
|
|
3384
|
+
/**
|
|
3385
|
+
* An e-invoice written as UN/CEFACT Cross Industry Invoice XML in the
|
|
3386
|
+
* Factur-X 1.09.2 / ZUGFeRD 2.5.2 EN 16931 profile (0027), or as an
|
|
3387
|
+
* XRechnung 3.0 (0038): the runtime's, as the QR-bill's payload is, since
|
|
3388
|
+
* the XML is the invoice's payload and the renderer decides none of it.
|
|
3389
|
+
* One writer for both kinds: the XML of an XRechnung is the XML of a
|
|
3390
|
+
* Factur-X invoice of the same terms, but for the specification
|
|
3391
|
+
* identifier (BT-24) it opens with, which says whose rules it follows.
|
|
3392
|
+
*
|
|
3393
|
+
* - **Its shape.** The root `rsm:CrossIndustryInvoice` with the four
|
|
3394
|
+
* namespaces of CEN/TC 434's binding; its context (BT-23, BT-24), its document
|
|
3395
|
+
* (BT-1, BT-3, BT-2) and its transaction: the lines, then the
|
|
3396
|
+
* agreement, the delivery and the settlement, each element in the order
|
|
3397
|
+
* the profile's XSD `xs:sequence` gives it, at the path CEN's binding
|
|
3398
|
+
* gives each business term. Only elements D16B shares with D22B are
|
|
3399
|
+
* written, since the validators run the D16B schema.
|
|
3400
|
+
* - **Dates** are `udt:DateTimeString` of format 102, YYYYMMDD.
|
|
3401
|
+
* - **The delivery**, which the XSD needs once, is written empty where the
|
|
3402
|
+
* invoice gives an invoicing period and no delivery date: it has nothing
|
|
3403
|
+
* else to hold. Mustang 2.26.0's Factur-X schematron warns of that empty
|
|
3404
|
+
* element (PEPPOL-EN16931-R008, "still status warning"), and KoSIT's
|
|
3405
|
+
* EN 16931 scenario does not, measured by hand on 17 October 2026.
|
|
3406
|
+
* - **Amounts** are written from their own digits with exactly two places;
|
|
3407
|
+
* only `TaxTotalAmount` names its currency (CII-DT-031). A quantity and
|
|
3408
|
+
* a net price, which CEN does not hold to two places, are written as the
|
|
3409
|
+
* template's columns resolved them; a rate by value, `19`, `7`, `0`.
|
|
3410
|
+
* - **Its order** is the template's and the table's: categories as
|
|
3411
|
+
* declared, lines as the table prints them. The same invoice is the same
|
|
3412
|
+
* bytes (`xml.ts`).
|
|
3413
|
+
*
|
|
3414
|
+
* Every value is one the rules have already held (`e-invoice-lines.ts`,
|
|
3415
|
+
* `e-invoice-terms.ts`) and every total one `e-invoice-totals.ts`
|
|
3416
|
+
* computed: nothing here decides, rounds or checks.
|
|
3417
|
+
*/
|
|
3418
|
+
/** CEN/TC 434's CII namespaces, as its schematron declares them. */
|
|
3419
|
+
const NAMESPACES = [
|
|
3420
|
+
["xmlns:rsm", "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"],
|
|
3421
|
+
["xmlns:qdt", "urn:un:unece:uncefact:data:standard:QualifiedDataType:100"],
|
|
3422
|
+
["xmlns:ram", "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"],
|
|
3423
|
+
["xmlns:udt", "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100"]
|
|
3424
|
+
];
|
|
3425
|
+
/** A date, YYYY-MM-DD as the runtime holds one, as CII writes it: format 102, YYYYMMDD. */
|
|
3426
|
+
function dateTime(name, date) {
|
|
3427
|
+
return element(name, [leaf("udt:DateTimeString", date.replaceAll("-", ""), [["format", "102"]])]);
|
|
3428
|
+
}
|
|
3429
|
+
/** An amount, from its own digits; a RangeError for one not at the two places every total and line amount is computed at. */
|
|
3430
|
+
function amount$2(name, value, attributes = []) {
|
|
3431
|
+
if (value.scale !== 2) throw new RangeError(`${name} is at ${value.scale} places, and an e-invoice's amounts are computed at two`);
|
|
3432
|
+
return leaf(name, decimalToString(value), attributes);
|
|
3433
|
+
}
|
|
3434
|
+
/** A tax (BT-118, BT-119; at a line BT-151, BT-152): `VAT`, its category and its rate, and its reason, basis and amount where a breakdown has them. */
|
|
3435
|
+
function tradeTax(breakdown, totals) {
|
|
3436
|
+
return element("ram:ApplicableTradeTax", [
|
|
3437
|
+
totals === void 0 ? void 0 : amount$2("ram:CalculatedAmount", breakdown.amount),
|
|
3438
|
+
leaf("ram:TypeCode", "VAT"),
|
|
3439
|
+
optional$1(totals?.reason, (reason) => leaf("ram:ExemptionReason", reason)),
|
|
3440
|
+
totals === void 0 ? void 0 : amount$2("ram:BasisAmount", breakdown.basis),
|
|
3441
|
+
leaf("ram:CategoryCode", breakdown.category.code),
|
|
3442
|
+
leaf("ram:RateApplicablePercent", breakdown.rate)
|
|
3443
|
+
]);
|
|
3444
|
+
}
|
|
3445
|
+
/** A line (BG-25): its identifier (BT-126), its item (BT-153), its net price (BT-146), its quantity and unit (BT-129, BT-130), its tax and its net amount (BT-131). */
|
|
3446
|
+
function line(each, breakdown) {
|
|
3447
|
+
return element("ram:IncludedSupplyChainTradeLineItem", [
|
|
3448
|
+
element("ram:AssociatedDocumentLineDocument", [leaf("ram:LineID", each.id)]),
|
|
3449
|
+
element("ram:SpecifiedTradeProduct", [leaf("ram:Name", each.name)]),
|
|
3450
|
+
element("ram:SpecifiedLineTradeAgreement", [element("ram:NetPriceProductTradePrice", [leaf("ram:ChargeAmount", each.netPrice)])]),
|
|
3451
|
+
element("ram:SpecifiedLineTradeDelivery", [leaf("ram:BilledQuantity", each.quantity, [["unitCode", each.unit]])]),
|
|
3452
|
+
element("ram:SpecifiedLineTradeSettlement", [tradeTax(breakdown), element("ram:SpecifiedTradeSettlementLineMonetarySummation", [amount$2("ram:LineTotalAmount", each.netAmount)])])
|
|
3453
|
+
]);
|
|
3454
|
+
}
|
|
3455
|
+
/** The settlement: the remittance (BT-83), the currency (BT-5), the payment, the breakdown, the period (BG-14), the terms (BT-20, BT-9) and the totals (BG-22). */
|
|
3456
|
+
function settlement(invoice) {
|
|
3457
|
+
const { terms, totals, currency } = invoice;
|
|
3458
|
+
const period = terms.period;
|
|
3459
|
+
return element("ram:ApplicableHeaderTradeSettlement", [
|
|
3460
|
+
optional$1(terms.payment?.remittance, (remittance) => leaf("ram:PaymentReference", remittance)),
|
|
3461
|
+
leaf("ram:InvoiceCurrencyCode", currency),
|
|
3462
|
+
terms.payment === void 0 ? void 0 : paymentMeans(terms.payment),
|
|
3463
|
+
...totals.breakdown.map((breakdown) => tradeTax(breakdown, { reason: terms.reasons.get(breakdown.category.id) })),
|
|
3464
|
+
period === void 0 ? void 0 : element("ram:BillingSpecifiedPeriod", [optional$1(period.start, (start) => dateTime("ram:StartDateTime", start)), optional$1(period.end, (end) => dateTime("ram:EndDateTime", end))]),
|
|
3465
|
+
terms.terms === void 0 && terms.due === void 0 ? void 0 : element("ram:SpecifiedTradePaymentTerms", [optional$1(terms.terms, (text) => leaf("ram:Description", text)), optional$1(terms.due, (due) => dateTime("ram:DueDateDateTime", due))]),
|
|
3466
|
+
element("ram:SpecifiedTradeSettlementHeaderMonetarySummation", [
|
|
3467
|
+
amount$2("ram:LineTotalAmount", totals.lineTotal),
|
|
3468
|
+
amount$2("ram:TaxBasisTotalAmount", totals.taxBasisTotal),
|
|
3469
|
+
amount$2("ram:TaxTotalAmount", totals.taxTotal, [["currencyID", currency]]),
|
|
3470
|
+
amount$2("ram:GrandTotalAmount", totals.grandTotal),
|
|
3471
|
+
totals.paid === null ? void 0 : amount$2("ram:TotalPrepaidAmount", totals.paid),
|
|
3472
|
+
amount$2("ram:DuePayableAmount", totals.duePayable)
|
|
3473
|
+
])
|
|
3474
|
+
]);
|
|
3475
|
+
}
|
|
3476
|
+
/** `invoice` as CII XML, UTF-8 text with its declaration, the same bytes for the same invoice. */
|
|
3477
|
+
function ciiXml(invoice) {
|
|
3478
|
+
const { terms, totals } = invoice;
|
|
3479
|
+
const breakdowns = new Map(totals.breakdown.map((breakdown) => [breakdown.category.id, breakdown]));
|
|
3480
|
+
return xmlDocument(element("rsm:CrossIndustryInvoice", [
|
|
3481
|
+
element("rsm:ExchangedDocumentContext", [optional$1(terms.businessProcess, (process) => element("ram:BusinessProcessSpecifiedDocumentContextParameter", [leaf("ram:ID", process)])), element("ram:GuidelineSpecifiedDocumentContextParameter", [leaf("ram:ID", invoice.guideline)])]),
|
|
3482
|
+
element("rsm:ExchangedDocument", [
|
|
3483
|
+
leaf("ram:ID", terms.number),
|
|
3484
|
+
leaf("ram:TypeCode", invoice.type),
|
|
3485
|
+
dateTime("ram:IssueDateTime", terms.issued)
|
|
3486
|
+
]),
|
|
3487
|
+
element("rsm:SupplyChainTradeTransaction", [
|
|
3488
|
+
...invoice.lines.map((each) => line(each, breakdowns.get(each.category.id))),
|
|
3489
|
+
element("ram:ApplicableHeaderTradeAgreement", [
|
|
3490
|
+
optional$1(terms.buyerReference, (reference) => leaf("ram:BuyerReference", reference)),
|
|
3491
|
+
tradeParty("ram:SellerTradeParty", terms.seller),
|
|
3492
|
+
tradeParty("ram:BuyerTradeParty", terms.buyer)
|
|
3493
|
+
]),
|
|
3494
|
+
element("ram:ApplicableHeaderTradeDelivery", [optional$1(terms.delivered, (delivered) => element("ram:ActualDeliverySupplyChainEvent", [dateTime("ram:OccurrenceDateTime", delivered)]))]),
|
|
3495
|
+
settlement(invoice)
|
|
3496
|
+
])
|
|
3497
|
+
], NAMESPACES));
|
|
3498
|
+
}
|
|
3499
|
+
// src/e-invoice-totals.ts
|
|
3500
|
+
/**
|
|
3501
|
+
* An e-invoice's totals and VAT breakdown, computed once, here, from its
|
|
3502
|
+
* lines (0027): the page prints them through `invoice`, `vatBasis` and
|
|
3503
|
+
* `vatAmount`, and the XML is written from the very same values, so the
|
|
3504
|
+
* two cannot part. The rules are CEN/TC 434's CII artefacts 1.3.17's, by
|
|
3505
|
+
* number.
|
|
3506
|
+
*
|
|
3507
|
+
* | Value | Computed as | Rule |
|
|
3508
|
+
* |---|---|---|
|
|
3509
|
+
* | BT-131 | BT-129 × BT-146, rounded once to two places: held, not written from it | EN 16931's definition; PEPPOL-EN16931-R120 |
|
|
3510
|
+
* | BT-106 | Σ BT-131, each a whole number of cents | BR-CO-10 |
|
|
3511
|
+
* | BT-109 | BT-106: there are no allowances or charges | BR-CO-13 |
|
|
3512
|
+
* | BT-116 | Σ BT-131 of the category's lines | BR-S-08, BR-E-08, BR-AE-08 |
|
|
3513
|
+
* | BT-117 | BT-116 × BT-119 / 100, rounded once to two places, half away from zero | BR-CO-17, BR-E-09, BR-AE-09 |
|
|
3514
|
+
* | BT-110 | Σ BT-117 | BR-CO-14 |
|
|
3515
|
+
* | BT-112 | BT-109 + BT-110 | BR-CO-15 |
|
|
3516
|
+
* | BT-115 | BT-112 − BT-113; there is no BT-114 | BR-CO-16 |
|
|
3517
|
+
*
|
|
3518
|
+
* - **Exact.** In `@formancy/expressions`' `Decimal`, a value as an integer
|
|
3519
|
+
* of units at a scale; nothing passes through a JavaScript number.
|
|
3520
|
+
* Dividing by 100 moves the point and loses nothing, so a category's tax
|
|
3521
|
+
* is the exact product rounded once. CEN tests BR-CO-17 and BR-S-09
|
|
3522
|
+
* within one unit of the currency either way, a euro, and the exact
|
|
3523
|
+
* product rounded once lies inside.
|
|
3524
|
+
* - **Per category, once.** VAT is rounded per category, never per line:
|
|
3525
|
+
* an ERP that rounds each line can differ by up to half a cent a line,
|
|
3526
|
+
* which is said where the costs are.
|
|
3527
|
+
* - **Half away from zero**, as upstream's `roundDecimal` rounds and as a
|
|
3528
|
+
* person rounds by hand. CEN's tests round the absolute value, where half
|
|
3529
|
+
* away from zero and XPath's `round` agree.
|
|
3530
|
+
* - **A breakdown for each category a line is in**, in the order the
|
|
3531
|
+
* invoice declares them: BR-E-01 and BR-AE-01 refuse one for a category
|
|
3532
|
+
* no line has, and one invoice is one XML.
|
|
3533
|
+
*/
|
|
3534
|
+
const ZERO = new Decimal(0n, 2);
|
|
3535
|
+
/** `amount`, which a defect of the caller's would have written at another scale than the two places the XML writes. */
|
|
3536
|
+
function cents(amount, what) {
|
|
3537
|
+
if (amount.scale !== 2) throw new RangeError(`${what} is at ${amount.scale} places, and the e-invoice's lines are read at two`);
|
|
3538
|
+
return amount;
|
|
3539
|
+
}
|
|
3540
|
+
const sum = (amounts) => {
|
|
3541
|
+
let total = ZERO;
|
|
3542
|
+
for (const amount of amounts) total = addDecimal(total, amount);
|
|
3543
|
+
return total;
|
|
3544
|
+
};
|
|
3545
|
+
/**
|
|
3546
|
+
* A line's net amount (BT-131) as EN 16931 makes it, which the lines'
|
|
3547
|
+
* reader holds each line's to: its quantity (BT-129) times its net price
|
|
3548
|
+
* (BT-146), each as the XML writes it, rounded once to two places, half
|
|
3549
|
+
* away from zero, as BT-117 is. This version writes no line allowance or
|
|
3550
|
+
* charge and no base quantity (BT-149), which would enter it.
|
|
3551
|
+
*/
|
|
3552
|
+
function lineNetAmount(quantity, netPrice) {
|
|
3553
|
+
return roundDecimal(multiplyDecimal(decimalFromString(quantity), decimalFromString(netPrice)), 2);
|
|
3554
|
+
}
|
|
3555
|
+
/** BT-117 of a category of `rate` over `basis`: the exact product over 100, rounded once to two places, half away from zero. */
|
|
3556
|
+
function tax(basis, rate) {
|
|
3557
|
+
const product = multiplyDecimal(basis, decimalFromString(rate));
|
|
3558
|
+
return roundDecimal(new Decimal(product.units, product.scale + 2), 2);
|
|
3559
|
+
}
|
|
3560
|
+
/**
|
|
3561
|
+
* The totals of `lines`, each in one of `categories`, as declared; `paid`
|
|
3562
|
+
* the amount already paid (BT-113), or null. Every amount it is handed is
|
|
3563
|
+
* at exactly two places, as the lines' reader writes it, and a RangeError
|
|
3564
|
+
* says a caller handed one that is not.
|
|
3565
|
+
*/
|
|
3566
|
+
function invoiceTotals(categories, lines, paid) {
|
|
3567
|
+
const amounts = lines.map((line, index) => cents(line.netAmount, `line ${index}'s net amount`));
|
|
3568
|
+
const breakdown = categories.flatMap((category) => {
|
|
3569
|
+
const own = lines.flatMap((line, index) => line.category === category ? [amounts[index]] : []);
|
|
3570
|
+
if (own.length === 0) return [];
|
|
3571
|
+
const basis = sum(own);
|
|
3572
|
+
return [{
|
|
3573
|
+
category,
|
|
3574
|
+
rate: checkVatRate(category.code, category.rate).value,
|
|
3575
|
+
basis,
|
|
3576
|
+
amount: tax(basis, category.rate)
|
|
3577
|
+
}];
|
|
3578
|
+
});
|
|
3579
|
+
const lineTotal = sum(amounts);
|
|
3580
|
+
const taxTotal = sum(breakdown.map(({ amount }) => amount));
|
|
3581
|
+
const grandTotal = addDecimal(lineTotal, taxTotal);
|
|
3582
|
+
const prepaid = paid === null ? null : cents(paid, "the paid amount");
|
|
3583
|
+
return {
|
|
3584
|
+
lineTotal,
|
|
3585
|
+
taxBasisTotal: lineTotal,
|
|
3586
|
+
taxTotal,
|
|
3587
|
+
grandTotal,
|
|
3588
|
+
paid: prepaid,
|
|
3589
|
+
duePayable: prepaid === null ? grandTotal : subtractDecimal(grandTotal, prepaid),
|
|
3590
|
+
breakdown
|
|
3591
|
+
};
|
|
3592
|
+
}
|
|
3593
|
+
/**
|
|
3594
|
+
* What the e-invoice's names hold, as an expression is handed them (0027,
|
|
3595
|
+
* beside 0009): `invoice` each document total, `paid` only where the
|
|
3596
|
+
* invoice declares a paid amount, as report-core binds it; `vatBasis` and
|
|
3597
|
+
* `vatAmount` each declared category's basis and tax by its id, null where
|
|
3598
|
+
* no line is in it, which prints as nothing (0007). The very values the
|
|
3599
|
+
* XML is written from.
|
|
3600
|
+
*/
|
|
3601
|
+
function invoiceNames(invoice, totals) {
|
|
3602
|
+
const of = (category) => totals.breakdown.find((each) => each.category.id === category.id);
|
|
3603
|
+
return {
|
|
3604
|
+
invoice: {
|
|
3605
|
+
lineTotal: totals.lineTotal,
|
|
3606
|
+
taxBasisTotal: totals.taxBasisTotal,
|
|
3607
|
+
taxTotal: totals.taxTotal,
|
|
3608
|
+
grandTotal: totals.grandTotal,
|
|
3609
|
+
...invoice.paid === void 0 ? {} : { paid: totals.paid },
|
|
3610
|
+
duePayable: totals.duePayable
|
|
3611
|
+
},
|
|
3612
|
+
vatBasis: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.basis ?? null])),
|
|
3613
|
+
vatAmount: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.amount ?? null]))
|
|
3614
|
+
};
|
|
3615
|
+
}
|
|
3616
|
+
// src/inlines.ts
|
|
3617
|
+
/**
|
|
3618
|
+
* The totals an aggregate run reads, by what it is over: every detail
|
|
3619
|
+
* row's wherever it stands, or the current table's or group's. report-spec
|
|
3620
|
+
* allows a table's only in its total rows and its group's rows, and a
|
|
3621
|
+
* group's only in a group's (0062), where the scope holds them.
|
|
3622
|
+
*/
|
|
3623
|
+
const OVER = {
|
|
3624
|
+
report: (render) => render.totals.report,
|
|
3625
|
+
table: (_, scope) => scope.table,
|
|
3626
|
+
group: (_, scope) => scope.group
|
|
3627
|
+
};
|
|
3628
|
+
/** The value `inline`, at `path`, reads in `scope`, unformatted; undefined when its evaluation failed, which is recorded. */
|
|
3629
|
+
function inlineValue(render, scope, inline, path) {
|
|
3630
|
+
switch (inline.kind) {
|
|
3631
|
+
case "field": return fieldValue(render, scope.record, inline.field);
|
|
3632
|
+
case "parameter": {
|
|
3633
|
+
const value = render.params[inline.parameter] ?? null;
|
|
3634
|
+
return value === null ? null : {
|
|
3635
|
+
type: parameterType(render.report, inline.parameter),
|
|
3636
|
+
value
|
|
3637
|
+
};
|
|
3638
|
+
}
|
|
3639
|
+
case "expression": return valueOf(render, scope, `${path}/expression/cel`);
|
|
3640
|
+
case "aggregate": return OVER[inline.over](render, scope)?.get(inline.aggregate) ?? null;
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
/** What the e-invoice kept of the detail row `row` for the column value at `path`: the value, null among them; or undefined where it kept nothing. */
|
|
3644
|
+
function kept(render, path, row) {
|
|
3645
|
+
const column = row === void 0 ? void 0 : render.invoice?.columns.get(path);
|
|
3646
|
+
return column === void 0 ? void 0 : { value: column[row] };
|
|
3647
|
+
}
|
|
3648
|
+
/** The value `inline` reads in `scope`, and the text it prints; undefined when either could not be had, which is recorded. */
|
|
3649
|
+
function printed(render, scope, inline, path, owner) {
|
|
3650
|
+
const read = kept(render, path, scope.row);
|
|
3651
|
+
const value = read === void 0 ? inlineValue(render, scope, inline, path) : read.value;
|
|
3652
|
+
if (value === void 0) return void 0;
|
|
3653
|
+
const formatted = render.formatter.format(value, inline.format, scope.currency);
|
|
3654
|
+
if (formatted.ok) return {
|
|
3655
|
+
value,
|
|
3656
|
+
text: formatted.text
|
|
3657
|
+
};
|
|
3658
|
+
const where = [
|
|
3659
|
+
owner.componentId === void 0 ? owner.said : `component ${owner.componentId}`,
|
|
3660
|
+
owner.columnId && `column ${owner.columnId}`,
|
|
3661
|
+
scope.row !== void 0 && `detail row ${scope.row}`
|
|
3662
|
+
].filter(Boolean).join(", ");
|
|
3663
|
+
render.problems.error({
|
|
3664
|
+
stage: "format",
|
|
3665
|
+
code: formatted.code,
|
|
3666
|
+
path,
|
|
3667
|
+
message: `${where}: ${formatted.message}`,
|
|
3668
|
+
...placed({
|
|
3669
|
+
componentId: owner.componentId,
|
|
3670
|
+
columnId: owner.columnId,
|
|
3671
|
+
row: scope.row
|
|
3672
|
+
})
|
|
3673
|
+
});
|
|
3674
|
+
}
|
|
3675
|
+
/**
|
|
3676
|
+
* `inline`, at `path` in the report, as the run it prints in `scope`;
|
|
3677
|
+
* undefined when it could not be, which is recorded. A run carries the
|
|
3678
|
+
* baseline its source sets (0061), and a run that sets none carries no key,
|
|
3679
|
+
* so that the document of a report that sets none is the one it was. A
|
|
3680
|
+
* table's cell joins its runs' text and drops it, where report-spec refuses
|
|
3681
|
+
* one.
|
|
3682
|
+
*/
|
|
3683
|
+
function runOf(render, scope, inline, path, owner) {
|
|
3684
|
+
if (inline.kind === "pageNumber" || inline.kind === "pageCount") return { field: inline.kind };
|
|
3685
|
+
const shift = inline.baseline === void 0 ? {} : { baseline: inline.baseline };
|
|
3686
|
+
if (inline.kind === "text") return {
|
|
3687
|
+
text: inline.text,
|
|
3688
|
+
...shift
|
|
3689
|
+
};
|
|
3690
|
+
const run = printed(render, scope, inline, path, owner);
|
|
3691
|
+
return run && {
|
|
3692
|
+
text: run.text,
|
|
3693
|
+
...shift
|
|
3694
|
+
};
|
|
3695
|
+
}
|
|
3696
|
+
/** What a code of less than its runs would scan as, by what they are encoded in. */
|
|
3697
|
+
const SCANNED_AS = {
|
|
3698
|
+
"a QR code": "some other text",
|
|
3699
|
+
"a QR-bill": "some other bill",
|
|
3700
|
+
"an EPC QR code": "some other transfer"
|
|
3701
|
+
};
|
|
3702
|
+
/**
|
|
3703
|
+
* The runs at `path`, read in `scope` run by run as a paragraph's are, so
|
|
3704
|
+
* that what a code or an e-invoice holds and what a paragraph prints never
|
|
3705
|
+
* format a value apart. A page counter has no value before there are
|
|
3706
|
+
* pages, and report-spec refuses one wherever runs are read so; one that
|
|
3707
|
+
* reaches here all the same throws, naming what holds it, never read as
|
|
3708
|
+
* nothing.
|
|
3709
|
+
*/
|
|
3710
|
+
function readRuns(render, scope, runs, path, owner) {
|
|
3711
|
+
const texts = [];
|
|
3712
|
+
const nulls = [];
|
|
3713
|
+
let refused = false;
|
|
3714
|
+
for (const [index, inline] of runs.entries()) {
|
|
3715
|
+
const at = `${path}/${index}`;
|
|
3716
|
+
if (inline.kind === "pageNumber" || inline.kind === "pageCount") throw new RangeError(`${owner.said} holds a ${inline.kind} at ${at}, which has no value before there are pages; report-spec refuses it`);
|
|
3717
|
+
const run = inline.kind === "text" ? {
|
|
3718
|
+
value: void 0,
|
|
3719
|
+
text: inline.text
|
|
3720
|
+
} : printed(render, scope, inline, at, owner);
|
|
3721
|
+
if (run === void 0) refused = true;
|
|
3722
|
+
else {
|
|
3723
|
+
if (run.value === null) nulls.push(at);
|
|
3724
|
+
texts.push(run.text);
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
return {
|
|
3728
|
+
text: texts.join(""),
|
|
3729
|
+
nulls,
|
|
3730
|
+
refused
|
|
3731
|
+
};
|
|
3732
|
+
}
|
|
3733
|
+
/**
|
|
3734
|
+
* The text `runs`, at `path`, join to when they are encoded in a code,
|
|
3735
|
+
* read as `readRuns` reads them. Undefined when a run is refused, which is
|
|
3736
|
+
* recorded, naming `encoder`.
|
|
3737
|
+
*
|
|
3738
|
+
* A final render refuses a run whose value is null: a code of less than
|
|
3739
|
+
* its content scans as some other text, and the page does not say so. A
|
|
3740
|
+
* preview encodes it as nothing, as a paragraph prints it, and says it
|
|
3741
|
+
* did.
|
|
3742
|
+
*
|
|
3743
|
+
* `unused` is given for a text its code may leave out, and says whether
|
|
3744
|
+
* the text the runs print leaves its element unused. A text that does,
|
|
3745
|
+
* nulls and all -- a nullable field's way of saying "none" -- is no text
|
|
3746
|
+
* rather than one cut short, and a final render takes it as a preview
|
|
3747
|
+
* does; one whose other runs print something is still refused.
|
|
3748
|
+
*/
|
|
3749
|
+
function joinedText(render, scope, runs, path, encoder, unused) {
|
|
3750
|
+
const { text, nulls, refused } = readRuns(render, scope, runs, path, encoder);
|
|
3751
|
+
if (!render.preview && nulls.length > 0 && unused?.(text) !== true) {
|
|
3752
|
+
for (const at of nulls) render.problems.error({
|
|
3753
|
+
stage: "resolve",
|
|
3754
|
+
code: "no-qr-value",
|
|
3755
|
+
path: at,
|
|
3756
|
+
message: `${encoder.said}: this run has no value, and ${encoder.code} without it would scan as ${SCANNED_AS[encoder.code]}`,
|
|
3757
|
+
...placed(encoder)
|
|
3758
|
+
});
|
|
3759
|
+
return;
|
|
3760
|
+
}
|
|
3761
|
+
return refused ? void 0 : {
|
|
3762
|
+
text,
|
|
3763
|
+
lacking: render.preview && nulls.length > 0
|
|
3764
|
+
};
|
|
3765
|
+
}
|
|
3766
|
+
/**
|
|
3767
|
+
* The text the QR code `id` encodes: its `content`, at `path`, joined as
|
|
3768
|
+
* `joinedText` joins it. Undefined when it is refused, which is recorded,
|
|
3769
|
+
* naming the code. A final render refuses content that prints nothing at
|
|
3770
|
+
* all, a code of nothing, which scans as no code; a preview encodes it.
|
|
3771
|
+
*/
|
|
3772
|
+
function encodedText(render, scope, content, path, id) {
|
|
3773
|
+
const joined = joinedText(render, scope, content, `${path}/content`, {
|
|
3774
|
+
said: `component ${id}`,
|
|
3775
|
+
componentId: id,
|
|
3776
|
+
code: "a QR code"
|
|
3777
|
+
});
|
|
3778
|
+
if (joined === void 0) return void 0;
|
|
3779
|
+
if (joined.text !== "" || render.preview) return joined.text;
|
|
3780
|
+
render.problems.error({
|
|
3781
|
+
stage: "resolve",
|
|
3782
|
+
code: "empty-qr-code",
|
|
3783
|
+
path: `${path}/content`,
|
|
3784
|
+
message: `component ${id}: its content prints nothing, and a QR code of nothing scans as no code`,
|
|
3785
|
+
componentId: id
|
|
3786
|
+
});
|
|
3787
|
+
}
|
|
3788
|
+
/** The text of runs that hold no page counter: what a table cell or a group header prints. */
|
|
3789
|
+
function textOfRuns(runs) {
|
|
3790
|
+
return runs.map((run) => "text" in run ? run.text : "").join("");
|
|
3791
|
+
}
|
|
3792
|
+
// src/e-invoice-lines.ts
|
|
3793
|
+
/**
|
|
3794
|
+
* An e-invoice's lines (BG-25): one for each row of the table that prints
|
|
3795
|
+
* them, read once, before the totals, for the page and the XML alike
|
|
3796
|
+
* (0027).
|
|
3797
|
+
*
|
|
3798
|
+
* - **One evaluation.** The four columns the e-invoice names -- the item
|
|
3799
|
+
* name (BT-153), the invoiced quantity (BT-129), the net price (BT-146)
|
|
3800
|
+
* and the net amount (BT-131) -- are read here for every row, as the
|
|
3801
|
+
* table reads a cell, and kept by the path of each column's value and the
|
|
3802
|
+
* row's index: the table prints the very value kept (`inlines.ts`). So
|
|
3803
|
+
* the page and the XML cannot each read a line, and part. The line's
|
|
3804
|
+
* identifier (BT-126), its unit (BT-130) and its VAT category (BT-151)
|
|
3805
|
+
* are codes a page need not print, read from each row as an aggregate
|
|
3806
|
+
* reads it.
|
|
3807
|
+
* - **In the table's order** (`orderTable`, 0007), which the XML holds
|
|
3808
|
+
* them in.
|
|
3809
|
+
* - **Held to EN 16931's rules**, report-spec's functions over text, the
|
|
3810
|
+
* ones its validator applies to a literal (`en16931.ts`): a code from a
|
|
3811
|
+
* closed list, a net price that is not negative, a net amount that is a
|
|
3812
|
+
* whole number of cents, never rounded, a category the invoice declares.
|
|
3813
|
+
* And to what EN 16931 defines and no rule of CEN's tests: a net amount
|
|
3814
|
+
* that is the quantity times the net price, rounded once to the cent
|
|
3815
|
+
* (`lineNetAmount`), and a line identifier no other line has. A rule
|
|
3816
|
+
* broken is `invalid-e-invoice`, naming the row and the column or the
|
|
3817
|
+
* code, the term and the rule, never the value.
|
|
3818
|
+
* - **Printed as the XML holds it.** A quantity or a net price whose
|
|
3819
|
+
* column's format shows fewer places than it has is refused: the page
|
|
3820
|
+
* would round it, and the XML would not.
|
|
3821
|
+
* - **A preview holds what it has.** A final render refuses a term that
|
|
3822
|
+
* has no value (BR-21 to BR-26, BR-CO-04) and a table of no rows
|
|
3823
|
+
* (BR-16). A preview takes a term with no value as one it lacks, and
|
|
3824
|
+
* leaves a line whose net amount or category it lacks out of every
|
|
3825
|
+
* total, as an aggregate skips a null; what the data does hold it holds
|
|
3826
|
+
* to the same rules.
|
|
3827
|
+
*/
|
|
3828
|
+
/** The key of each term of `LineTerms` the e-invoice names a column or a code by. */
|
|
3829
|
+
const TERM_OF = {
|
|
3830
|
+
name: "name",
|
|
3831
|
+
quantity: "quantity",
|
|
3832
|
+
netPrice: "netPrice",
|
|
3833
|
+
netAmount: "netAmount",
|
|
3834
|
+
id: "id",
|
|
3835
|
+
unit: "unit",
|
|
3836
|
+
vat: "category"
|
|
3837
|
+
};
|
|
3838
|
+
function refuse$3(render, place, message) {
|
|
3839
|
+
render.problems.error({
|
|
3840
|
+
stage: "resolve",
|
|
3841
|
+
code: "invalid-e-invoice",
|
|
3842
|
+
path: place.path,
|
|
3843
|
+
message: `${place.said}, detail row ${place.row}: ${message}`,
|
|
3844
|
+
...placed(place)
|
|
3845
|
+
});
|
|
3846
|
+
}
|
|
3847
|
+
/** The rule a term with no value breaks: every line term is needed. */
|
|
3848
|
+
function required(term) {
|
|
3849
|
+
const rule = term.term in E_INVOICE_DECIMALS ? E_INVOICE_DECIMALS[term.term].required : E_INVOICE_TEXTS[term.term].required;
|
|
3850
|
+
return en16931Rule(rule, "has no value, and every line of an e-invoice has one");
|
|
3851
|
+
}
|
|
3852
|
+
/** A value as its term's text: a decimal and an integer by their own digits, a text as it is. */
|
|
3853
|
+
function written(value) {
|
|
3854
|
+
return value.type === "decimal" ? decimalToString(value.value) : String(value.value);
|
|
3855
|
+
}
|
|
3856
|
+
/**
|
|
3857
|
+
* The term `term` of a line, read as `value`, held to its rule: what the
|
|
3858
|
+
* XML writes, null where a preview has no value for it, or undefined when
|
|
3859
|
+
* it is refused, which is recorded at `place`.
|
|
3860
|
+
*/
|
|
3861
|
+
function checked$2(render, term, value, place) {
|
|
3862
|
+
if (value === null || render.preview && value.type === "string" && eInvoiceBlank(value.value)) return render.preview ? null : refuse$3(render, place, `${term.what} ${required(term)}`);
|
|
3863
|
+
if (!term.types.includes(value.type)) return refuse$3(render, place, `${term.what} is read from ${term.types.map(aType).join(" or ")}, and this gives ${aType(value.type)}`);
|
|
3864
|
+
const text = written(value);
|
|
3865
|
+
const outcome = term.term in E_INVOICE_DECIMALS ? checkEInvoiceDecimal(term.term, text) : checkEInvoiceText(term.term, text);
|
|
3866
|
+
return outcome.ok ? outcome.value : refuse$3(render, place, `${term.what} ${outcome.rule}`);
|
|
3867
|
+
}
|
|
3868
|
+
/** The table the lines are the rows of, and the columns that print their terms. */
|
|
3869
|
+
function namedColumns(render, invoice) {
|
|
3870
|
+
const located = walkComponents(render.report).find(({ component }) => component.kind === "table" && component.id === invoice.lines.table);
|
|
3871
|
+
const table = located.component;
|
|
3872
|
+
return {
|
|
3873
|
+
table,
|
|
3874
|
+
columns: Object.keys(E_INVOICE_LINE_COLUMNS).map((key) => {
|
|
3875
|
+
const index = table.columns.findIndex((column) => column.id === invoice.lines[key]);
|
|
3876
|
+
const column = table.columns[index];
|
|
3877
|
+
return {
|
|
3878
|
+
key,
|
|
3879
|
+
id: column.id,
|
|
3880
|
+
value: column.value,
|
|
3881
|
+
path: `${located.path}/columns/${index}/value`,
|
|
3882
|
+
printed: new Array(render.data.detail.length).fill(null)
|
|
3883
|
+
};
|
|
3884
|
+
})
|
|
3885
|
+
};
|
|
3886
|
+
}
|
|
3887
|
+
/**
|
|
3888
|
+
* The columns whose term the XML writes with the data's own places, which
|
|
3889
|
+
* their format may not round: the quantity and the net price. The net
|
|
3890
|
+
* amount and every total are amounts the XML writes at two places, which
|
|
3891
|
+
* the editing core holds a format to where the template is written.
|
|
3892
|
+
*/
|
|
3893
|
+
const AS_WRITTEN = /* @__PURE__ */ new Set(["quantity", "netPrice"]);
|
|
3894
|
+
/** The places `column` prints `value` at, where printing it there would round it, by value; undefined where it prints it as it is. */
|
|
3895
|
+
function roundingPlaces(column, value) {
|
|
3896
|
+
const format = column.value.format;
|
|
3897
|
+
if (!AS_WRITTEN.has(column.key) || value.type !== "decimal" || format?.kind !== "number" && format?.kind !== "currency") return void 0;
|
|
3898
|
+
const shown = roundDecimalAs(value.value, {
|
|
3899
|
+
scale: format.scale,
|
|
3900
|
+
mode: "half-away-from-zero"
|
|
3901
|
+
});
|
|
3902
|
+
return compareDecimal(shown, value.value) === 0 ? void 0 : format.scale;
|
|
3903
|
+
}
|
|
3904
|
+
/** The term of `column` in `row`, read and held to its rule, and to the places its column prints; `undefined` when it could not be, which is recorded. */
|
|
3905
|
+
function readColumn(render, scope, column, place) {
|
|
3906
|
+
const value = inlineValue(render, scope, column.value, column.path);
|
|
3907
|
+
if (value === void 0) return void 0;
|
|
3908
|
+
column.printed[place.row] = value;
|
|
3909
|
+
const term = E_INVOICE_LINE_COLUMNS[column.key];
|
|
3910
|
+
const text = checked$2(render, term, value, place);
|
|
3911
|
+
const places = typeof text === "string" ? roundingPlaces(column, value) : void 0;
|
|
3912
|
+
if (places === void 0) return text;
|
|
3913
|
+
return refuse$3(render, place, `${term.what} has more places than its column prints, ${places}, so the page would print another than the XML holds: the column prints the places the data gives`);
|
|
3914
|
+
}
|
|
3915
|
+
/** The line of `row`, every term read and held to its rule; undefined when a term is refused or could not be read, which is recorded. */
|
|
3916
|
+
function readLine(render, invoice, table, columns, row) {
|
|
3917
|
+
const scope = rowScope(render, render.totals.report, row);
|
|
3918
|
+
const terms = {};
|
|
3919
|
+
let whole = true;
|
|
3920
|
+
const keep = (key, value) => {
|
|
3921
|
+
if (value === void 0) whole = false;
|
|
3922
|
+
else terms[TERM_OF[key]] = value;
|
|
3923
|
+
};
|
|
3924
|
+
const placeOf = (column) => ({
|
|
3925
|
+
path: column.path,
|
|
3926
|
+
said: `component ${table.id}, column ${column.id}`,
|
|
3927
|
+
componentId: table.id,
|
|
3928
|
+
columnId: column.id,
|
|
3929
|
+
row: row.index
|
|
3930
|
+
});
|
|
3931
|
+
for (const column of columns) {
|
|
3932
|
+
const text = readColumn(render, scope, column, placeOf(column));
|
|
3933
|
+
keep(column.key, column.key === "netAmount" && typeof text === "string" ? decimalFromString(text) : text);
|
|
3934
|
+
}
|
|
3935
|
+
const { quantity, netPrice, netAmount } = terms;
|
|
3936
|
+
if (typeof quantity === "string" && typeof netPrice === "string" && netAmount !== void 0 && netAmount !== null && compareDecimal(lineNetAmount(quantity, netPrice), netAmount) !== 0) keep("netAmount", refuse$3(render, placeOf(columns.find(({ key }) => key === "netAmount")), `${E_INVOICE_LINE_COLUMNS.netAmount.what} is not ${E_INVOICE_LINE_COLUMNS.quantity.what} times ${E_INVOICE_LINE_COLUMNS.netPrice.what}, rounded once to the cent: a receiver that multiplies them reads another amount`));
|
|
3937
|
+
for (const key of Object.keys(E_INVOICE_LINE_CODES)) {
|
|
3938
|
+
const code = invoice.lines[key];
|
|
3939
|
+
const path = `/eInvoice/lines/${key}`;
|
|
3940
|
+
const value = code.kind === "field" ? fieldValue(render, row.record, code.field) : valueOf(render, scope, `${path}/expression/cel`);
|
|
3941
|
+
if (value === void 0) {
|
|
3942
|
+
whole = false;
|
|
3943
|
+
continue;
|
|
3944
|
+
}
|
|
3945
|
+
const place = {
|
|
3946
|
+
path,
|
|
3947
|
+
said: "the e-invoice",
|
|
3948
|
+
row: row.index
|
|
3949
|
+
};
|
|
3950
|
+
const text = checked$2(render, E_INVOICE_LINE_CODES[key], value, place);
|
|
3951
|
+
if (key !== "vat" || typeof text !== "string") keep(key, text);
|
|
3952
|
+
else {
|
|
3953
|
+
const category = checkLineCategory(text, invoice.vat);
|
|
3954
|
+
keep(key, category.ok ? category.value : refuse$3(render, place, `${E_INVOICE_LINE_CODES.vat.what} ${category.rule}`));
|
|
3955
|
+
}
|
|
3956
|
+
}
|
|
3957
|
+
return whole ? {
|
|
3958
|
+
...terms,
|
|
3959
|
+
row: row.index
|
|
3960
|
+
} : void 0;
|
|
3961
|
+
}
|
|
3962
|
+
/**
|
|
3963
|
+
* `invoice`'s lines in the table's order, each term read once and held to
|
|
3964
|
+
* its rule, and what the named columns printed of each row; undefined when
|
|
3965
|
+
* a line is refused, or could not be read, which is recorded. A final
|
|
3966
|
+
* render refuses a table of no rows (BR-16).
|
|
3967
|
+
*/
|
|
3968
|
+
function readLines(render, invoice) {
|
|
3969
|
+
const { table, columns } = namedColumns(render, invoice);
|
|
3970
|
+
const lines = [];
|
|
3971
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3972
|
+
let whole = true;
|
|
3973
|
+
for (const row of orderTable(render.report, table, render.data.detail).rows) {
|
|
3974
|
+
if (render.problems.full) return void 0;
|
|
3975
|
+
const line = readLine(render, invoice, table, columns, row);
|
|
3976
|
+
if (line === void 0) whole = false;
|
|
3977
|
+
else if (line.id !== null && ids.has(line.id)) {
|
|
3978
|
+
refuse$3(render, {
|
|
3979
|
+
path: "/eInvoice/lines/id",
|
|
3980
|
+
said: "the e-invoice",
|
|
3981
|
+
row: row.index
|
|
3982
|
+
}, `${E_INVOICE_LINE_CODES.id.what} is an earlier line's, and each line of an e-invoice has its own`);
|
|
3983
|
+
whole = false;
|
|
3984
|
+
} else {
|
|
3985
|
+
if (line.id !== null) ids.add(line.id);
|
|
3986
|
+
lines.push(line);
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
if (!render.preview && render.data.detail.length === 0) {
|
|
3990
|
+
render.problems.error({
|
|
3991
|
+
stage: "resolve",
|
|
3992
|
+
code: "invalid-e-invoice",
|
|
3993
|
+
path: "/eInvoice/lines/table",
|
|
3994
|
+
message: `the e-invoice: ${en16931Rule("BR-16", `an e-invoice has one line at least, a row of the table ${table.id}, and the data has no rows`)}`,
|
|
3995
|
+
componentId: table.id
|
|
3996
|
+
});
|
|
3997
|
+
return;
|
|
3998
|
+
}
|
|
3999
|
+
return whole ? {
|
|
4000
|
+
lines,
|
|
4001
|
+
columns: new Map(columns.map(({ path, printed }) => [path, printed]))
|
|
4002
|
+
} : void 0;
|
|
4003
|
+
}
|
|
4004
|
+
/** The lines a final render writes: every term of each read, which a final render refuses a line without. */
|
|
4005
|
+
function writtenLines(lines) {
|
|
4006
|
+
return lines.every((line) => Object.values(line).every((term) => term !== null)) ? lines : void 0;
|
|
4007
|
+
}
|
|
4008
|
+
// src/e-invoice-terms.ts
|
|
4009
|
+
/**
|
|
4010
|
+
* An e-invoice's terms but its lines -- its number, its dates, its seller
|
|
4011
|
+
* and its buyer, its categories' reasons, its payment instructions, its
|
|
4012
|
+
* paid amount -- each read in the report's scope once the data has
|
|
4013
|
+
* resolved it, and held to EN 16931's rules: report-spec's `en16931.ts`,
|
|
4014
|
+
* the very functions its validator applies to a literal, named by the same
|
|
4015
|
+
* tables.
|
|
4016
|
+
*
|
|
4017
|
+
* - **Read as a paragraph.** Each text is its runs, read as a paragraph's
|
|
4018
|
+
* in the report's scope (`readRuns`), so the XML holds what the same runs
|
|
4019
|
+
* would print. A literal passes again; a value from data is held where
|
|
4020
|
+
* the validator could not see it.
|
|
4021
|
+
* - **What may be left out is.** An optional text the data resolves to
|
|
4022
|
+
* blank, nulls and all, is a term the XML leaves out, as an EPC QR code's
|
|
4023
|
+
* optional texts are: a nullable field's null is how data says "none".
|
|
4024
|
+
* A needed one that prints nothing breaks its rule (BR-02, BR-06 ...);
|
|
4025
|
+
* one whose runs print something around a null is refused as a text cut
|
|
4026
|
+
* short. The seller's contact is left out whole or written whole: one
|
|
4027
|
+
* the data gives in part is refused at each term it lacks (0037).
|
|
4028
|
+
* - **Each kind's rules.** An XRechnung's texts are held to its kind's
|
|
4029
|
+
* (`E_INVOICE_KIND_TEXTS`, 0038): what XRechnung needs is needed, a
|
|
4030
|
+
* contact's three terms among them, and its payment terms hold no line
|
|
4031
|
+
* led by #. An electronic address under 0204 is a Leitweg-ID in either
|
|
4032
|
+
* kind.
|
|
4033
|
+
* - **What only the whole says** -- the identifiers the lines' categories
|
|
4034
|
+
* need of the seller and the buyer (BR-CO-26, BR-S-02, BR-E-02,
|
|
4035
|
+
* BR-AE-02), the time of supply (§ 14 UStG), a category's reason (BR-E-10,
|
|
4036
|
+
* BR-AE-10) -- is said of the categories the lines are in, once every
|
|
4037
|
+
* part has resolved; an invoicing period's order (BR-29) once both its
|
|
4038
|
+
* dates have.
|
|
4039
|
+
* - **A preview holds what it has**: a term it has no value for is one it
|
|
4040
|
+
* lacks, and what only an absence breaks it does not say. What the data
|
|
4041
|
+
* holds it holds to the same rules.
|
|
4042
|
+
*
|
|
4043
|
+
* A rule broken is `invalid-e-invoice` at the term, naming its business
|
|
4044
|
+
* term and the rule, never the value, which may be a person's name,
|
|
4045
|
+
* account or VAT identifier.
|
|
4046
|
+
*/
|
|
4047
|
+
/** What an error names the e-invoice by: it stands in no component. */
|
|
4048
|
+
const OWNER = { said: "the e-invoice" };
|
|
4049
|
+
function refuse$2({ render }, path, message) {
|
|
4050
|
+
render.problems.error({
|
|
4051
|
+
stage: "resolve",
|
|
4052
|
+
code: "invalid-e-invoice",
|
|
4053
|
+
path,
|
|
4054
|
+
message: `the e-invoice: ${message}`
|
|
4055
|
+
});
|
|
4056
|
+
}
|
|
4057
|
+
/** The text of `term`, its runs at `path`, held to its rule of the reader's kind, or to `check` where it is given. */
|
|
4058
|
+
function text(reader, term, runs, path, check = (written) => checkEInvoiceText(term, written, reader.kind)) {
|
|
4059
|
+
if (runs === void 0) return null;
|
|
4060
|
+
const read = readRuns(reader.render, reader.scope, runs, path, OWNER);
|
|
4061
|
+
if (read.refused) return void 0;
|
|
4062
|
+
const rule = E_INVOICE_KIND_TEXTS[reader.kind][term];
|
|
4063
|
+
const blank = eInvoiceBlank(read.text);
|
|
4064
|
+
if (reader.render.preview && (blank || read.nulls.length > 0)) return null;
|
|
4065
|
+
if (blank && rule.required === void 0) return null;
|
|
4066
|
+
if (!blank && read.nulls.length > 0) return refuse$2(reader, path, `${rule.what} has a run with no value, and written without it the e-invoice would hold less than its runs print`);
|
|
4067
|
+
const checked = check(read.text);
|
|
4068
|
+
return checked.ok ? checked.value : refuse$2(reader, path, `${rule.what} ${checked.rule}`);
|
|
4069
|
+
}
|
|
4070
|
+
/** The date of `term`, its expression at `path`: a day on the calendar, YYYY-MM-DD. */
|
|
4071
|
+
function date(reader, term, expression, path) {
|
|
4072
|
+
if (expression === void 0) return null;
|
|
4073
|
+
const value = valueOf(reader.render, reader.scope, `${path}/cel`);
|
|
4074
|
+
if (value === void 0) return void 0;
|
|
4075
|
+
const rule = E_INVOICE_DATES[term];
|
|
4076
|
+
if (value === null) return rule.required === void 0 || reader.render.preview ? null : refuse$2(reader, path, `${rule.what} ${en16931Rule(rule.required, "has no value, and an e-invoice needs it")}`);
|
|
4077
|
+
if (value.type !== "date" && value.type !== "string") return refuse$2(reader, path, `${rule.what} is a date, and this gives ${aType(value.type)}`);
|
|
4078
|
+
const checked = checkEInvoiceDate(value.value);
|
|
4079
|
+
return checked.ok ? checked.value : refuse$2(reader, path, `${rule.what} ${checked.rule}`);
|
|
4080
|
+
}
|
|
4081
|
+
/** `value` under `key` where it is a value; nothing where it is none or was refused. */
|
|
4082
|
+
const term = (key, value) => value === null || value === void 0 ? {} : { [key]: value };
|
|
4083
|
+
/** Whether every one of `values` was read and is there: what a term needs of each of its parts. */
|
|
4084
|
+
const all = (...values) => values.every((value) => value !== null && value !== void 0);
|
|
4085
|
+
function address$1(reader, held, path, which) {
|
|
4086
|
+
const terms = E_INVOICE_TEXT_TERMS[which].address;
|
|
4087
|
+
const line1 = text(reader, terms.line1, held.line1, `${path}/line1`);
|
|
4088
|
+
const line2 = text(reader, terms.line2, held.line2, `${path}/line2`);
|
|
4089
|
+
const postalCode = text(reader, terms.postalCode, held.postalCode, `${path}/postalCode`);
|
|
4090
|
+
const city = text(reader, terms.city, held.city, `${path}/city`);
|
|
4091
|
+
const country = text(reader, terms.country, held.country, `${path}/country`);
|
|
4092
|
+
if (line2 === void 0 || !all(line1, postalCode, city, country)) return void 0;
|
|
4093
|
+
return {
|
|
4094
|
+
line1,
|
|
4095
|
+
...term("line2", line2),
|
|
4096
|
+
postalCode,
|
|
4097
|
+
city,
|
|
4098
|
+
country
|
|
4099
|
+
};
|
|
4100
|
+
}
|
|
4101
|
+
/** An electronic address: its identifier read, held to its scheme where that is 0204, with the scheme the template names; none where the data gives the identifier as nothing. */
|
|
4102
|
+
function electronicAddress(reader, held, path, term) {
|
|
4103
|
+
if (held === void 0) return null;
|
|
4104
|
+
const id = text(reader, term, held.id, `${path}/id`, (written) => checkElectronicAddress(term, held.scheme, written, reader.kind));
|
|
4105
|
+
return id === null || id === void 0 ? id : {
|
|
4106
|
+
id,
|
|
4107
|
+
scheme: held.scheme
|
|
4108
|
+
};
|
|
4109
|
+
}
|
|
4110
|
+
/**
|
|
4111
|
+
* The seller's contact: all three of its terms, or none where the data
|
|
4112
|
+
* gives none of them. One it gives in part is refused at each term it
|
|
4113
|
+
* lacks, as the validator refuses a literal one: a contact gives all three
|
|
4114
|
+
* or none (0037). A preview lacks what it has no value for, and says
|
|
4115
|
+
* nothing of it.
|
|
4116
|
+
*/
|
|
4117
|
+
function contact(reader, held, path) {
|
|
4118
|
+
if (held === void 0) return null;
|
|
4119
|
+
const terms = E_INVOICE_TEXT_TERMS.seller.contact;
|
|
4120
|
+
const read = {
|
|
4121
|
+
name: text(reader, terms.name, held.name, `${path}/name`),
|
|
4122
|
+
telephone: text(reader, terms.telephone, held.telephone, `${path}/telephone`),
|
|
4123
|
+
email: text(reader, terms.email, held.email, `${path}/email`)
|
|
4124
|
+
};
|
|
4125
|
+
const { name, telephone, email } = read;
|
|
4126
|
+
if (name === void 0 || telephone === void 0 || email === void 0) return void 0;
|
|
4127
|
+
if (name !== null && telephone !== null && email !== null) return {
|
|
4128
|
+
name,
|
|
4129
|
+
telephone,
|
|
4130
|
+
email
|
|
4131
|
+
};
|
|
4132
|
+
if (name === null && telephone === null && email === null || reader.render.preview) return null;
|
|
4133
|
+
for (const key of [
|
|
4134
|
+
"name",
|
|
4135
|
+
"telephone",
|
|
4136
|
+
"email"
|
|
4137
|
+
]) if (read[key] === null) refuse$2(reader, `${path}/${key}`, `${E_INVOICE_KIND_TEXTS[reader.kind][terms[key]].what} is empty, and a contact gives all three of its terms or none`);
|
|
4138
|
+
}
|
|
4139
|
+
function party$1(reader, held, path, which) {
|
|
4140
|
+
const terms = E_INVOICE_TEXT_TERMS[which];
|
|
4141
|
+
const name = text(reader, terms.name, held.name, `${path}/name`);
|
|
4142
|
+
const vatId = text(reader, terms.vatId, held.vatId, `${path}/vatId`);
|
|
4143
|
+
const taxNumber = which === "seller" ? text(reader, E_INVOICE_TEXT_TERMS.seller.taxNumber, held.taxNumber, `${path}/taxNumber`) : null;
|
|
4144
|
+
const legalId = text(reader, terms.legalId, held.legalId?.id, `${path}/legalId/id`);
|
|
4145
|
+
const reached = electronicAddress(reader, held.electronicAddress, `${path}/electronicAddress`, terms.electronicAddress);
|
|
4146
|
+
const contacted = which === "seller" ? contact(reader, held.contact, `${path}/contact`) : null;
|
|
4147
|
+
const where = address$1(reader, held.address, `${path}/address`, which);
|
|
4148
|
+
const has = {
|
|
4149
|
+
vatId: vatId !== null,
|
|
4150
|
+
taxNumber: taxNumber !== null,
|
|
4151
|
+
legalId: legalId !== null
|
|
4152
|
+
};
|
|
4153
|
+
if (vatId === void 0 || taxNumber === void 0 || legalId === void 0 || reached === void 0 || contacted === void 0 || !all(name, where)) return {
|
|
4154
|
+
party: void 0,
|
|
4155
|
+
has
|
|
4156
|
+
};
|
|
4157
|
+
const scheme = held.legalId?.scheme;
|
|
4158
|
+
const registration = legalId === null ? {} : { legalId: {
|
|
4159
|
+
id: legalId,
|
|
4160
|
+
...scheme === void 0 ? {} : { scheme }
|
|
4161
|
+
} };
|
|
4162
|
+
return {
|
|
4163
|
+
party: {
|
|
4164
|
+
name,
|
|
4165
|
+
...term("vatId", vatId),
|
|
4166
|
+
...term("taxNumber", taxNumber),
|
|
4167
|
+
...registration,
|
|
4168
|
+
...term("electronicAddress", reached),
|
|
4169
|
+
...term("contact", contacted),
|
|
4170
|
+
address: where
|
|
4171
|
+
},
|
|
4172
|
+
has
|
|
4173
|
+
};
|
|
4174
|
+
}
|
|
4175
|
+
function payment(reader, invoice) {
|
|
4176
|
+
const held = invoice.payment;
|
|
4177
|
+
if (held === void 0) return {
|
|
4178
|
+
payment: null,
|
|
4179
|
+
account: void 0
|
|
4180
|
+
};
|
|
4181
|
+
const terms = E_INVOICE_TEXT_TERMS.payment;
|
|
4182
|
+
const account = text(reader, terms.iban, held.iban, "/eInvoice/payment/iban");
|
|
4183
|
+
const bic = text(reader, terms.bic, held.bic, "/eInvoice/payment/bic");
|
|
4184
|
+
const accountName = text(reader, terms.accountName, held.accountName, "/eInvoice/payment/accountName");
|
|
4185
|
+
const remittance = text(reader, terms.remittance, held.remittance, "/eInvoice/payment/remittance");
|
|
4186
|
+
const known = account ?? void 0;
|
|
4187
|
+
if (bic === void 0 || accountName === void 0 || remittance === void 0 || !all(account)) return {
|
|
4188
|
+
payment: void 0,
|
|
4189
|
+
account: known
|
|
4190
|
+
};
|
|
4191
|
+
return {
|
|
4192
|
+
payment: {
|
|
4193
|
+
means: held.means,
|
|
4194
|
+
account,
|
|
4195
|
+
...term("bic", bic),
|
|
4196
|
+
...term("accountName", accountName),
|
|
4197
|
+
...term("remittance", remittance)
|
|
4198
|
+
},
|
|
4199
|
+
account: known
|
|
4200
|
+
};
|
|
4201
|
+
}
|
|
4202
|
+
/** The paid amount (BT-113), read in the report's scope: a whole number of cents, at two places, or null where none is paid. */
|
|
4203
|
+
function paidAmount(render, invoice) {
|
|
4204
|
+
if (invoice.paid === void 0) return null;
|
|
4205
|
+
const path = "/eInvoice/paid";
|
|
4206
|
+
const value = valueOf(render, reportScope(render, render.totals.report), `${path}/cel`);
|
|
4207
|
+
if (value === void 0 || value === null) return value;
|
|
4208
|
+
const what = E_INVOICE_DECIMALS["BT-113"].what;
|
|
4209
|
+
if (value.type !== "decimal") return refuse$2({ render }, path, `${what} is a decimal, and this gives ${aType(value.type)}`);
|
|
4210
|
+
const checked = checkEInvoiceDecimal("BT-113", decimalToString(value.value));
|
|
4211
|
+
return checked.ok ? decimalFromString(checked.value) : refuse$2({ render }, path, `${what} ${checked.rule}`);
|
|
4212
|
+
}
|
|
4213
|
+
/**
|
|
4214
|
+
* Every term of `invoice` but its lines and its totals, each read in the
|
|
4215
|
+
* report's scope and held to its rule, and what the whole breaks said of
|
|
4216
|
+
* `used`, the categories the lines are in. `terms` is undefined where a
|
|
4217
|
+
* term was refused, which is recorded, or a preview lacks one.
|
|
4218
|
+
*/
|
|
4219
|
+
function readTerms(render, invoice, used) {
|
|
4220
|
+
const reader = {
|
|
4221
|
+
render,
|
|
4222
|
+
scope: reportScope(render, render.totals.report),
|
|
4223
|
+
kind: invoice.kind
|
|
4224
|
+
};
|
|
4225
|
+
const number = text(reader, E_INVOICE_TEXT_TERMS.number, invoice.number, "/eInvoice/number");
|
|
4226
|
+
const issued = date(reader, "BT-2", invoice.issued, "/eInvoice/issued");
|
|
4227
|
+
const businessProcess = text(reader, E_INVOICE_TEXT_TERMS.businessProcess, invoice.businessProcess, "/eInvoice/businessProcess");
|
|
4228
|
+
const seller = party$1(reader, invoice.seller, "/eInvoice/seller", "seller");
|
|
4229
|
+
const buyer = party$1(reader, invoice.buyer, "/eInvoice/buyer", "buyer");
|
|
4230
|
+
const buyerReference = text(reader, E_INVOICE_TEXT_TERMS.buyerReference, invoice.buyerReference, "/eInvoice/buyerReference");
|
|
4231
|
+
const delivered = date(reader, "BT-72", invoice.delivered, "/eInvoice/delivered");
|
|
4232
|
+
const start = date(reader, "BT-73", invoice.period?.start, "/eInvoice/period/start");
|
|
4233
|
+
const end = date(reader, "BT-74", invoice.period?.end, "/eInvoice/period/end");
|
|
4234
|
+
const reasons = used.map((category) => [category, text(reader, E_INVOICE_TEXT_TERMS.reason, category.reason, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`)]);
|
|
4235
|
+
const paying = payment(reader, invoice);
|
|
4236
|
+
const due = date(reader, "BT-9", invoice.due, "/eInvoice/due");
|
|
4237
|
+
const terms = text(reader, E_INVOICE_TEXT_TERMS.terms, invoice.terms, "/eInvoice/terms");
|
|
4238
|
+
const ordered = typeof start === "string" && typeof end === "string" ? checkInvoicingPeriod(start, end) : void 0;
|
|
4239
|
+
if (ordered !== void 0) refuse$2(reader, "/eInvoice/period", ordered);
|
|
4240
|
+
if (!render.preview) {
|
|
4241
|
+
const codes = used.map(({ code }) => code);
|
|
4242
|
+
for (const rule of sellerIdentificationBreaks(seller.has, codes)) refuse$2(reader, "/eInvoice/seller", rule);
|
|
4243
|
+
const unidentified = buyerIdentificationBreak(buyer.has, codes);
|
|
4244
|
+
if (unidentified !== void 0) refuse$2(reader, "/eInvoice/buyer", unidentified);
|
|
4245
|
+
const unsupplied = supplyBreak(delivered !== null, start !== null || end !== null);
|
|
4246
|
+
if (unsupplied !== void 0) refuse$2(reader, "/eInvoice/delivered", unsupplied);
|
|
4247
|
+
for (const [category, reason] of reasons) {
|
|
4248
|
+
const unreasoned = vatReasonBreak(category.code, reason !== null);
|
|
4249
|
+
if (unreasoned !== void 0) refuse$2(reader, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`, unreasoned);
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
const read = [
|
|
4253
|
+
number,
|
|
4254
|
+
issued,
|
|
4255
|
+
businessProcess,
|
|
4256
|
+
seller.party,
|
|
4257
|
+
buyer.party,
|
|
4258
|
+
buyerReference,
|
|
4259
|
+
delivered,
|
|
4260
|
+
start,
|
|
4261
|
+
end,
|
|
4262
|
+
paying.payment,
|
|
4263
|
+
due,
|
|
4264
|
+
terms,
|
|
4265
|
+
...reasons.map(([, reason]) => reason)
|
|
4266
|
+
];
|
|
4267
|
+
if (render.problems.failed || read.includes(void 0) || !all(number, issued, seller.party, buyer.party)) return {
|
|
4268
|
+
terms: void 0,
|
|
4269
|
+
account: paying.account
|
|
4270
|
+
};
|
|
4271
|
+
return {
|
|
4272
|
+
terms: {
|
|
4273
|
+
number,
|
|
4274
|
+
issued,
|
|
4275
|
+
...term("businessProcess", businessProcess),
|
|
4276
|
+
seller: seller.party,
|
|
4277
|
+
buyer: buyer.party,
|
|
4278
|
+
...term("buyerReference", buyerReference),
|
|
4279
|
+
...term("delivered", delivered),
|
|
4280
|
+
...start === null && end === null ? {} : { period: {
|
|
4281
|
+
...term("start", start),
|
|
4282
|
+
...term("end", end)
|
|
4283
|
+
} },
|
|
4284
|
+
reasons: new Map(reasons.flatMap(([category, reason]) => typeof reason === "string" ? [[category.id, reason]] : [])),
|
|
4285
|
+
...term("payment", paying.payment),
|
|
4286
|
+
...term("due", due),
|
|
4287
|
+
...term("terms", terms)
|
|
4288
|
+
},
|
|
4289
|
+
account: paying.account
|
|
4290
|
+
};
|
|
4291
|
+
}
|
|
4292
|
+
// src/lower-e-invoice.ts
|
|
4293
|
+
/**
|
|
4294
|
+
* A report's e-invoice resolved (0027): its lines and its totals before
|
|
4295
|
+
* anything is lowered, since the page prints them; and after the page is
|
|
4296
|
+
* lowered, in a final render, the XML the PDF embeds.
|
|
4297
|
+
*
|
|
4298
|
+
* 1. **The lines**, read once from the rows of the table that prints them
|
|
4299
|
+
* (`e-invoice-lines.ts`), each column's value kept for the table to
|
|
4300
|
+
* print.
|
|
4301
|
+
* 2. **The paid amount and the totals**, computed once from the lines
|
|
4302
|
+
* (`e-invoice-totals.ts`) and bound as `invoice`, `vatBasis` and
|
|
4303
|
+
* `vatAmount` for every scope that reads them.
|
|
4304
|
+
* 3. **The other terms**, read in the report's scope and held to EN
|
|
4305
|
+
* 16931's rules (`e-invoice-terms.ts`); a payment code is held to the
|
|
4306
|
+
* amount due and the account they give (`e-invoice-payable.ts`).
|
|
4307
|
+
* 4. **The XML** (`cii.ts`), written from those very values.
|
|
4308
|
+
*
|
|
4309
|
+
* **A preview is not the invoice.** In Germany the XML a hybrid invoice
|
|
4310
|
+
* embeds is the invoice, so a preview writes none and the PDF that leaves
|
|
4311
|
+
* it is no e-invoice; it prints the totals of what it has, and warns
|
|
4312
|
+
* `e-invoice-preview` whatever data it has, so that every page carries a
|
|
4313
|
+
* preview label, complete data or not. A final render writes the XML or
|
|
4314
|
+
* refuses.
|
|
4315
|
+
*
|
|
4316
|
+
* **Both kinds are resolved alike** (0038): an XRechnung's terms are EN
|
|
4317
|
+
* 16931's, read by the same readers under its kind's rules, and written by
|
|
4318
|
+
* the same writer, its specification identifier apart. What differs is
|
|
4319
|
+
* the file the document carries: a Factur-X file a PDF/A-3b embeds, or an
|
|
4320
|
+
* XRechnung's XML a host takes and sends.
|
|
4321
|
+
*/
|
|
4322
|
+
/** BT-24 of each kind: a Factur-X profile's identifier, or an XRechnung version's. A table over every kind, so a kind added without one does not compile. */
|
|
4323
|
+
const GUIDELINES = {
|
|
4324
|
+
facturX: (invoice) => FACTUR_X_PROFILES$1[invoice.profile].guideline,
|
|
4325
|
+
xrechnung: (invoice) => XRECHNUNG$1[invoice.version].guideline
|
|
4326
|
+
};
|
|
4327
|
+
/** The guideline of `invoice`, by its kind. */
|
|
4328
|
+
const guidelineOf = (invoice) => GUIDELINES[invoice.kind](invoice);
|
|
4329
|
+
/**
|
|
4330
|
+
* `invoice`, `render`'s e-invoice, resolved before anything is lowered,
|
|
4331
|
+
* whatever its kind: its lines, its totals and its terms, each held to its
|
|
4332
|
+
* kind's rules, and in a final render whose every term resolved what its
|
|
4333
|
+
* XML is written from. Undefined when its lines or its totals could not
|
|
4334
|
+
* be, which is recorded: nothing that prints them can be lowered. A term
|
|
4335
|
+
* refused is recorded, and leaves nothing to write.
|
|
4336
|
+
*/
|
|
4337
|
+
function resolveEInvoice(render, invoice) {
|
|
4338
|
+
const read = readLines(render, invoice);
|
|
4339
|
+
const paid = paidAmount(render, invoice);
|
|
4340
|
+
if (read === void 0 || paid === void 0) return void 0;
|
|
4341
|
+
const placed = read.lines.flatMap(({ netAmount, category }) => netAmount === null || category === null ? [] : [{
|
|
4342
|
+
netAmount,
|
|
4343
|
+
category
|
|
4344
|
+
}]);
|
|
4345
|
+
const totals = invoiceTotals(invoice.vat, placed, paid);
|
|
4346
|
+
const { terms, account } = readTerms(render, invoice, totals.breakdown.map(({ category }) => category));
|
|
4347
|
+
const lines = writtenLines(read.lines);
|
|
4348
|
+
const written = render.preview || terms === void 0 || lines === void 0 ? void 0 : {
|
|
4349
|
+
guideline: guidelineOf(invoice),
|
|
4350
|
+
type: invoice.type,
|
|
4351
|
+
currency: invoice.currency,
|
|
4352
|
+
terms,
|
|
4353
|
+
lines,
|
|
4354
|
+
totals
|
|
4355
|
+
};
|
|
4356
|
+
return {
|
|
4357
|
+
reads: {
|
|
4358
|
+
names: invoiceNames(invoice, totals),
|
|
4359
|
+
columns: read.columns,
|
|
4360
|
+
payable: {
|
|
4361
|
+
amount: totals.duePayable,
|
|
4362
|
+
account
|
|
4363
|
+
}
|
|
4364
|
+
},
|
|
4365
|
+
written
|
|
4366
|
+
};
|
|
4367
|
+
}
|
|
4368
|
+
/**
|
|
4369
|
+
* The file of each kind, around its XML: Factur-X's, named as report-spec
|
|
4370
|
+
* names the file a PDF/A-3b embeds [S]; an XRechnung's, standalone, named
|
|
4371
|
+
* by its syntax, guideline and version. A table over every kind.
|
|
4372
|
+
*/
|
|
4373
|
+
const FILES = {
|
|
4374
|
+
facturX: (invoice, xml) => {
|
|
4375
|
+
const profile = FACTUR_X_PROFILES$1[invoice.profile];
|
|
4376
|
+
return {
|
|
4377
|
+
kind: "facturX",
|
|
4378
|
+
xml,
|
|
4379
|
+
fileName: FACTUR_X$1.fileName,
|
|
4380
|
+
relationship: profile.relationship,
|
|
4381
|
+
conformanceLevel: profile.conformanceLevel
|
|
4382
|
+
};
|
|
4383
|
+
},
|
|
4384
|
+
xrechnung: (invoice, xml) => {
|
|
4385
|
+
const version = XRECHNUNG$1[invoice.version];
|
|
4386
|
+
return {
|
|
4387
|
+
kind: "xrechnung",
|
|
4388
|
+
xml,
|
|
4389
|
+
syntax: version.syntax,
|
|
4390
|
+
guideline: version.guideline,
|
|
4391
|
+
version: invoice.version
|
|
4392
|
+
};
|
|
4393
|
+
}
|
|
4394
|
+
};
|
|
4395
|
+
/** What a preview of an e-invoice warns, whatever data it has. */
|
|
4396
|
+
const PREVIEWED = "this is a preview, which writes no e-invoice: a final render alone writes its XML, and this PDF is not the invoice";
|
|
4397
|
+
/**
|
|
4398
|
+
* The file the PDF of `render` embeds, once its page is lowered: in a
|
|
4399
|
+
* final render the XML, named as report-spec names it; in a preview none,
|
|
4400
|
+
* and the warning that says so. Undefined too where anything was refused,
|
|
4401
|
+
* which refuses the document.
|
|
4402
|
+
*
|
|
4403
|
+
* A final render with nothing to write and nothing recorded would hand on
|
|
4404
|
+
* a document without its XML, which a renderer draws as a plain PDF: a
|
|
4405
|
+
* picture of an invoice handed over as though it were one. Every way to
|
|
4406
|
+
* nothing records an error first, so that is a defect, and throws.
|
|
4407
|
+
*/
|
|
4408
|
+
function eInvoiceFile(render, resolved, invoice) {
|
|
4409
|
+
if (render.preview) {
|
|
4410
|
+
render.problems.warn({
|
|
4411
|
+
stage: "resolve",
|
|
4412
|
+
code: "e-invoice-preview",
|
|
4413
|
+
path: "/eInvoice",
|
|
4414
|
+
message: `the e-invoice: ${PREVIEWED}`
|
|
4415
|
+
});
|
|
4416
|
+
return;
|
|
4417
|
+
}
|
|
4418
|
+
if (render.problems.failed) return void 0;
|
|
4419
|
+
if (resolved.written === void 0) throw new RangeError("a final render of an e-invoice wrote no XML and recorded no reason: a defect, refused rather than drawn as a plain PDF");
|
|
4420
|
+
return FILES[invoice.kind](invoice, ciiXml(resolved.written));
|
|
4421
|
+
}
|
|
4422
|
+
// src/lower-fonts.ts
|
|
4423
|
+
/**
|
|
4424
|
+
* A report's font map resolved to the bytes the renderer embeds (0043).
|
|
4425
|
+
*
|
|
4426
|
+
* The definition maps each font token to approved font assets, face by face
|
|
4427
|
+
* ([report-spec's `font-map.ts`](../../report-spec/src/font-map.ts)); here
|
|
4428
|
+
* the host's lookup hands over each face's bytes, as it does an image's
|
|
4429
|
+
* (0033), and the runtime reads them once with report-spec's `readFont`
|
|
4430
|
+
* before it hands them on, so that a font the renderer could not embed is
|
|
4431
|
+
* refused where the data is resolved, not deep inside the engine. The
|
|
4432
|
+
* renderer reads them again, since it is a package boundary that takes
|
|
4433
|
+
* resolved input and approved bytes and refuses what it cannot draw (0011);
|
|
4434
|
+
* what is read here is read there too, by the one reader.
|
|
4435
|
+
*
|
|
4436
|
+
* A font is structural, not a value: a token a report maps prints all its
|
|
4437
|
+
* text in that face, so a face whose bytes cannot be had, or that `readFont`
|
|
4438
|
+
* refuses, refuses the render -- in a preview too, since a preview that
|
|
4439
|
+
* dropped a mapped face would print its text in another font nobody chose
|
|
4440
|
+
* (fail closed). Each face is fetched once, however many tokens or weights
|
|
4441
|
+
* share one asset.
|
|
4442
|
+
*
|
|
4443
|
+
* Nothing here is shared with the host: the bytes are copied, as an image's
|
|
4444
|
+
* are, so that what the host changes afterwards never reaches the document.
|
|
4445
|
+
*/
|
|
4446
|
+
/**
|
|
4447
|
+
* `fonts` resolved to the bytes each face prints in, or undefined when the
|
|
4448
|
+
* report maps nothing. A face that cannot be had or that `readFont` refuses
|
|
4449
|
+
* records an error and resolves nothing for that face; the caller refuses
|
|
4450
|
+
* the render when any error was recorded.
|
|
4451
|
+
*/
|
|
4452
|
+
function resolveFonts(render, fonts) {
|
|
4453
|
+
if (fonts === void 0) return void 0;
|
|
4454
|
+
const byId = /* @__PURE__ */ new Map();
|
|
4455
|
+
const result = {};
|
|
4456
|
+
for (const [family, faces] of Object.entries(fonts)) {
|
|
4457
|
+
if (faces === void 0) continue;
|
|
4458
|
+
const resolved = {};
|
|
4459
|
+
for (const key of FONT_FACE_KEYS$1) {
|
|
4460
|
+
const id = faces[key];
|
|
4461
|
+
if (id === void 0) continue;
|
|
4462
|
+
const asset = faceAsset(render, byId, id, `/fonts/${family}/${key}`);
|
|
4463
|
+
if (asset !== void 0) resolved[key] = asset;
|
|
4464
|
+
}
|
|
4465
|
+
if (resolved.normal !== void 0) result[family] = resolved;
|
|
4466
|
+
}
|
|
4467
|
+
return result;
|
|
4468
|
+
}
|
|
4469
|
+
/** The bytes of the face asset `id`, fetched once and kept, checked with `readFont`; undefined when it could not be had, which is recorded at `path`. */
|
|
4470
|
+
function faceAsset(render, byId, id, path) {
|
|
4471
|
+
if (byId.has(id)) return byId.get(id);
|
|
4472
|
+
const asset = fetchFace(render, id, path);
|
|
4473
|
+
byId.set(id, asset);
|
|
4474
|
+
return asset;
|
|
4475
|
+
}
|
|
4476
|
+
/** What the host holds for the font asset `id`, copied and read, or undefined with an error recorded at `path`. */
|
|
4477
|
+
function fetchFace(render, id, path) {
|
|
4478
|
+
const error = (code, message) => {
|
|
4479
|
+
render.problems.error({
|
|
4480
|
+
stage: "resolve",
|
|
4481
|
+
code,
|
|
4482
|
+
path,
|
|
4483
|
+
message
|
|
4484
|
+
});
|
|
4485
|
+
};
|
|
4486
|
+
if (render.images === void 0) return error("missing-asset", `the report maps a font, and the host gave no way to fetch approved assets`);
|
|
4487
|
+
const declared = render.report.assets.find((ref) => ref.id === id);
|
|
4488
|
+
let found;
|
|
4489
|
+
try {
|
|
4490
|
+
found = render.images({
|
|
4491
|
+
asset: declared.id,
|
|
4492
|
+
digest: declared.digest
|
|
4493
|
+
});
|
|
4494
|
+
} catch {
|
|
4495
|
+
return error("asset-lookup-failed", `fetching the approved font ${id} failed`);
|
|
4496
|
+
}
|
|
4497
|
+
if (found === void 0) return error("missing-asset", `the host has no bytes for the approved font ${id} at its digest`);
|
|
4498
|
+
if (typeof found !== "object" || !(found.bytes instanceof Uint8Array) || !isFontMediaType$1(found.mediaType)) return error("invalid-asset", `the host's answer for the approved font ${id} is not bytes of ${declared.mediaType}`);
|
|
4499
|
+
if (found.bytes.length > MAX_FONT_BYTES$1) return error("invalid-asset", `the approved font ${id} is ${found.bytes.length} bytes; a font may have ${MAX_FONT_BYTES$1}`);
|
|
4500
|
+
const bytes = new Uint8Array(found.bytes);
|
|
4501
|
+
const read = readFont$1(bytes);
|
|
4502
|
+
if (!read.ok) return error("invalid-asset", `the approved font ${id}: the font ${read.message}`);
|
|
4503
|
+
return {
|
|
4504
|
+
id,
|
|
4505
|
+
digest: declared.digest,
|
|
4506
|
+
bytes
|
|
4507
|
+
};
|
|
4508
|
+
}
|
|
4509
|
+
// src/e-invoice-payable.ts
|
|
4510
|
+
/**
|
|
4511
|
+
* A payment code printed with an e-invoice -- the QR-bill, an EPC QR code
|
|
4512
|
+
* -- held to it once both have resolved: it asks for the amount due for
|
|
4513
|
+
* payment (BT-115), or leaves the amount to the payer, and to be paid to
|
|
4514
|
+
* the e-invoice's payment account (BT-84).
|
|
4515
|
+
*
|
|
4516
|
+
* The page and the XML are one invoice, or the page is a second one: a
|
|
4517
|
+
* picture that asks for another amount or another account than its
|
|
4518
|
+
* structured part says may count as a further invoice under § 14c UStG
|
|
4519
|
+
* (BMF, 15 October 2025, UStAE 14c.1 (4a)). report-spec refuses what a
|
|
4520
|
+
* template's literals break, its currency among them; what only the data
|
|
4521
|
+
* decides -- an amount is always an expression, an account may be read
|
|
4522
|
+
* from a field -- is compared here, by value, the account as each code's
|
|
4523
|
+
* own rule wrote it: its spaces dropped and its letters capitals. A code
|
|
4524
|
+
* whose amount or account its own rules refused is not compared again.
|
|
4525
|
+
*/
|
|
4526
|
+
/**
|
|
4527
|
+
* Records what `code`, which asks for `amount` -- null to leave it to the
|
|
4528
|
+
* payer -- to `account`, asks for that the e-invoice does not name; nothing
|
|
4529
|
+
* in a report that is no e-invoice, or where the e-invoice's account was
|
|
4530
|
+
* refused or a preview lacks it.
|
|
4531
|
+
*/
|
|
4532
|
+
function checkPayable(render, code, amount, account) {
|
|
4533
|
+
const payable = render.invoice?.payable;
|
|
4534
|
+
if (payable === void 0) return;
|
|
4535
|
+
const refuse = (path, message) => render.problems.error({
|
|
4536
|
+
stage: "resolve",
|
|
4537
|
+
code: "invalid-e-invoice",
|
|
4538
|
+
path,
|
|
4539
|
+
message: `${code.said}: ${message}`,
|
|
4540
|
+
...code.componentId === void 0 ? {} : { componentId: code.componentId }
|
|
4541
|
+
});
|
|
4542
|
+
if (amount !== null && compareDecimal(amount, payable.amount) !== 0) refuse(code.amountPath, `${code.code} asks for another amount than the e-invoice's amount due for payment (BT-115): a page and its XML ask for one amount`);
|
|
4543
|
+
if (payable.account !== void 0 && account !== payable.account) refuse(code.accountPath, `${code.code} asks to be paid to another account than the e-invoice's payment account (BT-84): a page and its XML name one account`);
|
|
4544
|
+
}
|
|
4545
|
+
// src/qr-bill.ts
|
|
4546
|
+
/**
|
|
4547
|
+
* A Swiss QR-bill made from values SIX's rules have accepted: the Swiss QR
|
|
4548
|
+
* Code's payload, and every text its slip prints.
|
|
4549
|
+
*
|
|
4550
|
+
* The rules a value is held to are report-spec's (`qr-bill.ts` there), one
|
|
4551
|
+
* set for a literal at validation and for a value from data here. What is
|
|
4552
|
+
* the runtime's alone is what a checked bill becomes:
|
|
4553
|
+
*
|
|
4554
|
+
* - **The payload**, in the order of IG Table 8, each element on its line.
|
|
4555
|
+
* - **The printed values**, grouped as the slip prints them (IG 3.5, 3.6).
|
|
4556
|
+
* - **The headings**, in the slip's language (IG Annex C).
|
|
4557
|
+
*
|
|
4558
|
+
* Nothing here reads a value as a number: an amount's digits are grouped
|
|
4559
|
+
* as text. "IG" is SIX's Swiss Implementation Guidelines for the QR-bill,
|
|
4560
|
+
* version 2.4 of 24 February 2026, whose payload, printing rules and
|
|
4561
|
+
* headings are version 2.3's, but for the Romansh headings it adds.
|
|
4562
|
+
*/
|
|
4563
|
+
/**
|
|
4564
|
+
* IG Annex C, Table 23, version 2.4, read in its PDF's text. Version 2.3's
|
|
4565
|
+
* English table printed Italian's currency as "Value date" and two French
|
|
4566
|
+
* words wrongly, which version 2.4 and the French edition correct; and
|
|
4567
|
+
* version 2.4 adds Romansh, in force since 1 January 2026.
|
|
4568
|
+
*/
|
|
4569
|
+
const HEADINGS = {
|
|
4570
|
+
de: {
|
|
4571
|
+
paymentPart: "Zahlteil",
|
|
4572
|
+
receipt: "Empfangsschein",
|
|
4573
|
+
account: "Konto / Zahlbar an",
|
|
4574
|
+
reference: "Referenz",
|
|
4575
|
+
additionalInformation: "Zusätzliche Informationen",
|
|
4576
|
+
payableBy: "Zahlbar durch",
|
|
4577
|
+
payableByBlank: "Zahlbar durch (Name/Adresse)",
|
|
4578
|
+
currency: "Währung",
|
|
4579
|
+
amount: "Betrag",
|
|
4580
|
+
acceptancePoint: "Annahmestelle",
|
|
4581
|
+
separate: "Vor der Einzahlung abzutrennen"
|
|
4582
|
+
},
|
|
4583
|
+
fr: {
|
|
4584
|
+
paymentPart: "Section paiement",
|
|
4585
|
+
receipt: "Récépissé",
|
|
4586
|
+
account: "Compte / Payable à",
|
|
4587
|
+
reference: "Référence",
|
|
4588
|
+
additionalInformation: "Informations supplémentaires",
|
|
4589
|
+
payableBy: "Payable par",
|
|
4590
|
+
payableByBlank: "Payable par (nom/adresse)",
|
|
4591
|
+
currency: "Monnaie",
|
|
4592
|
+
amount: "Montant",
|
|
4593
|
+
acceptancePoint: "Point de dépôt",
|
|
4594
|
+
separate: "A détacher avant le versement"
|
|
4595
|
+
},
|
|
4596
|
+
it: {
|
|
4597
|
+
paymentPart: "Sezione pagamento",
|
|
4598
|
+
receipt: "Ricevuta",
|
|
4599
|
+
account: "Conto / Pagabile a",
|
|
4600
|
+
reference: "Riferimento",
|
|
4601
|
+
additionalInformation: "Informazioni supplementari",
|
|
4602
|
+
payableBy: "Pagabile da",
|
|
4603
|
+
payableByBlank: "Pagabile da (nome/indirizzo)",
|
|
4604
|
+
currency: "Valuta",
|
|
4605
|
+
amount: "Importo",
|
|
4606
|
+
acceptancePoint: "Punto di accettazione",
|
|
4607
|
+
separate: "Da staccare prima del versamento"
|
|
4608
|
+
},
|
|
4609
|
+
en: {
|
|
4610
|
+
paymentPart: "Payment part",
|
|
4611
|
+
receipt: "Receipt",
|
|
4612
|
+
account: "Account / Payable to",
|
|
4613
|
+
reference: "Reference",
|
|
4614
|
+
additionalInformation: "Additional information",
|
|
4615
|
+
payableBy: "Payable by",
|
|
4616
|
+
payableByBlank: "Payable by (name/address)",
|
|
4617
|
+
currency: "Currency",
|
|
4618
|
+
amount: "Amount",
|
|
4619
|
+
acceptancePoint: "Acceptance point",
|
|
4620
|
+
separate: "Separate before paying in"
|
|
4621
|
+
},
|
|
4622
|
+
rm: {
|
|
4623
|
+
paymentPart: "Part da pajament",
|
|
4624
|
+
receipt: "Quittanza",
|
|
4625
|
+
account: "Conto / Da pajar a",
|
|
4626
|
+
reference: "Referenza",
|
|
4627
|
+
additionalInformation: "Infurmaziuns supplementaras",
|
|
4628
|
+
payableBy: "Da pajar da",
|
|
4629
|
+
payableByBlank: "Da pajar da (num/adressa)",
|
|
4630
|
+
currency: "Valuta",
|
|
4631
|
+
amount: "Import",
|
|
4632
|
+
acceptancePoint: "Post da recepziun",
|
|
4633
|
+
separate: "Da distatgar avant che pajar"
|
|
4634
|
+
}
|
|
4635
|
+
};
|
|
4636
|
+
/** An address's parts in the order the code holds them, which report-spec's table of their rules is in. */
|
|
4637
|
+
const ADDRESS_PARTS$1 = Object.keys(QR_BILL_ADDRESS_RULES);
|
|
4638
|
+
/** A party's seven lines (IG Table 8): the structured address type, S, and its parts; none at all, seven empty lines. */
|
|
4639
|
+
function party(address) {
|
|
4640
|
+
return address === null ? ["", ...ADDRESS_PARTS$1.map(() => "")] : ["S", ...ADDRESS_PARTS$1.map((part) => address[part])];
|
|
4641
|
+
}
|
|
4642
|
+
/**
|
|
4643
|
+
* The Swiss QR Code's text (IG 4.1.4, Table 8). Every element is on its
|
|
4644
|
+
* line, an empty one as an empty line, and the lines are separated by a
|
|
4645
|
+
* line feed, with none after the last. The ultimate creditor's lines are
|
|
4646
|
+
* empty: SIX keeps them for later use and they "must not be filled in".
|
|
4647
|
+
* Billing information, of status A, is left out when the bill has none:
|
|
4648
|
+
* nothing after it is ever used, since this format has no alternative
|
|
4649
|
+
* procedure. Version 0200 is the only one SIX allows in master version 02,
|
|
4650
|
+
* and coding 1 is UTF-8 restricted to the characters of IG 4.1.1.
|
|
4651
|
+
*/
|
|
4652
|
+
function payload(bill) {
|
|
4653
|
+
return [
|
|
4654
|
+
"SPC",
|
|
4655
|
+
"0200",
|
|
4656
|
+
"1",
|
|
4657
|
+
bill.account.iban,
|
|
4658
|
+
...party(bill.creditor),
|
|
4659
|
+
...party(null),
|
|
4660
|
+
bill.amount ?? "",
|
|
4661
|
+
bill.currency,
|
|
4662
|
+
...party(bill.debtor),
|
|
4663
|
+
bill.reference?.type ?? "NON",
|
|
4664
|
+
bill.reference?.reference ?? "",
|
|
4665
|
+
bill.message,
|
|
4666
|
+
"EPD",
|
|
4667
|
+
...bill.billingInformation === "" ? [] : [bill.billingInformation]
|
|
4668
|
+
].join("\n");
|
|
4669
|
+
}
|
|
4670
|
+
/** `text` in blocks of `size` characters from its start, the last block shorter. */
|
|
4671
|
+
function blocks(text, size) {
|
|
4672
|
+
const parts = [];
|
|
4673
|
+
for (let start = 0; start < text.length; start += size) parts.push(text.slice(start, start + size));
|
|
4674
|
+
return parts.join(" ");
|
|
4675
|
+
}
|
|
4676
|
+
/** A QR reference in two digits and five blocks of five; a creditor reference in blocks of four (IG 3.5.4). */
|
|
4677
|
+
function printedReference(reference) {
|
|
4678
|
+
const { type, reference: text } = reference;
|
|
4679
|
+
return type === "QRR" ? `${text.slice(0, 2)} ${blocks(text.slice(2), 5)}` : blocks(text, 4);
|
|
4680
|
+
}
|
|
4681
|
+
/** The amount with a space between each three digits before the point (IG 3.5.3: "CHF 1 590.00"), grouped as text. */
|
|
4682
|
+
function printedAmount(amount) {
|
|
4683
|
+
const [whole = "", cents = ""] = amount.split(".");
|
|
4684
|
+
const groups = [];
|
|
4685
|
+
for (let end = whole.length; end > 0; end -= 3) groups.unshift(whole.slice(Math.max(0, end - 3), end));
|
|
4686
|
+
return `${groups.join(" ")}.${cents}`;
|
|
4687
|
+
}
|
|
4688
|
+
/**
|
|
4689
|
+
* An address as the slip prints it, as IG 3.5.4 and SIX's style guide show
|
|
4690
|
+
* it: the name; the street and building number, on one line; the postal
|
|
4691
|
+
* code and the town. The country is printed for a party outside
|
|
4692
|
+
* Switzerland, Liechtenstein one of them; the guidelines do not say how,
|
|
4693
|
+
* and it goes before the postal code, as in "LI-9490 Vaduz".
|
|
4694
|
+
*/
|
|
4695
|
+
function printedAddress(address) {
|
|
4696
|
+
const street = [address.street, address.buildingNumber].filter((part) => part !== "").join(" ");
|
|
4697
|
+
const country = address.country === "CH" ? "" : `${address.country}-`;
|
|
4698
|
+
return [
|
|
4699
|
+
address.name,
|
|
4700
|
+
...street === "" ? [] : [street],
|
|
4701
|
+
`${country}${address.postalCode} ${address.town}`
|
|
4702
|
+
];
|
|
4703
|
+
}
|
|
4704
|
+
/** The document's bill: `bill`'s payload, and every text its slip prints, in its language. */
|
|
4705
|
+
function qrBillPart(bill) {
|
|
4706
|
+
const { payableByBlank, payableBy, ...words } = HEADINGS[bill.language];
|
|
4707
|
+
return {
|
|
4708
|
+
kind: "swissQrBill",
|
|
4709
|
+
payload: payload(bill),
|
|
4710
|
+
headings: {
|
|
4711
|
+
...words,
|
|
4712
|
+
payableBy: bill.debtor === null ? payableByBlank : payableBy
|
|
4713
|
+
},
|
|
4714
|
+
account: blocks(bill.account.iban, 4),
|
|
4715
|
+
creditor: printedAddress(bill.creditor),
|
|
4716
|
+
reference: bill.reference === null ? null : printedReference(bill.reference),
|
|
4717
|
+
additionalInformation: [bill.message, bill.billingInformation].filter((text) => text !== ""),
|
|
4718
|
+
debtor: bill.debtor === null ? null : printedAddress(bill.debtor),
|
|
4719
|
+
currency: bill.currency,
|
|
4720
|
+
amount: bill.amount === null ? null : printedAmount(bill.amount)
|
|
4721
|
+
};
|
|
4722
|
+
}
|
|
4723
|
+
// src/lower-payment-part.ts
|
|
4724
|
+
/**
|
|
4725
|
+
* A report's payment part lowered to the document's: each text read in the
|
|
4726
|
+
* report's scope, held to SIX's rules, and made into the bill
|
|
4727
|
+
* (`qr-bill.ts`).
|
|
4728
|
+
*
|
|
4729
|
+
* - **Read as a paragraph.** Every text is its runs, read as a paragraph's
|
|
4730
|
+
* in the report's scope and joined as a QR code's content is
|
|
4731
|
+
* (`joinedText`): a final render refuses a run whose value is null, as
|
|
4732
|
+
* `no-qr-value`, since the bill's code would say less than its texts.
|
|
4733
|
+
* - **Held to SIX's rules.** report-spec's checks, the very functions its
|
|
4734
|
+
* validator applies to a literal, are applied to every text once it has
|
|
4735
|
+
* resolved: a literal passes again, and a value from data is held where
|
|
4736
|
+
* the validator could not see it. A rule broken is `invalid-qr-bill` on
|
|
4737
|
+
* the field, naming the rule and never the value, which may be a
|
|
4738
|
+
* person's name or account.
|
|
4739
|
+
* - **The same in a preview.** A preview prints a value that is null, or
|
|
4740
|
+
* one its data lacks, as nothing, as a paragraph does; the bill that
|
|
4741
|
+
* leaves is held to the same rules, and refused where it breaks one,
|
|
4742
|
+
* saying the preview had no value for it. A bill SIX refuses cannot be
|
|
4743
|
+
* drawn as one: its code would scan as a bill no bank pays.
|
|
4744
|
+
* - **The amount** is a decimal, or null for the payer to fill in. Any
|
|
4745
|
+
* other value is refused by its type, and a decimal is written with its
|
|
4746
|
+
* own digits, never rounded: one with more than two places is refused.
|
|
4747
|
+
* - **Printed with an e-invoice**, it asks for the amount due and to be
|
|
4748
|
+
* paid to the e-invoice's account (`e-invoice-payable.ts`).
|
|
4749
|
+
*/
|
|
4750
|
+
const PATH = "/paymentPart";
|
|
4751
|
+
/** What an error in the payment part names it by: it stands in no component. */
|
|
4752
|
+
const PART = {
|
|
4753
|
+
said: "the payment part",
|
|
4754
|
+
code: "a QR-bill"
|
|
4755
|
+
};
|
|
4756
|
+
function refuse$1({ render }, path, message) {
|
|
4757
|
+
render.problems.error({
|
|
4758
|
+
stage: "resolve",
|
|
4759
|
+
code: "invalid-qr-bill",
|
|
4760
|
+
path,
|
|
4761
|
+
message
|
|
4762
|
+
});
|
|
4763
|
+
}
|
|
4764
|
+
/**
|
|
4765
|
+
* The text the runs at `path` print, held to `check`, as `what` names it in
|
|
4766
|
+
* an error: what the check made of it, or undefined when a run or the rule
|
|
4767
|
+
* refused it, which is recorded. Absent runs print nothing, which the rule
|
|
4768
|
+
* judges: an optional text, nothing; a required one, empty.
|
|
4769
|
+
*/
|
|
4770
|
+
function checked$1(lowering, runs, path, what, check) {
|
|
4771
|
+
const joined = joinedText(lowering.render, lowering.scope, runs ?? [], path, PART);
|
|
4772
|
+
if (joined === void 0) return void 0;
|
|
4773
|
+
const outcome = check(joined.text);
|
|
4774
|
+
if (outcome.ok) return outcome.value;
|
|
4775
|
+
return refuse$1(lowering, path, `${what} ${outcome.rule}${joined.lacking ? "; this preview has no value for a run of it" : ""}`);
|
|
1727
4776
|
}
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
4777
|
+
const ADDRESS_PARTS = Object.entries(QR_BILL_ADDRESS_RULES);
|
|
4778
|
+
/** A party's address, each part held to its rule; undefined when a part is refused, which is recorded. */
|
|
4779
|
+
function address(lowering, value, path, party) {
|
|
4780
|
+
const parts = {};
|
|
4781
|
+
let whole = true;
|
|
4782
|
+
for (const [part, rule] of ADDRESS_PARTS) {
|
|
4783
|
+
const text = checked$1(lowering, value[part], `${path}/${part}`, `the ${party}'s ${rule.said}`, (each) => checkQrBillText(each, rule));
|
|
4784
|
+
if (text === void 0) whole = false;
|
|
4785
|
+
else parts[part] = text;
|
|
4786
|
+
}
|
|
4787
|
+
return whole ? parts : void 0;
|
|
1731
4788
|
}
|
|
1732
|
-
|
|
1733
|
-
|
|
4789
|
+
/** The amount as the code writes it, null for the payer to fill in, or undefined when it is refused, which is recorded. */
|
|
4790
|
+
function amount$1(lowering, expression) {
|
|
4791
|
+
if (expression === void 0) return null;
|
|
4792
|
+
const path = `${PATH}/amount`;
|
|
4793
|
+
const value = valueOf(lowering.render, lowering.scope, `${path}/cel`);
|
|
4794
|
+
if (value === void 0 || value === null) return value;
|
|
4795
|
+
if (value.type !== "decimal") return refuse$1(lowering, path, `the amount gives ${value.type}, and a QR-bill's amount is a decimal, or null to leave it for the payer`);
|
|
4796
|
+
const outcome = checkQrBillAmount$1(decimalToString(value.value));
|
|
4797
|
+
return outcome.ok ? outcome.value : refuse$1(lowering, path, `the amount ${outcome.rule}`);
|
|
1734
4798
|
}
|
|
1735
|
-
/**
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
const
|
|
1743
|
-
const
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
4799
|
+
/** `bill`, resolved and held to SIX's rules; undefined when anything of it is refused, which is recorded. */
|
|
4800
|
+
function swissQrBill(lowering, bill) {
|
|
4801
|
+
const account = checked$1(lowering, bill.account, `${PATH}/account`, "the account", checkQrBillAccount);
|
|
4802
|
+
const creditor = address(lowering, bill.creditor, `${PATH}/creditor`, "creditor");
|
|
4803
|
+
const sum = amount$1(lowering, bill.amount);
|
|
4804
|
+
const debtor = bill.debtor === void 0 ? null : address(lowering, bill.debtor, `${PATH}/debtor`, "debtor");
|
|
4805
|
+
const reference = bill.reference === void 0 ? null : checked$1(lowering, bill.reference, `${PATH}/reference`, "the reference", checkQrBillReference);
|
|
4806
|
+
const message = checked$1(lowering, bill.message, `${PATH}/message`, "the message", (text) => checkQrBillText(text, QR_BILL_MESSAGE_RULE));
|
|
4807
|
+
const billing = checked$1(lowering, bill.billingInformation, `${PATH}/billingInformation`, "the billing information", (text) => checkQrBillText(text, QR_BILL_BILLING_RULE));
|
|
4808
|
+
const together = message === void 0 || billing === void 0 ? void 0 : checkQrBillAdditionalInformation(message, billing);
|
|
4809
|
+
if (together !== void 0) refuse$1(lowering, `${PATH}/message`, together);
|
|
4810
|
+
if (account !== void 0 && sum !== void 0) {
|
|
4811
|
+
const asked = {
|
|
4812
|
+
said: PART.said,
|
|
4813
|
+
code: "the QR-bill",
|
|
4814
|
+
amountPath: `${PATH}/amount`,
|
|
4815
|
+
accountPath: `${PATH}/account`
|
|
4816
|
+
};
|
|
4817
|
+
checkPayable(lowering.render, asked, sum === null ? null : decimalFromString(sum), account.iban);
|
|
4818
|
+
}
|
|
4819
|
+
const pairing = account === void 0 || reference === void 0 ? [] : qrBillPairing(account.qrIban ? "qrIban" : "iban", reference?.type ?? "NON", bill.currency);
|
|
4820
|
+
for (const { field, rule } of pairing) refuse$1(lowering, `${PATH}/${field}`, rule);
|
|
4821
|
+
if (together !== void 0 || pairing.length > 0) return void 0;
|
|
4822
|
+
if (account === void 0 || creditor === void 0 || sum === void 0 || debtor === void 0 || reference === void 0 || message === void 0 || billing === void 0) return void 0;
|
|
4823
|
+
return qrBillPart({
|
|
4824
|
+
language: bill.language,
|
|
4825
|
+
account,
|
|
4826
|
+
creditor,
|
|
4827
|
+
currency: bill.currency,
|
|
4828
|
+
amount: sum,
|
|
4829
|
+
debtor,
|
|
4830
|
+
reference,
|
|
4831
|
+
message,
|
|
4832
|
+
billingInformation: billing
|
|
4833
|
+
});
|
|
1749
4834
|
}
|
|
1750
|
-
/**
|
|
1751
|
-
|
|
1752
|
-
|
|
4835
|
+
/** How each kind of payment part is lowered. A table over every kind, so a kind added to report-spec without a way down does not compile. */
|
|
4836
|
+
const PARTS = { swissQrBill };
|
|
4837
|
+
/** `render`'s payment part, lowered; undefined when the report has none, or when it is refused, which is recorded. */
|
|
4838
|
+
function lowerPaymentPart(render) {
|
|
4839
|
+
const part = render.report.paymentPart;
|
|
4840
|
+
if (part === void 0) return void 0;
|
|
4841
|
+
return PARTS[part.kind]({
|
|
4842
|
+
render,
|
|
4843
|
+
scope: reportScope(render, render.totals.report)
|
|
4844
|
+
}, part);
|
|
1753
4845
|
}
|
|
1754
|
-
|
|
1755
|
-
//#region src/images.ts
|
|
4846
|
+
// src/images.ts
|
|
1756
4847
|
/**
|
|
1757
4848
|
* An image component lowered to the bytes it draws.
|
|
1758
4849
|
*
|
|
@@ -1763,11 +4854,14 @@ function imageValue(render, ref) {
|
|
|
1763
4854
|
* bytes, and a media type a report may draw, the one the template declares
|
|
1764
4855
|
* for its own asset -- and copied, so that nothing the host changes
|
|
1765
4856
|
* afterwards reaches the document. Whether the bytes are a picture is the
|
|
1766
|
-
* renderer's to say (`invalid-asset`)
|
|
4857
|
+
* renderer's to say (`invalid-asset`): for an SVG, whether they are exactly
|
|
4858
|
+
* the drawing report-spec's `cleanSvg` writes, by report-spec's `checkSvg`,
|
|
4859
|
+
* which the renderer applies (0030).
|
|
1767
4860
|
*
|
|
1768
|
-
* The lookup is trusted to return the bytes the digest pins
|
|
1769
|
-
*
|
|
1770
|
-
*
|
|
4861
|
+
* The lookup is trusted to return the bytes the digest pins, and they are
|
|
4862
|
+
* not checked against it. Not for want of a hash: a pure SHA-256 reaches the
|
|
4863
|
+
* runtime through `@formancy/spec`, and checking digests is a decision of
|
|
4864
|
+
* its own, since it changes what every host's resolver must satisfy (0030).
|
|
1771
4865
|
*
|
|
1772
4866
|
* An image field with no value draws nothing, and its box is kept as space,
|
|
1773
4867
|
* so that what follows it stands where it would with a picture: null prints
|
|
@@ -1775,8 +4869,11 @@ function imageValue(render, ref) {
|
|
|
1775
4869
|
*
|
|
1776
4870
|
* Each approved asset is asked for once per render, and every image that
|
|
1777
4871
|
* draws it shares the one copy, so that a logo on every page header, or a
|
|
1778
|
-
* photo drawn by forty components, is held
|
|
1779
|
-
*
|
|
4872
|
+
* photo drawn by forty components, is held once: a PNG or a JPEG is
|
|
4873
|
+
* embedded once, and an SVG is drawn again wherever it prints, on every
|
|
4874
|
+
* page of a page region (0030). An answer past its type's limit --
|
|
4875
|
+
* `MAX_ASSET_BYTES`, or `MAX_SVG_BYTES` for an SVG -- is refused before it
|
|
4876
|
+
* is copied.
|
|
1780
4877
|
*/
|
|
1781
4878
|
/** What the host handed over, if it is bytes of a media type a report draws, within the limit: copied. A string says why it is not. */
|
|
1782
4879
|
function checkedBytes(found, declared) {
|
|
@@ -1785,7 +4882,8 @@ function checkedBytes(found, declared) {
|
|
|
1785
4882
|
const { mediaType, bytes } = found;
|
|
1786
4883
|
if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType)) return media;
|
|
1787
4884
|
if (declared !== void 0 && mediaType !== declared) return media;
|
|
1788
|
-
if (bytes.length >
|
|
4885
|
+
if (mediaType === "image/svg+xml" && bytes.length > MAX_SVG_BYTES$1) return `is ${bytes.length} bytes; an SVG asset may have ${MAX_SVG_BYTES$1} (1 MiB)`;
|
|
4886
|
+
if (bytes.length > MAX_ASSET_BYTES$1) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES$1} (20 MB)`;
|
|
1789
4887
|
return {
|
|
1790
4888
|
mediaType,
|
|
1791
4889
|
bytes: new Uint8Array(bytes)
|
|
@@ -1879,53 +4977,152 @@ function imageBlock(render, component, path) {
|
|
|
1879
4977
|
fit: component.fit
|
|
1880
4978
|
};
|
|
1881
4979
|
}
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
4980
|
+
// src/lower-epc-qr-code.ts
|
|
4981
|
+
/**
|
|
4982
|
+
* An EPC QR code lowered to the document's block: each text read in the
|
|
4983
|
+
* report's scope, held to the EPC's rules, and written into the payload the
|
|
4984
|
+
* renderer encodes. "EPC" is EPC069-12, version 3.1, by its section.
|
|
4985
|
+
*
|
|
4986
|
+
* - **Read as a paragraph.** Every text is its runs, read as a paragraph's
|
|
4987
|
+
* in the report's scope and joined as a QR code's content is
|
|
4988
|
+
* (`joinedText`): a final render refuses a run whose value is null, as
|
|
4989
|
+
* `no-qr-value`, since the transfer would say less than the invoice --
|
|
4990
|
+
* unless the text is optional and prints nothing else.
|
|
4991
|
+
* - **Held to the EPC's rules.** report-spec's checks (`epc-payload.ts`),
|
|
4992
|
+
* the very functions its validator applies to a literal, are applied to
|
|
4993
|
+
* every text once it has resolved: a literal passes again, and a value
|
|
4994
|
+
* from data is held where the validator could not see it -- the IBAN's
|
|
4995
|
+
* spaces dropped and its letters made capitals, its country's, its
|
|
4996
|
+
* length and its check digits; the BIC, and whether the account needs
|
|
4997
|
+
* one; the creditor reference; each text's characters and length. A rule
|
|
4998
|
+
* broken is `invalid-epc-qr-code` on the field, naming the code and the
|
|
4999
|
+
* rule and never the value, which may be a person's name or account.
|
|
5000
|
+
* - **An optional text that prints nothing is unused.** A BIC, a
|
|
5001
|
+
* reference, a text or information the data gives empty, blank or null
|
|
5002
|
+
* is an element the code leaves empty, as one the template does not
|
|
5003
|
+
* have, in a final render as in a preview: a customer with no BIC on
|
|
5004
|
+
* record is paid by version 002, never refused for a BIC that is no BIC.
|
|
5005
|
+
* The validator refuses a blank literal instead, a second spelling of an
|
|
5006
|
+
* element left out.
|
|
5007
|
+
* - **The same in a preview.** A preview prints a value that is null, or
|
|
5008
|
+
* one its data lacks, as nothing, as a paragraph does; the code that
|
|
5009
|
+
* leaves is held to the same rules, and refused where it breaks one,
|
|
5010
|
+
* saying the preview had no value for it. A code the EPC refuses cannot
|
|
5011
|
+
* be drawn as one: it would scan as a transfer no bank makes.
|
|
5012
|
+
* - **The amount** is a decimal, or null for the payer to fill in. Any
|
|
5013
|
+
* other value is refused by its type, and a decimal is written with its
|
|
5014
|
+
* own digits, as short as it can be, never rounded: one with more than
|
|
5015
|
+
* two places is refused.
|
|
5016
|
+
* - **The payload** is report-spec's `epcPayload` of the checked texts,
|
|
5017
|
+
* held to the EPC's 331 bytes in UTF-8, which only the whole can break.
|
|
5018
|
+
* - **Printed with an e-invoice**, it asks for the amount due and to be
|
|
5019
|
+
* paid to the e-invoice's account (`e-invoice-payable.ts`).
|
|
5020
|
+
*/
|
|
5021
|
+
/** What a refusal adds when a preview had no value for a run of the text it refuses. */
|
|
5022
|
+
const LACKED = "; this preview has no value for a run of it";
|
|
5023
|
+
function refuse({ render, code, encoder }, path, message) {
|
|
1912
5024
|
render.problems.error({
|
|
1913
|
-
stage: "
|
|
1914
|
-
code:
|
|
5025
|
+
stage: "resolve",
|
|
5026
|
+
code: "invalid-epc-qr-code",
|
|
1915
5027
|
path,
|
|
1916
|
-
message: `${
|
|
1917
|
-
|
|
1918
|
-
...owner,
|
|
1919
|
-
row: scope.row
|
|
1920
|
-
})
|
|
5028
|
+
message: `${encoder.said}: ${message}`,
|
|
5029
|
+
componentId: code.id
|
|
1921
5030
|
});
|
|
1922
5031
|
}
|
|
1923
|
-
/**
|
|
1924
|
-
|
|
1925
|
-
|
|
5032
|
+
/**
|
|
5033
|
+
* The text `key` of the code, resolved and held to its field's rule
|
|
5034
|
+
* (report-spec's `EPC_TEXT_FIELDS`); undefined when a run or the rule
|
|
5035
|
+
* refused it, which is recorded. An optional text that prints nothing a
|
|
5036
|
+
* payer reads (`epcBlank`), nulls and all, is its element unused, and no
|
|
5037
|
+
* rule is asked.
|
|
5038
|
+
*/
|
|
5039
|
+
function checked(lowering, key) {
|
|
5040
|
+
const runs = lowering.code[key];
|
|
5041
|
+
if (runs === void 0) return {
|
|
5042
|
+
text: "",
|
|
5043
|
+
lacking: false
|
|
5044
|
+
};
|
|
5045
|
+
const path = `${lowering.path}/${key}`;
|
|
5046
|
+
const { what, optional } = EPC_TEXT_FIELDS[key];
|
|
5047
|
+
const joined = joinedText(lowering.render, lowering.scope, runs, path, lowering.encoder, optional ? epcBlank : void 0);
|
|
5048
|
+
if (joined === void 0) return void 0;
|
|
5049
|
+
if (optional && epcBlank(joined.text)) return {
|
|
5050
|
+
text: "",
|
|
5051
|
+
lacking: joined.lacking
|
|
5052
|
+
};
|
|
5053
|
+
const outcome = checkEpcField(key, joined.text);
|
|
5054
|
+
if (outcome.ok) return {
|
|
5055
|
+
text: outcome.value,
|
|
5056
|
+
lacking: joined.lacking
|
|
5057
|
+
};
|
|
5058
|
+
return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? LACKED : ""}`);
|
|
5059
|
+
}
|
|
5060
|
+
/** The amount as the code writes it after `EUR`, '' for the payer to fill in, or undefined when it is refused, which is recorded. */
|
|
5061
|
+
function amount(lowering) {
|
|
5062
|
+
if (lowering.code.amount === void 0) return "";
|
|
5063
|
+
const path = `${lowering.path}/amount`;
|
|
5064
|
+
const value = valueOf(lowering.render, lowering.scope, `${path}/cel`);
|
|
5065
|
+
if (value === void 0) return void 0;
|
|
5066
|
+
if (value === null) return "";
|
|
5067
|
+
if (value.type !== "decimal") return refuse(lowering, path, `the amount gives ${value.type}, and an EPC QR code's amount is a decimal in euro, or null to leave it for the payer`);
|
|
5068
|
+
const outcome = checkEpcAmount(decimalToString(value.value));
|
|
5069
|
+
return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`);
|
|
5070
|
+
}
|
|
5071
|
+
/**
|
|
5072
|
+
* The block the EPC QR code `code`, at `path`, prints, read in `scope`;
|
|
5073
|
+
* undefined when anything of it is refused, which is recorded. Every text
|
|
5074
|
+
* is read and every rule broken said, not the first alone.
|
|
5075
|
+
*/
|
|
5076
|
+
function epcQrCodeBlock(render, scope, code, path) {
|
|
5077
|
+
const lowering = {
|
|
5078
|
+
render,
|
|
5079
|
+
scope,
|
|
5080
|
+
code,
|
|
5081
|
+
path,
|
|
5082
|
+
encoder: {
|
|
5083
|
+
said: `component ${code.id}`,
|
|
5084
|
+
componentId: code.id,
|
|
5085
|
+
code: "an EPC QR code"
|
|
5086
|
+
}
|
|
5087
|
+
};
|
|
5088
|
+
const bic = checked(lowering, "bic");
|
|
5089
|
+
const beneficiary = checked(lowering, "beneficiary");
|
|
5090
|
+
const iban = checked(lowering, "iban");
|
|
5091
|
+
const sum = amount(lowering);
|
|
5092
|
+
const reference = checked(lowering, "reference");
|
|
5093
|
+
const text = checked(lowering, "text");
|
|
5094
|
+
const information = checked(lowering, "information");
|
|
5095
|
+
const pairing = epcPairing(iban?.text, bic === void 0 ? void 0 : bic.text === "" ? null : bic.text);
|
|
5096
|
+
for (const { field, rule } of pairing) refuse(lowering, `${path}/${field}`, `${rule}${bic?.lacking === true ? LACKED : ""}`);
|
|
5097
|
+
if (iban !== void 0 && sum !== void 0) checkPayable(render, {
|
|
5098
|
+
said: lowering.encoder.said,
|
|
5099
|
+
code: "the EPC QR code",
|
|
5100
|
+
componentId: code.id,
|
|
5101
|
+
amountPath: `${path}/amount`,
|
|
5102
|
+
accountPath: `${path}/iban`
|
|
5103
|
+
}, sum === "" ? null : decimalFromString(sum), iban.text);
|
|
5104
|
+
if (pairing.length > 0 || bic === void 0 || beneficiary === void 0 || iban === void 0 || sum === void 0 || reference === void 0 || text === void 0 || information === void 0) return void 0;
|
|
5105
|
+
const payload = epcPayload({
|
|
5106
|
+
bic: bic.text,
|
|
5107
|
+
beneficiary: beneficiary.text,
|
|
5108
|
+
iban: iban.text,
|
|
5109
|
+
amount: sum,
|
|
5110
|
+
purpose: code.purpose,
|
|
5111
|
+
reference: reference.text,
|
|
5112
|
+
text: text.text,
|
|
5113
|
+
information: information.text
|
|
5114
|
+
});
|
|
5115
|
+
const bytes = checkEpcPayload(payload);
|
|
5116
|
+
if (!bytes.ok) return refuse(lowering, path, `its payload ${bytes.rule}`);
|
|
5117
|
+
return {
|
|
5118
|
+
kind: "epcQrCode",
|
|
5119
|
+
id: code.id,
|
|
5120
|
+
payload,
|
|
5121
|
+
size: code.size,
|
|
5122
|
+
...code.caption === void 0 ? {} : { caption: code.caption }
|
|
5123
|
+
};
|
|
1926
5124
|
}
|
|
1927
|
-
|
|
1928
|
-
//#region src/styles.ts
|
|
5125
|
+
// src/styles.ts
|
|
1929
5126
|
/** Each print style as the document's: the same tokens without the id. */
|
|
1930
5127
|
function documentStyles(styles) {
|
|
1931
5128
|
return new Map(styles.map(({ id, ...style }) => [id, style]));
|
|
@@ -1945,8 +5142,7 @@ function styled(render, scope, base, style, rules, path) {
|
|
|
1945
5142
|
for (const [index, rule] of (rules ?? []).entries()) if (holds(render, scope, `${path}/${index}/when/cel`) === true) held.push(render.styles.get(rule.style));
|
|
1946
5143
|
return layered(base, style === void 0 ? void 0 : render.styles.get(style), ...held);
|
|
1947
5144
|
}
|
|
1948
|
-
|
|
1949
|
-
//#region src/lower-table.ts
|
|
5145
|
+
// src/lower-table.ts
|
|
1950
5146
|
/** `style` as a row's: the table's under the named print style; absent when neither sets anything. */
|
|
1951
5147
|
function rowStyle(lowering, style) {
|
|
1952
5148
|
const resolved = layered(lowering.base, style === void 0 ? void 0 : lowering.render.styles.get(style));
|
|
@@ -1999,13 +5195,15 @@ function groupedRows(lowering, groups) {
|
|
|
1999
5195
|
const rows = [];
|
|
2000
5196
|
for (const each of groups) {
|
|
2001
5197
|
if (render.problems.full) break;
|
|
2002
|
-
const scope = groupScope(render, each, render.totals.over(each.rows), group.by.field);
|
|
5198
|
+
const scope = groupScope(render, each, render.totals.over(each.rows), lowering.totals, group.by.field);
|
|
2003
5199
|
const runs = group.header.map((inline, index) => runOf(render, scope, inline, `${path}/group/header/${index}`, { componentId: table.id }));
|
|
5200
|
+
const keep = Math.min(group.keepWithRows ?? 1, each.rows.length);
|
|
2004
5201
|
rows.push({
|
|
2005
5202
|
kind: "groupHeader",
|
|
2006
5203
|
cells: [textOfRuns(runs.filter((run) => run !== void 0))],
|
|
2007
5204
|
across: true,
|
|
2008
|
-
...rowStyle(lowering, group.headerStyle)
|
|
5205
|
+
...rowStyle(lowering, group.headerStyle),
|
|
5206
|
+
...keep > 1 ? { keepWithRows: keep } : {}
|
|
2009
5207
|
});
|
|
2010
5208
|
for (const row of each.rows) rows.push(detailRow(lowering, row));
|
|
2011
5209
|
rows.push(...footerRows(lowering, group.footer, `${path}/group/footer`, "groupFooter", scope));
|
|
@@ -2013,6 +5211,25 @@ function groupedRows(lowering, groups) {
|
|
|
2013
5211
|
return rows;
|
|
2014
5212
|
}
|
|
2015
5213
|
/**
|
|
5214
|
+
* The detail rows `table`'s condition, at `path`, selects, in the data's
|
|
5215
|
+
* order; undefined for a table without one, which has every row. A row
|
|
5216
|
+
* whose condition could not be read is left out and recorded as an error,
|
|
5217
|
+
* so the report is refused.
|
|
5218
|
+
*/
|
|
5219
|
+
function selectedRows(render, table, path) {
|
|
5220
|
+
if (table.rowsWhen === void 0) return void 0;
|
|
5221
|
+
const selected = [];
|
|
5222
|
+
for (const [index, record] of render.data.detail.entries()) {
|
|
5223
|
+
if (render.problems.full) break;
|
|
5224
|
+
const row = {
|
|
5225
|
+
index,
|
|
5226
|
+
record
|
|
5227
|
+
};
|
|
5228
|
+
if (holds(render, rowScope(render, render.totals.report, row), `${path}/rowsWhen/cel`) === true) selected.push(row);
|
|
5229
|
+
}
|
|
5230
|
+
return selected;
|
|
5231
|
+
}
|
|
5232
|
+
/**
|
|
2016
5233
|
* `table`, at `path`, as the document's table, `base` its own resolved
|
|
2017
5234
|
* style; undefined when every column is hidden. A value that could not be
|
|
2018
5235
|
* read prints nothing here, and is recorded as an error, so the report is
|
|
@@ -2025,22 +5242,24 @@ function tableBlock(render, table, path, base) {
|
|
|
2025
5242
|
index
|
|
2026
5243
|
})).filter(({ column, index }) => column.visibleWhen === void 0 || holds(render, scope, `${path}/columns/${index}/visibleWhen/cel`) === true);
|
|
2027
5244
|
if (shown.length === 0) return void 0;
|
|
5245
|
+
const selected = selectedRows(render, table, path);
|
|
5246
|
+
const totals = selected === void 0 ? render.totals.report : render.totals.over(selected);
|
|
2028
5247
|
const lowering = {
|
|
2029
5248
|
render,
|
|
2030
5249
|
table,
|
|
2031
5250
|
path,
|
|
2032
5251
|
shown,
|
|
2033
|
-
base
|
|
5252
|
+
base,
|
|
5253
|
+
totals
|
|
2034
5254
|
};
|
|
2035
|
-
const ordered = orderTable(render.report, table, render.data.detail);
|
|
5255
|
+
const ordered = orderTable(render.report, table, render.data.detail, selected);
|
|
2036
5256
|
const rows = [];
|
|
2037
5257
|
if (ordered.groups !== void 0) rows.push(...groupedRows(lowering, ordered.groups));
|
|
2038
5258
|
else for (const row of ordered.rows) {
|
|
2039
5259
|
if (render.problems.full) break;
|
|
2040
5260
|
rows.push(detailRow(lowering, row));
|
|
2041
5261
|
}
|
|
2042
|
-
rows.push(...footerRows(lowering, table.totals, `${path}/totals`, "total",
|
|
2043
|
-
const headerStyle = layered(base, table.headerStyle === void 0 ? void 0 : render.styles.get(table.headerStyle));
|
|
5262
|
+
rows.push(...footerRows(lowering, table.totals, `${path}/totals`, "total", tableScope(render, totals)));
|
|
2044
5263
|
return {
|
|
2045
5264
|
kind: "table",
|
|
2046
5265
|
id: table.id,
|
|
@@ -2048,14 +5267,29 @@ function tableBlock(render, table, path, base) {
|
|
|
2048
5267
|
width: column.width,
|
|
2049
5268
|
align: column.align
|
|
2050
5269
|
})),
|
|
2051
|
-
|
|
2052
|
-
...headerStyle === void 0 ? {} : { headerStyle },
|
|
5270
|
+
...headerOf(render, table, shown, base),
|
|
2053
5271
|
rows,
|
|
2054
5272
|
emptyText: table.emptyText
|
|
2055
5273
|
};
|
|
2056
5274
|
}
|
|
2057
|
-
|
|
2058
|
-
|
|
5275
|
+
/**
|
|
5276
|
+
* The header row of the `shown` columns and its style, or neither where no
|
|
5277
|
+
* title prints (0078): white space prints nothing, read as every engine
|
|
5278
|
+
* reads a cell, by `trim`. A title is a literal, never a value, and a word
|
|
5279
|
+
* of no letter is never translated (report-spec's `not-a-word`) nor one
|
|
5280
|
+
* translated to white space (`blank-translation`), so a table has a header
|
|
5281
|
+
* in every language it is written in, or in none.
|
|
5282
|
+
*/
|
|
5283
|
+
function headerOf(render, table, shown, base) {
|
|
5284
|
+
const header = shown.map(({ column }) => column.header);
|
|
5285
|
+
if (header.every((title) => title.trim() === "")) return {};
|
|
5286
|
+
const headerStyle = layered(base, table.headerStyle === void 0 ? void 0 : render.styles.get(table.headerStyle));
|
|
5287
|
+
return {
|
|
5288
|
+
header,
|
|
5289
|
+
...headerStyle === void 0 ? {} : { headerStyle }
|
|
5290
|
+
};
|
|
5291
|
+
}
|
|
5292
|
+
// src/lower.ts
|
|
2059
5293
|
/** `value` under `key` when it is defined: the document writes only what is set. */
|
|
2060
5294
|
const optional = (key, value) => value === void 0 ? {} : { [key]: value };
|
|
2061
5295
|
const LOWER = {
|
|
@@ -2068,6 +5302,17 @@ const LOWER = {
|
|
|
2068
5302
|
};
|
|
2069
5303
|
},
|
|
2070
5304
|
image: (image, { render, path }) => imageBlock(render, image, path),
|
|
5305
|
+
qrCode: (code, { render, scope, path }) => {
|
|
5306
|
+
const text = encodedText(render, scope, code.content, path, code.id);
|
|
5307
|
+
return text === void 0 ? void 0 : {
|
|
5308
|
+
kind: "qrCode",
|
|
5309
|
+
id: code.id,
|
|
5310
|
+
text,
|
|
5311
|
+
size: code.size,
|
|
5312
|
+
errorCorrection: code.errorCorrection
|
|
5313
|
+
};
|
|
5314
|
+
},
|
|
5315
|
+
epcQrCode: (code, { render, scope, path }) => epcQrCodeBlock(render, scope, code, path),
|
|
2071
5316
|
line: (line) => ({
|
|
2072
5317
|
kind: "rule",
|
|
2073
5318
|
thickness: line.thickness,
|
|
@@ -2099,6 +5344,7 @@ const LOWER = {
|
|
|
2099
5344
|
...optional("padding", section.padding)
|
|
2100
5345
|
}),
|
|
2101
5346
|
table: (table, { render, path, style }) => tableBlock(render, table, path, style),
|
|
5347
|
+
chart: (chart, { render, path, style }) => chartBlock(render, chart, path, style),
|
|
2102
5348
|
pageBreak: () => ({ kind: "pageBreak" }),
|
|
2103
5349
|
keepTogether: (kept, { render, path, style }) => ({
|
|
2104
5350
|
kind: "keepTogether",
|
|
@@ -2121,12 +5367,15 @@ function blockOf(render, component, path, inherited) {
|
|
|
2121
5367
|
function blocksOf(render, components, path, inherited) {
|
|
2122
5368
|
return components.flatMap((component, index) => blockOf(render, component, `${path}/${index}`, inherited) ?? []);
|
|
2123
5369
|
}
|
|
5370
|
+
/** A region every report holds, lowered. */
|
|
2124
5371
|
function region(render, name) {
|
|
2125
5372
|
return blocksOf(render, render.report.regions[name], `/regions/${name}`, void 0);
|
|
2126
5373
|
}
|
|
2127
5374
|
/** Every region of `render`'s report, lowered: the report header, body and summary as the one body. */
|
|
2128
5375
|
function lowerRegions(render) {
|
|
5376
|
+
const own = render.report.regions.firstPageHeader;
|
|
2129
5377
|
return {
|
|
5378
|
+
...own === void 0 ? {} : { firstPageHeader: blocksOf(render, own, "/regions/firstPageHeader", void 0) },
|
|
2130
5379
|
pageHeader: region(render, "pageHeader"),
|
|
2131
5380
|
pageFooter: region(render, "pageFooter"),
|
|
2132
5381
|
body: [
|
|
@@ -2136,20 +5385,27 @@ function lowerRegions(render) {
|
|
|
2136
5385
|
]
|
|
2137
5386
|
};
|
|
2138
5387
|
}
|
|
2139
|
-
|
|
2140
|
-
//#region src/report-check.ts
|
|
5388
|
+
// src/report-check.ts
|
|
2141
5389
|
/**
|
|
2142
|
-
* `report` validated and its expressions compiled for one render
|
|
2143
|
-
*
|
|
2144
|
-
*
|
|
5390
|
+
* `report` validated and its expressions compiled for one render in
|
|
5391
|
+
* `locale`, the report's own where absent, or every reason it is refused:
|
|
5392
|
+
* each structural error; a locale the report is not written in
|
|
5393
|
+
* (`undeclared-locale`); or, for a report that is structurally valid,
|
|
5394
|
+
* each diagnostic of severity error that names no language or that
|
|
5395
|
+
* locale (0063).
|
|
2145
5396
|
*/
|
|
2146
|
-
function checkReport(report) {
|
|
5397
|
+
function checkReport(report, locale) {
|
|
2147
5398
|
const validation = validateReport(report);
|
|
2148
5399
|
if (!validation.valid) return {
|
|
2149
5400
|
ok: false,
|
|
2150
5401
|
errors: validation.errors.map(fromReport)
|
|
2151
5402
|
};
|
|
2152
|
-
const
|
|
5403
|
+
const chosen = printLocale(validation.report, locale);
|
|
5404
|
+
if (!chosen.ok) return {
|
|
5405
|
+
ok: false,
|
|
5406
|
+
errors: [chosen.error]
|
|
5407
|
+
};
|
|
5408
|
+
const prepared = prepareExpressions(validation.report, chosen.locale);
|
|
2153
5409
|
if (!prepared.ok) return {
|
|
2154
5410
|
ok: false,
|
|
2155
5411
|
errors: prepared.diagnostics.map(fromDiagnostic)
|
|
@@ -2157,184 +5413,11 @@ function checkReport(report) {
|
|
|
2157
5413
|
return {
|
|
2158
5414
|
ok: true,
|
|
2159
5415
|
report: validation.report,
|
|
5416
|
+
printed: prepared.report,
|
|
2160
5417
|
expressions: prepared.expressions
|
|
2161
5418
|
};
|
|
2162
5419
|
}
|
|
2163
|
-
|
|
2164
|
-
//#region src/totals.ts
|
|
2165
|
-
/**
|
|
2166
|
-
* The report's aggregates, computed exactly, once, here (0007): over every
|
|
2167
|
-
* detail row for `totals`, and over a group's rows for `group`.
|
|
2168
|
-
*
|
|
2169
|
-
* - **In report-core's order.** An aggregate's expression may read another
|
|
2170
|
-
* aggregate's total, so each is computed after every one it reads, in the
|
|
2171
|
-
* order `compileReport` gives (0009); an aggregate that could never be
|
|
2172
|
-
* computed has already refused the report.
|
|
2173
|
-
* - **Each row read once.** What an aggregate reads from a row is read once
|
|
2174
|
-
* per render, with the report's totals, and kept by the row's index; a
|
|
2175
|
-
* group's aggregate is the same function over its rows' values. So a
|
|
2176
|
-
* group's subtotal and the report's total are totals of the same values,
|
|
2177
|
-
* and the subtotals of a sum that declares no rounding add up to the
|
|
2178
|
-
* total. A declared rounding is applied to each group's exact sum and to
|
|
2179
|
-
* the report's, once each, so rounded subtotals need not add up to the
|
|
2180
|
-
* rounded total: two groups of 0.02, rounded to 0.05, print 0.00 and 0.00
|
|
2181
|
-
* over 0.05.
|
|
2182
|
-
* - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,
|
|
2183
|
-
* through `decimal.ts`; nothing passes through a JavaScript number. A
|
|
2184
|
-
* total report-core compiled as a decimal is a decimal, its 0 too, and so
|
|
2185
|
-
* is one whose kind the compiler could not tell (`dyn`) once it declares a
|
|
2186
|
-
* rounding or meets a decimal; a group's total is of the report total's
|
|
2187
|
-
* kind, so an expression reading `group.<id>` meets one type.
|
|
2188
|
-
* - **Nulls are skipped**, and so is a value a preview's data lacks. Over no
|
|
2189
|
-
* values a count and a sum are 0 and the rest null (0007).
|
|
2190
|
-
* - **Declared rounding is applied once**, to the exact result: an average
|
|
2191
|
-
* always declares one, and a sum, a minimum or a maximum of decimals may.
|
|
2192
|
-
* A rounding on a total that is an integer or a moment is refused, never
|
|
2193
|
-
* ignored.
|
|
2194
|
-
*/
|
|
2195
|
-
const isRefusal = (value) => value !== null && "code" in value;
|
|
2196
|
-
const integer = (value) => ({
|
|
2197
|
-
type: "integer",
|
|
2198
|
-
value
|
|
2199
|
-
});
|
|
2200
|
-
const decimal = (value) => ({
|
|
2201
|
-
type: "decimal",
|
|
2202
|
-
value
|
|
2203
|
-
});
|
|
2204
|
-
const asDecimal = (value) => value.type === "integer" ? new Decimal(value.value, 0) : value.value;
|
|
2205
|
-
/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */
|
|
2206
|
-
function numbers(values, decimals) {
|
|
2207
|
-
if (!decimals && values.every((value) => value.type === "integer")) return { integers: values.map((value) => value.value) };
|
|
2208
|
-
if (!values.every((value) => value.type === "integer" || value.type === "decimal")) return void 0;
|
|
2209
|
-
return { decimals: values.map(asDecimal) };
|
|
2210
|
-
}
|
|
2211
|
-
const NOT_NUMBERS = {
|
|
2212
|
-
code: "aggregate-value-type",
|
|
2213
|
-
message: "totals integers and decimals, and a value it read is neither"
|
|
2214
|
-
};
|
|
2215
|
-
function sum(values, decimals) {
|
|
2216
|
-
const read = numbers(values, decimals);
|
|
2217
|
-
if (read === void 0) return NOT_NUMBERS;
|
|
2218
|
-
return "integers" in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals));
|
|
2219
|
-
}
|
|
2220
|
-
function average(values, rounding) {
|
|
2221
|
-
const read = numbers(values, true);
|
|
2222
|
-
if (read === void 0) return NOT_NUMBERS;
|
|
2223
|
-
const result = averageDecimals(read.decimals, rounding);
|
|
2224
|
-
return result === null ? null : decimal(result);
|
|
2225
|
-
}
|
|
2226
|
-
const ordered = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2227
|
-
/** -1, 0 or 1 for two values of one kind: numbers by value, text as the report's language sorts it, dates as days, moments in time order. */
|
|
2228
|
-
function comparator(values, collator) {
|
|
2229
|
-
const types = new Set(values.map(({ type }) => type));
|
|
2230
|
-
if ([...types].every((type) => type === "integer" || type === "decimal")) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b));
|
|
2231
|
-
const only = types.size === 1 ? [...types][0] : void 0;
|
|
2232
|
-
if (only === "string") return (a, b) => collator.compare(a.value, b.value);
|
|
2233
|
-
if (only === "date") return (a, b) => ordered(a.value, b.value);
|
|
2234
|
-
if (only === "datetime" || only === "instant") return (a, b) => ordered(fixedWidth(a.value), fixedWidth(b.value));
|
|
2235
|
-
}
|
|
2236
|
-
/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */
|
|
2237
|
-
function extreme(values, sign, totalling) {
|
|
2238
|
-
const compare = comparator(values, totalling.collator);
|
|
2239
|
-
if (compare === void 0) return {
|
|
2240
|
-
code: "aggregate-value-type",
|
|
2241
|
-
message: "takes the least or greatest of values of one kind, and the values it read are of several"
|
|
2242
|
-
};
|
|
2243
|
-
const found = values.reduce((kept, value) => kept === null || Math.sign(compare(value, kept)) === sign ? value : kept, null);
|
|
2244
|
-
return found?.type === "integer" && totalling.decimals ? decimal(asDecimal(found)) : found;
|
|
2245
|
-
}
|
|
2246
|
-
/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */
|
|
2247
|
-
function rounded(total, rounding) {
|
|
2248
|
-
if (rounding === void 0 || total === null || isRefusal(total)) return total;
|
|
2249
|
-
if (total.type === "decimal") return decimal(roundDecimalAs(total.value, rounding));
|
|
2250
|
-
return {
|
|
2251
|
-
code: "rounding-not-decimal",
|
|
2252
|
-
message: `declares a rounding, and its total is ${total.type === "integer" ? "an integer" : `a ${total.type}`}, which has no places to round`
|
|
2253
|
-
};
|
|
2254
|
-
}
|
|
2255
|
-
/** The aggregate over the values read from some rows -- each null or typed -- or over `rows` rows when it reads nothing. */
|
|
2256
|
-
function reduce(totalling, read, rows) {
|
|
2257
|
-
const { aggregate, decimals } = totalling;
|
|
2258
|
-
const values = (read ?? []).filter((value) => value !== null);
|
|
2259
|
-
switch (aggregate.fn) {
|
|
2260
|
-
case "count": return integer(BigInt(read === void 0 ? rows : values.length));
|
|
2261
|
-
case "avg": return values.length === 0 ? null : average(values, aggregate.rounding);
|
|
2262
|
-
case "sum": return rounded(sum(values, decimals), aggregate.rounding);
|
|
2263
|
-
case "min": return rounded(extreme(values, -1, totalling), aggregate.rounding);
|
|
2264
|
-
case "max": return rounded(extreme(values, 1, totalling), aggregate.rounding);
|
|
2265
|
-
}
|
|
2266
|
-
}
|
|
2267
|
-
/**
|
|
2268
|
-
* Every aggregate of `render`'s report, over its detail rows and, through
|
|
2269
|
-
* `over`, over any of them; or undefined when one could not be computed,
|
|
2270
|
-
* each reason recorded. `render` has every input but the totals.
|
|
2271
|
-
*/
|
|
2272
|
-
function computeTotals(render) {
|
|
2273
|
-
const { report, expressions, data, problems } = render;
|
|
2274
|
-
const collator = new Intl.Collator(report.locale, { usage: "sort" });
|
|
2275
|
-
const rows = data.detail.map((record, index) => ({
|
|
2276
|
-
index,
|
|
2277
|
-
record
|
|
2278
|
-
}));
|
|
2279
|
-
const read = /* @__PURE__ */ new Map();
|
|
2280
|
-
const totals = /* @__PURE__ */ new Map();
|
|
2281
|
-
const totallings = /* @__PURE__ */ new Map();
|
|
2282
|
-
const refuse = (index, refusal) => {
|
|
2283
|
-
problems.error({
|
|
2284
|
-
stage: "resolve",
|
|
2285
|
-
code: refusal.code,
|
|
2286
|
-
path: `/aggregates/${index}`,
|
|
2287
|
-
message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}`
|
|
2288
|
-
});
|
|
2289
|
-
};
|
|
2290
|
-
let computed = true;
|
|
2291
|
-
for (const id of expressions.compilation.aggregateOrder) {
|
|
2292
|
-
const index = report.aggregates.findIndex((aggregate) => aggregate.id === id);
|
|
2293
|
-
const aggregate = report.aggregates[index];
|
|
2294
|
-
const compiled = expressions.compilation.members.totals.get(id)?.type;
|
|
2295
|
-
const decimals = compiled === "decimal" || compiled === "dyn" && aggregate.rounding !== void 0;
|
|
2296
|
-
const of = aggregate.of;
|
|
2297
|
-
if (of !== void 0) {
|
|
2298
|
-
const path = `/aggregates/${index}/of/expression/cel`;
|
|
2299
|
-
const values = rows.map((row) => of.kind === "field" ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path));
|
|
2300
|
-
if (values.some((value) => value === void 0)) {
|
|
2301
|
-
computed = false;
|
|
2302
|
-
continue;
|
|
2303
|
-
}
|
|
2304
|
-
read.set(id, values);
|
|
2305
|
-
}
|
|
2306
|
-
const totalling = {
|
|
2307
|
-
aggregate,
|
|
2308
|
-
decimals,
|
|
2309
|
-
collator
|
|
2310
|
-
};
|
|
2311
|
-
const total = reduce(totalling, read.get(id), rows.length);
|
|
2312
|
-
if (isRefusal(total)) {
|
|
2313
|
-
computed = false;
|
|
2314
|
-
refuse(index, total);
|
|
2315
|
-
continue;
|
|
2316
|
-
}
|
|
2317
|
-
totals.set(id, total);
|
|
2318
|
-
totallings.set(id, total?.type === "decimal" ? {
|
|
2319
|
-
...totalling,
|
|
2320
|
-
decimals: true
|
|
2321
|
-
} : totalling);
|
|
2322
|
-
}
|
|
2323
|
-
if (!computed) return void 0;
|
|
2324
|
-
return {
|
|
2325
|
-
report: totals,
|
|
2326
|
-
over(group) {
|
|
2327
|
-
const values = /* @__PURE__ */ new Map();
|
|
2328
|
-
for (const aggregate of report.aggregates) {
|
|
2329
|
-
const each = read.get(aggregate.id);
|
|
2330
|
-
values.set(aggregate.id, reduce(totallings.get(aggregate.id), each && group.map((row) => each[row.index]), group.length));
|
|
2331
|
-
}
|
|
2332
|
-
return values;
|
|
2333
|
-
}
|
|
2334
|
-
};
|
|
2335
|
-
}
|
|
2336
|
-
//#endregion
|
|
2337
|
-
//#region src/resolve.ts
|
|
5420
|
+
// src/resolve.ts
|
|
2338
5421
|
/**
|
|
2339
5422
|
* A report resolved against its data: the renderer-neutral document it
|
|
2340
5423
|
* prints, and the manifest that says what it was printed from (plan 14).
|
|
@@ -2343,31 +5426,76 @@ function computeTotals(render) {
|
|
|
2343
5426
|
*
|
|
2344
5427
|
* 1. the report, validated again and its expressions compiled; one the
|
|
2345
5428
|
* editor's diagnostics give an error for is refused (`report-check.ts`);
|
|
5429
|
+
* then written in the locale the render names, its own or one its
|
|
5430
|
+
* translations declare, which every later stage reads (`languages.ts`,
|
|
5431
|
+
* 0063);
|
|
2346
5432
|
* 2. the options, the parameters and the data, each checked, and every
|
|
2347
5433
|
* error of the three listed together (`parameters.ts`, `data.ts`);
|
|
2348
5434
|
* 3. the aggregates, exactly, over every row (`totals.ts`);
|
|
2349
|
-
* 4. the
|
|
5435
|
+
* 4. the e-invoice's lines, read once, and its totals and its terms, where
|
|
5436
|
+
* the report is one (`lower-e-invoice.ts`);
|
|
5437
|
+
* 5. the regions, lowered component by component (`lower.ts`), tables row
|
|
2350
5438
|
* by row (`lower-table.ts`), images through the host's lookup
|
|
2351
|
-
* (`images.ts`)
|
|
5439
|
+
* (`images.ts`), an EPC QR code's every text held to the EPC's rules
|
|
5440
|
+
* (`lower-epc-qr-code.ts`);
|
|
5441
|
+
* 6. the payment part, its every text held to SIX's rules
|
|
5442
|
+
* (`lower-payment-part.ts`);
|
|
5443
|
+
* 7. the e-invoice's XML, in a final render (`cii.ts`).
|
|
2352
5444
|
*
|
|
2353
5445
|
* It refuses rather than prints a wrong report: any error at any stage, and
|
|
2354
5446
|
* the result is the errors, never a partial document. A preview may run on
|
|
2355
5447
|
* data the provider calls incomplete or that lacks a field; it says so in
|
|
2356
5448
|
* the manifest and in its warnings, and its every page carries
|
|
2357
5449
|
* `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for
|
|
2358
|
-
* the report. A final render refuses such data.
|
|
5450
|
+
* the report. A final render refuses such data. A preview of an e-invoice
|
|
5451
|
+
* writes no XML, and is labelled whatever its data:
|
|
5452
|
+
* `E_INVOICE_PREVIEW_LABEL` where nothing else is lacking. A final render
|
|
5453
|
+
* of an XRechnung is labelled too, `XRECHNUNG_COPY_LABEL`: its XML is the
|
|
5454
|
+
* invoice, and its PDF a copy (0038). And a final render of an e-invoice
|
|
5455
|
+
* of either kind that a host asks for as the copy (`eInvoice: 'copy'`,
|
|
5456
|
+
* 0077) is labelled as one in the render's language and carries no XML
|
|
5457
|
+
* (`e-invoice-copy.ts`): what a Word file is written of.
|
|
2359
5458
|
*/
|
|
2360
|
-
/** What every page of a preview that lacks data says, at the top of its page header. */
|
|
5459
|
+
/** What every page of a preview that lacks data says, at the top of its page header, and of page 1's own where it has one. */
|
|
2361
5460
|
const PREVIEW_LABEL = "Preview of incomplete data: not a final report";
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
5461
|
+
/** What every page of a preview of an e-invoice says when it lacks nothing else: it writes no XML, and is not the invoice. */
|
|
5462
|
+
const E_INVOICE_PREVIEW_LABEL = "Preview: not an e-invoice, and not a final report";
|
|
5463
|
+
/** What every page of a final render of an XRechnung says: the invoice is the XML the document carries, which a host sends, and the PDF drawn of the page is a copy (0038). */
|
|
5464
|
+
const XRECHNUNG_COPY_LABEL = "Copy of an XRechnung: the invoice is its XML, and this PDF is not the invoice";
|
|
5465
|
+
/**
|
|
5466
|
+
* The paragraph that opens every page's header of a final render of an
|
|
5467
|
+
* XRechnung, as the runtime writes it: `XRECHNUNG_COPY_LABEL` in the
|
|
5468
|
+
* labels' style. The renderer refuses an XRechnung's document whose page
|
|
5469
|
+
* header, or page 1's own where it has one (0060), does not open with it,
|
|
5470
|
+
* style and all, since the text in white or at one point would say nothing
|
|
5471
|
+
* to a reader (0038). Frozen, so that what
|
|
5472
|
+
* the renderer holds a copy to is not a host's to change; each document
|
|
5473
|
+
* carries a paragraph of its own.
|
|
5474
|
+
*/
|
|
5475
|
+
const XRECHNUNG_COPY_PARAGRAPH = frozen(label(XRECHNUNG_COPY_LABEL));
|
|
5476
|
+
/**
|
|
5477
|
+
* The label a copy of `report`'s e-invoice is headed with where `options`
|
|
5478
|
+
* ask for one (0077), `locale` the one the render prints in: its text,
|
|
5479
|
+
* undefined where no copy is asked for or the report carries no
|
|
5480
|
+
* e-invoice, or the error that refuses the copy. The option is the
|
|
5481
|
+
* host's, whatever its type says.
|
|
5482
|
+
*/
|
|
5483
|
+
function copyLabel(report, own, locale, options) {
|
|
5484
|
+
const asked = options.eInvoice;
|
|
5485
|
+
if (asked === void 0) return void 0;
|
|
5486
|
+
const no = (path, message) => ({
|
|
5487
|
+
stage: "resolve",
|
|
5488
|
+
code: "no-e-invoice-copy",
|
|
5489
|
+
path,
|
|
5490
|
+
message
|
|
5491
|
+
});
|
|
5492
|
+
if (asked !== "copy") return no("", "a render's eInvoice option is 'copy' or absent");
|
|
5493
|
+
if (report.eInvoice === void 0) return void 0;
|
|
5494
|
+
if (options.mode === "preview") return no("", "a copy is of a final render of an e-invoice; a preview writes no XML, and there is no invoice it is a copy of");
|
|
5495
|
+
const [run] = eInvoiceCopyParagraph(report.eInvoice.kind, locale)?.runs ?? [];
|
|
5496
|
+
if (run === void 0 || !("text" in run)) return no(localePath(own, locale), `a copy of an e-invoice is labelled in the language it prints in, and the runtime has no label in the language of ${locale}: it has one in ${E_INVOICE_COPY_LANGUAGES.join(", ")}`);
|
|
5497
|
+
return run.text;
|
|
5498
|
+
}
|
|
2371
5499
|
/** Each parameter's value as the format writes one. */
|
|
2372
5500
|
function writtenParameters(values) {
|
|
2373
5501
|
return Object.fromEntries(Object.entries(values).map(([id, value]) => {
|
|
@@ -2383,12 +5511,12 @@ function writtenParameters(values) {
|
|
|
2383
5511
|
* nothing in the result is shared with them.
|
|
2384
5512
|
*/
|
|
2385
5513
|
function resolveReport(report, data, options) {
|
|
2386
|
-
const checked = checkReport(report);
|
|
5514
|
+
const checked = checkReport(report, options.locale);
|
|
2387
5515
|
if (!checked.ok) return {
|
|
2388
5516
|
ok: false,
|
|
2389
5517
|
errors: checked.errors
|
|
2390
5518
|
};
|
|
2391
|
-
const valid = checked.
|
|
5519
|
+
const valid = checked.printed;
|
|
2392
5520
|
const timeZone = options.timeZone ?? "UTC";
|
|
2393
5521
|
const errors = [];
|
|
2394
5522
|
const creationDate = canonicalInstant(String(options.creationDate));
|
|
@@ -2405,13 +5533,18 @@ function resolveReport(report, data, options) {
|
|
|
2405
5533
|
if (!formatter.ok) errors.push({
|
|
2406
5534
|
stage: "format",
|
|
2407
5535
|
code: formatter.code,
|
|
2408
|
-
path: formatter.code === "unsupported-locale" ?
|
|
5536
|
+
path: formatter.code === "unsupported-locale" ? localePath(checked.report, valid.locale) : "",
|
|
2409
5537
|
message: formatter.message
|
|
2410
5538
|
});
|
|
2411
5539
|
const parameters = checkParameters(valid, options.parameters ?? {});
|
|
2412
5540
|
if (!parameters.ok) errors.push(...parameters.errors.map((error) => fromData("parameters", error)));
|
|
2413
|
-
const checkedData = checkData(valid, data, {
|
|
5541
|
+
const checkedData = checkData(valid, data, {
|
|
5542
|
+
mode: options.mode,
|
|
5543
|
+
reportLocale: checked.report.locale
|
|
5544
|
+
});
|
|
2414
5545
|
if (!checkedData.ok) errors.push(...checkedData.errors.map((error) => fromData("data", error)));
|
|
5546
|
+
const copy = copyLabel(valid, checked.report, valid.locale, options);
|
|
5547
|
+
if (typeof copy === "object") errors.push(copy);
|
|
2415
5548
|
if (errors.length > 0 || creationDate === void 0 || !formatter.ok || !parameters.ok || !checkedData.ok) return {
|
|
2416
5549
|
ok: false,
|
|
2417
5550
|
errors
|
|
@@ -2435,17 +5568,32 @@ function resolveReport(report, data, options) {
|
|
|
2435
5568
|
ok: false,
|
|
2436
5569
|
errors: problems.errors()
|
|
2437
5570
|
};
|
|
2438
|
-
const
|
|
5571
|
+
const invoice = valid.eInvoice === void 0 ? void 0 : resolveEInvoice({
|
|
2439
5572
|
...inputs,
|
|
2440
5573
|
totals
|
|
2441
|
-
});
|
|
5574
|
+
}, valid.eInvoice);
|
|
5575
|
+
if (valid.eInvoice !== void 0 && invoice === void 0) return {
|
|
5576
|
+
ok: false,
|
|
5577
|
+
errors: problems.errors()
|
|
5578
|
+
};
|
|
5579
|
+
const render = {
|
|
5580
|
+
...inputs,
|
|
5581
|
+
totals,
|
|
5582
|
+
...invoice === void 0 ? {} : { invoice: invoice.reads }
|
|
5583
|
+
};
|
|
5584
|
+
const regions = lowerRegions(render);
|
|
5585
|
+
const paymentPart = lowerPaymentPart(render);
|
|
5586
|
+
const fonts = resolveFonts(render, valid.fonts);
|
|
5587
|
+
const eInvoice = invoice === void 0 || valid.eInvoice === void 0 ? void 0 : eInvoiceFile(render, invoice, valid.eInvoice);
|
|
2442
5588
|
if (problems.failed) return {
|
|
2443
5589
|
ok: false,
|
|
2444
5590
|
errors: problems.errors()
|
|
2445
5591
|
};
|
|
2446
|
-
const { completeness, consistency } = checkedData.data;
|
|
5592
|
+
const { completeness, consistency, source } = checkedData.data;
|
|
2447
5593
|
const warnings = problems.warnings();
|
|
2448
|
-
const
|
|
5594
|
+
const lacking = !completeness.complete || warnings.some(({ code }) => code !== "e-invoice-preview");
|
|
5595
|
+
const labelled = !preview ? typeof copy === "string" ? copy : eInvoice?.kind === "xrechnung" ? XRECHNUNG_COPY_LABEL : void 0 : lacking ? PREVIEW_LABEL : invoice === void 0 ? void 0 : E_INVOICE_PREVIEW_LABEL;
|
|
5596
|
+
const headed = (blocks) => labelled === void 0 ? blocks : [label(labelled), ...blocks];
|
|
2449
5597
|
return {
|
|
2450
5598
|
ok: true,
|
|
2451
5599
|
document: {
|
|
@@ -2454,24 +5602,29 @@ function resolveReport(report, data, options) {
|
|
|
2454
5602
|
creationDate
|
|
2455
5603
|
},
|
|
2456
5604
|
page: valid.page,
|
|
2457
|
-
|
|
5605
|
+
...regions.firstPageHeader === void 0 ? {} : { firstPageHeader: headed(regions.firstPageHeader) },
|
|
5606
|
+
pageHeader: headed(regions.pageHeader),
|
|
2458
5607
|
pageFooter: regions.pageFooter,
|
|
2459
|
-
body: regions.body
|
|
5608
|
+
body: regions.body,
|
|
5609
|
+
...paymentPart === void 0 ? {} : { paymentPart },
|
|
5610
|
+
...eInvoice === void 0 || typeof copy === "string" ? {} : { eInvoice },
|
|
5611
|
+
...fonts === void 0 ? {} : { fonts }
|
|
2460
5612
|
},
|
|
2461
5613
|
manifest: {
|
|
2462
|
-
reportHash: reportHash(
|
|
5614
|
+
reportHash: reportHash(checked.report),
|
|
2463
5615
|
reportSpecVersion: valid.reportSpecVersion,
|
|
2464
5616
|
locale: valid.locale,
|
|
2465
5617
|
timeZone,
|
|
2466
5618
|
mode: checkedData.data.mode,
|
|
2467
5619
|
consistency,
|
|
2468
5620
|
completeness,
|
|
2469
|
-
parameters: writtenParameters(parameters.values)
|
|
5621
|
+
parameters: writtenParameters(parameters.values),
|
|
5622
|
+
...source === void 0 ? {} : { source },
|
|
5623
|
+
...typeof copy === "string" ? { eInvoice: "copy" } : {}
|
|
2470
5624
|
},
|
|
2471
5625
|
warnings
|
|
2472
5626
|
};
|
|
2473
5627
|
}
|
|
2474
|
-
|
|
2475
|
-
export { CAPABILITIES, CONSISTENCY_MODES, DATA_ERROR_CODES, DATA_MODES, EVALUATION_ERROR_CODES, EXPRESSION_STEP_BUDGET, FORMAT_ERROR_CODES, MAX_ASSET_BYTES, MAX_DATA_ERRORS, MAX_DETAIL_ROWS, MAX_FORMATTED_DIGITS, MAX_STRING_LENGTH, PREVIEW_LABEL, REFUSAL_CODES, RENDER_STEP_BUDGET, RESOLVE_ERROR_CODES, RenderRefusal, VALUE_ERROR_CODES, averageDecimals, checkData, checkParameters, checkReport, createFormatter, groupRows, maxDecimal, minDecimal, orderKeys, orderRows, orderTable, plainText, prepareExpressions, readValue, resolveReport, roundDecimalAs, sumDecimals, supportedLocale };
|
|
5628
|
+
export { BASELINE_SHIFTS, BIDI_CONTROLS, BILL_HEADING_FACES, CAPABILITIES, CONSISTENCY_MODES, DATA_ERROR_CODES, DATA_MODES, EPC_CAPTION, EPC_CAPTION_MODULE, EPC_FRAME, EPC_MAX_BYTES, EPC_MAX_VERSION, EVALUATION_ERROR_CODES, EXPRESSION_STEP_BUDGET, E_INVOICE_COPY_LABELS, E_INVOICE_COPY_LANGUAGES, E_INVOICE_PREVIEW_LABEL, FACTUR_X, FACTUR_X_PROFILES, FONT_EMBEDDING_REFUSALS, FONT_FACE_KEYS, FONT_FORMATS, FONT_MEDIA_TYPES, FONT_REFUSAL_CODES, FORMAT_ERROR_CODES, IMAGE_REFUSAL_CODES, MAX_ASSET_BYTES, MAX_ASSET_SIDE, MAX_CHART_CATEGORIES, MAX_CHART_SERIES, MAX_DATA_ERRORS, MAX_DETAIL_ROWS, MAX_FONT_BYTES, MAX_FONT_CHARACTERS, MAX_FONT_LINE, MAX_FONT_SIZE, MAX_FORMATTED_DIGITS, MAX_KEEP_WITH_ROWS, MAX_QR_BILL_ADDITIONAL_INFORMATION, MAX_SCALE, MAX_STRING_LENGTH, MAX_SVG_BYTES, MAX_SVG_COORDINATE, MAX_SVG_DEPTH, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS, MAX_TICK_INTERVALS, MIN_FONT_LINE, MIN_FONT_SIZE, PREVIEW_LABEL, PRINTED_BLOCKS, QR_BILL_CURRENCIES, QR_BILL_SIZE, QR_BILL_TOP, QR_MAX_CHARACTERS, QR_MIN_MODULE, QR_QUIET_ZONE, REFUSAL_CODES, RENDER_STEP_BUDGET, RESOLVE_ERROR_CODES, RenderRefusal, SHARE_PLACES, SHIFTED_RISE, SHIFTED_SIZE, SLIP_ACCEPTANCE, SLIP_CODE, SLIP_CORNER, SLIP_FIELD_GAP, SLIP_INSTRUCTION, SLIP_PAYMENT_PART, SLIP_RECEIPT, SLIP_RECEIPT_WIDTH, SLIP_SEPARATION, SLIP_TITLE, SOURCE_PROVIDERS, SUBMISSION_ID_SYNTAX, SVG_ELEMENTS, SVG_REFUSAL_CODES, SWISS_CODE_SIZE, SWISS_CROSS, SWISS_QR_MAX_CHARACTERS, UNICODE_VERSION, VALUE_ERROR_CODES, XRECHNUNG, XRECHNUNG_COPY_LABEL, XRECHNUNG_COPY_PARAGRAPH, XRECHNUNG_VERSIONS, assetDigest, averageDecimals, characterMap, checkData, checkParameters, checkQrBill, checkQrBillAmount, checkReport, checkSvg, cleanSvg, createFormatter, eInvoiceCopyParagraph, epcCaptionBreak, epcLeastVersion, epcModule, epcSymbol, faceKey, groupRows, imageHeader, isFontMediaType, isSubmissionId, maxDecimal, minDecimal, orderKeys, orderRows, orderTable, plainText, prepareExpressions, qrBillPageBreak, qrSymbol, qrSymbolModules, qrSymbolVersion, readCopyLabel, readFont, readValue, refuseBillPage, refusedCharacter, resolveReport, roundDecimalAs, slipBlocks, sniffImage, sumDecimals, supportedLocale, swissSymbol };
|
|
2476
5629
|
|
|
2477
5630
|
//# sourceMappingURL=index.mjs.map
|