@formancy/report-runtime 0.1.0 → 0.2.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/dist/index.mjs CHANGED
@@ -1,14 +1,7 @@
1
- import { ASSET_MEDIA_TYPES, MAX_ERRORS, MAX_KEY_LENGTH, MAX_SCALE, isIdentifier, reportHash, validateReport } from "@formancy/report-spec";
2
- import { DEFAULT_BUDGET, DEFAULT_VALUE_LIMITS, Decimal, addDecimal, compareDecimal, decimalFromString, decimalToString, evaluate, fixedCapabilities } from "@formancy/expressions";
1
+ import { ASSET_MEDIA_TYPES, EPC_CAPTION, EPC_CAPTION_MODULE, EPC_FRAME, EPC_MAX_BYTES, EPC_MAX_VERSION, EPC_TEXT_FIELDS, E_INVOICE_DATES, E_INVOICE_DECIMALS, 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, IMAGE_REFUSAL_CODES, MAX_ASSET_BYTES, MAX_ASSET_BYTES as MAX_ASSET_BYTES$1, MAX_ASSET_SIDE, MAX_ERRORS, MAX_KEY_LENGTH, MAX_QR_BILL_ADDITIONAL_INFORMATION, MAX_SCALE, MAX_SVG_BYTES, MAX_SVG_BYTES as MAX_SVG_BYTES$1, MAX_SVG_COORDINATE, MAX_SVG_DEPTH, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS, QR_BILL_ADDRESS_RULES, QR_BILL_BILLING_RULE, QR_BILL_CURRENCIES, QR_BILL_MESSAGE_RULE, QR_BILL_SIZE, QR_BILL_TOP, SVG_ELEMENTS, SVG_REFUSAL_CODES, buyerIdentificationBreak, checkEInvoiceDate, checkEInvoiceDecimal, checkEInvoiceText, checkEpcAmount, checkEpcField, checkEpcPayload, checkInvoicingPeriod, checkLineCategory, checkQrBillAccount, checkQrBillAdditionalInformation, checkQrBillAmount, checkQrBillAmount as checkQrBillAmount$1, checkQrBillReference, checkQrBillText, checkSvg, checkVatRate, cleanSvg, eInvoiceBlank, en16931Rule, epcBlank, epcCaptionBreak, epcLeastVersion, epcModule, epcPairing, epcPayload, imageHeader, isIdentifier, qrBillPageBreak, qrBillPairing, qrSymbolModules, reportHash, sellerIdentificationBreaks, sniffImage, supplyBreak, validateReport, vatReasonBreak, walkComponents, xmlCharacterBreak } from "@formancy/report-spec";
2
+ import { DEFAULT_BUDGET, DEFAULT_VALUE_LIMITS, Decimal, addDecimal, compareDecimal, decimalFromString, decimalToString, evaluate, fixedCapabilities, multiplyDecimal, roundDecimal, subtractDecimal } from "@formancy/expressions";
3
3
  import { compileReport, diagnose, expressionValues } from "@formancy/report-core";
4
4
  //#region src/document.ts
5
- /**
6
- * The most bytes one image asset may have: 20 MB, the renderer trial's
7
- * limit, the plan's "enforced limits" made a number to test. The runtime
8
- * refuses an answer past it before copying it, and the renderer before
9
- * decoding it, from this one constant.
10
- */
11
- const MAX_ASSET_BYTES = 20971520;
12
5
  const REFUSAL_CODES = [
13
6
  "too-many-pages",
14
7
  "content-too-large",
@@ -209,7 +202,7 @@ function wrongType(expected, raw) {
209
202
  /** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */
210
203
  const INTEGER = /^(?:0|-?[1-9]\d*)$/;
211
204
  /** 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\.\d*[1-9]\d*)$/;
205
+ const DECIMAL = /^(?:-?[1-9]\d*(?:\.\d+)?|0(?:\.\d+)?|-0\.0*[1-9]\d*)$/;
213
206
  /** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */
214
207
  const DIGEST = /^sha256:[0-9a-f]{64}$/;
215
208
  /** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */
@@ -1078,7 +1071,7 @@ function currencyOf(source, scope) {
1078
1071
  return refused("invalid-currency", `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`);
1079
1072
  }
1080
1073
  /** 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) {
1074
+ function kept$1(cache, options, make) {
1082
1075
  const key = JSON.stringify(options);
1083
1076
  const found = cache.get(key);
1084
1077
  if (found !== void 0) return found;
@@ -1138,7 +1131,7 @@ var LocaleFormatter = class {
1138
1131
  };
1139
1132
  return {
1140
1133
  ok: true,
1141
- text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded)
1134
+ text: kept$1(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded)
1142
1135
  };
1143
1136
  }
1144
1137
  #date(value, style) {
@@ -1151,7 +1144,7 @@ var LocaleFormatter = class {
1151
1144
  };
1152
1145
  return {
1153
1146
  ok: true,
1154
- text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs)
1147
+ text: kept$1(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs)
1155
1148
  };
1156
1149
  }
1157
1150
  };
@@ -1503,6 +1496,7 @@ var Evaluator = class {
1503
1496
  return {
1504
1497
  code,
1505
1498
  message: `${[
1499
+ site.path.startsWith("/paymentPart/") ? "the payment part" : site.path.startsWith("/eInvoice/") ? "the e-invoice" : void 0,
1506
1500
  site.componentId === void 0 ? void 0 : `component ${site.componentId}`,
1507
1501
  site.columnId === void 0 ? void 0 : `column ${site.columnId}`,
1508
1502
  aggregateId === void 0 ? void 0 : `aggregate ${aggregateId}`,
@@ -1534,6 +1528,368 @@ function prepareExpressions(report) {
1534
1528
  };
1535
1529
  }
1536
1530
  //#endregion
1531
+ //#region src/xml.ts
1532
+ /**
1533
+ * XML, written one way: a tree of elements serialised with the same bytes
1534
+ * for the same tree, every text escaped so that a parser gives back exactly
1535
+ * what was written. The e-invoice's CII is built as such a tree
1536
+ * (`cii.ts`), and this is the one place it becomes text.
1537
+ *
1538
+ * Exactly, to a parser: a reader that applies the schema reads an element
1539
+ * the XSD types as xs:token -- an identifier, a code -- with its white
1540
+ * space collapsed. report-spec's rules refuse such a text that holds any
1541
+ * (`token` in `en16931.ts`), so what such a reader reads is what was
1542
+ * written too.
1543
+ *
1544
+ * - **Deterministic.** `<?xml version="1.0" encoding="UTF-8"?>`, no byte
1545
+ * order mark, a line feed after every line, two spaces a level, an empty
1546
+ * element closed at once, attributes in the order given. Nothing reads a
1547
+ * clock or the machine.
1548
+ * - **Escaped.** In text `&`, `<` and `>`, and a carriage return as
1549
+ * `&#13;`, which a parser would otherwise read as a line feed (XML 1.0,
1550
+ * 2.11). In an attribute the double quote too, and a tab, a line feed and
1551
+ * a carriage return as references, which a parser would otherwise read
1552
+ * as spaces (3.3.3).
1553
+ * - **Never a character XML 1.0 cannot hold.** report-spec's
1554
+ * `xmlCharacterBreak` decides which: the e-invoice's rules refuse a text
1555
+ * that holds one where it is read, naming its term. One that reaches the
1556
+ * writer anyway is a defect, thrown as a RangeError, never dropped, since
1557
+ * dropping it would change what the invoice says.
1558
+ */
1559
+ /** An element holding `children`, in order; an undefined child is a term the document leaves out. */
1560
+ function element(name, children, attributes = []) {
1561
+ return {
1562
+ name,
1563
+ attributes,
1564
+ content: children.filter((child) => child !== void 0)
1565
+ };
1566
+ }
1567
+ /** An element holding the text `text`. */
1568
+ function leaf(name, text, attributes = []) {
1569
+ return {
1570
+ name,
1571
+ attributes,
1572
+ content: text
1573
+ };
1574
+ }
1575
+ /** `text` with no character XML 1.0 cannot write; a RangeError when it holds one, which the rules refuse before. */
1576
+ function writable(text) {
1577
+ const broken = xmlCharacterBreak(text);
1578
+ if (broken !== void 0) throw new RangeError(`a text ${broken}; the e-invoice's rules refuse it where it is read`);
1579
+ return text;
1580
+ }
1581
+ const TEXT = /[&<>\r]/g;
1582
+ const ATTRIBUTE = /[&<>"\t\n\r]/g;
1583
+ const REFERENCES = {
1584
+ "&": "&amp;",
1585
+ "<": "&lt;",
1586
+ ">": "&gt;",
1587
+ "\"": "&quot;",
1588
+ " ": "&#9;",
1589
+ "\n": "&#10;",
1590
+ "\r": "&#13;"
1591
+ };
1592
+ const escaped = (pattern) => (text) => writable(text).replace(pattern, (character) => REFERENCES[character]);
1593
+ const text$1 = escaped(TEXT);
1594
+ const attribute = escaped(ATTRIBUTE);
1595
+ /** `node` written into `lines`, at `depth` levels. */
1596
+ function write(node, depth, lines) {
1597
+ const indent = " ".repeat(depth);
1598
+ const open = `${indent}<${node.name}${node.attributes.map(([name, value]) => ` ${name}="${attribute(value)}"`).join("")}`;
1599
+ if (typeof node.content === "string") {
1600
+ lines.push(`${open}>${text$1(node.content)}</${node.name}>`);
1601
+ return;
1602
+ }
1603
+ if (node.content.length === 0) {
1604
+ lines.push(`${open}/>`);
1605
+ return;
1606
+ }
1607
+ lines.push(`${open}>`);
1608
+ for (const child of node.content) write(child, depth + 1, lines);
1609
+ lines.push(`${indent}</${node.name}>`);
1610
+ }
1611
+ /** The document whose root is `root`, as UTF-8 XML text: its declaration first, a line feed after every line. */
1612
+ function xmlDocument(root) {
1613
+ const lines = ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>"];
1614
+ write(root, 0, lines);
1615
+ return `${lines.join("\n")}\n`;
1616
+ }
1617
+ //#endregion
1618
+ //#region src/cii-parties.ts
1619
+ /** `make` of `value` where there is one; nothing where the term is left out. */
1620
+ function optional$1(value, make) {
1621
+ return value === void 0 ? void 0 : make(value);
1622
+ }
1623
+ /** 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). */
1624
+ function postalAddress(address) {
1625
+ return element("ram:PostalTradeAddress", [
1626
+ leaf("ram:PostcodeCode", address.postalCode),
1627
+ leaf("ram:LineOne", address.line1),
1628
+ optional$1(address.line2, (line) => leaf("ram:LineTwo", line)),
1629
+ leaf("ram:CityName", address.city),
1630
+ leaf("ram:CountryID", address.country)
1631
+ ]);
1632
+ }
1633
+ /**
1634
+ * The seller or the buyer: its name (BT-27, BT-44), its legal registration
1635
+ * and its scheme (BT-30, BT-47), its address, its VAT identifier (BT-31,
1636
+ * BT-48) and, the seller's, its tax number (BT-32).
1637
+ */
1638
+ function tradeParty(name, party) {
1639
+ const registration = party.legalId;
1640
+ return element(name, [
1641
+ leaf("ram:Name", party.name),
1642
+ registration === void 0 ? void 0 : element("ram:SpecifiedLegalOrganization", [leaf("ram:ID", registration.id, registration.scheme === void 0 ? [] : [["schemeID", registration.scheme]])]),
1643
+ postalAddress(party.address),
1644
+ optional$1(party.vatId, (id) => element("ram:SpecifiedTaxRegistration", [leaf("ram:ID", id, [["schemeID", "VA"]])])),
1645
+ optional$1(party.taxNumber, (id) => element("ram:SpecifiedTaxRegistration", [leaf("ram:ID", id, [["schemeID", "FC"]])]))
1646
+ ]);
1647
+ }
1648
+ /**
1649
+ * BG-16: the means (BT-81), the account by its IBAN (BT-84) and its name
1650
+ * (BT-85), and the BIC of its bank (BT-86). The remittance information
1651
+ * (BT-83) is the settlement's `PaymentReference`, which `cii.ts` writes.
1652
+ */
1653
+ function paymentMeans(payment) {
1654
+ return element("ram:SpecifiedTradeSettlementPaymentMeans", [
1655
+ leaf("ram:TypeCode", payment.means),
1656
+ element("ram:PayeePartyCreditorFinancialAccount", [leaf("ram:IBANID", payment.account), optional$1(payment.accountName, (name) => leaf("ram:AccountName", name))]),
1657
+ optional$1(payment.bic, (bic) => element("ram:PayeeSpecifiedCreditorFinancialInstitution", [leaf("ram:BICID", bic)]))
1658
+ ]);
1659
+ }
1660
+ //#endregion
1661
+ //#region src/cii.ts
1662
+ /**
1663
+ * An e-invoice written as UN/CEFACT Cross Industry Invoice XML in the
1664
+ * Factur-X 1.09.2 / ZUGFeRD 2.5.2 EN 16931 profile (0027): the runtime's,
1665
+ * as the QR-bill's payload is, since the XML is the invoice's payload and
1666
+ * the renderer decides none of it.
1667
+ *
1668
+ * - **Its shape.** The root `rsm:CrossIndustryInvoice` with the four
1669
+ * namespaces of CEN/TC 434's binding; its context (BT-24), its document
1670
+ * (BT-1, BT-3, BT-2) and its transaction: the lines, then the
1671
+ * agreement, the delivery and the settlement, each element in the order
1672
+ * the profile's XSD `xs:sequence` gives it, at the path CEN's binding
1673
+ * gives each business term. Only elements D16B shares with D22B are
1674
+ * written, since the validators run the D16B schema.
1675
+ * - **Dates** are `udt:DateTimeString` of format 102, YYYYMMDD.
1676
+ * - **The delivery**, which the XSD needs once, is written empty where the
1677
+ * invoice gives an invoicing period and no delivery date: it has nothing
1678
+ * else to hold. Mustang 2.26.0's Factur-X schematron warns of that empty
1679
+ * element (PEPPOL-EN16931-R008, "still status warning"), and KoSIT's
1680
+ * EN 16931 scenario does not, measured by hand on 17 October 2026.
1681
+ * - **Amounts** are written from their own digits with exactly two places;
1682
+ * only `TaxTotalAmount` names its currency (CII-DT-031). A quantity and
1683
+ * a net price, which CEN does not hold to two places, are written as the
1684
+ * template's columns resolved them; a rate by value, `19`, `7`, `0`.
1685
+ * - **Its order** is the template's and the table's: categories as
1686
+ * declared, lines as the table prints them. The same invoice is the same
1687
+ * bytes (`xml.ts`).
1688
+ *
1689
+ * Every value is one the rules have already held (`e-invoice-lines.ts`,
1690
+ * `e-invoice-terms.ts`) and every total one `e-invoice-totals.ts`
1691
+ * computed: nothing here decides, rounds or checks.
1692
+ */
1693
+ /** CEN/TC 434's CII namespaces, as its schematron declares them. */
1694
+ const NAMESPACES = [
1695
+ ["xmlns:rsm", "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"],
1696
+ ["xmlns:qdt", "urn:un:unece:uncefact:data:standard:QualifiedDataType:100"],
1697
+ ["xmlns:ram", "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"],
1698
+ ["xmlns:udt", "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100"]
1699
+ ];
1700
+ /** A date, YYYY-MM-DD as the runtime holds one, as CII writes it: format 102, YYYYMMDD. */
1701
+ function dateTime(name, date) {
1702
+ return element(name, [leaf("udt:DateTimeString", date.replaceAll("-", ""), [["format", "102"]])]);
1703
+ }
1704
+ /** An amount, from its own digits; a RangeError for one not at the two places every total and line amount is computed at. */
1705
+ function amount$2(name, value, attributes = []) {
1706
+ if (value.scale !== 2) throw new RangeError(`${name} is at ${value.scale} places, and an e-invoice's amounts are computed at two`);
1707
+ return leaf(name, decimalToString(value), attributes);
1708
+ }
1709
+ /** 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. */
1710
+ function tradeTax(breakdown, totals) {
1711
+ return element("ram:ApplicableTradeTax", [
1712
+ totals === void 0 ? void 0 : amount$2("ram:CalculatedAmount", breakdown.amount),
1713
+ leaf("ram:TypeCode", "VAT"),
1714
+ optional$1(totals?.reason, (reason) => leaf("ram:ExemptionReason", reason)),
1715
+ totals === void 0 ? void 0 : amount$2("ram:BasisAmount", breakdown.basis),
1716
+ leaf("ram:CategoryCode", breakdown.category.code),
1717
+ leaf("ram:RateApplicablePercent", breakdown.rate)
1718
+ ]);
1719
+ }
1720
+ /** 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). */
1721
+ function line(each, breakdown) {
1722
+ return element("ram:IncludedSupplyChainTradeLineItem", [
1723
+ element("ram:AssociatedDocumentLineDocument", [leaf("ram:LineID", each.id)]),
1724
+ element("ram:SpecifiedTradeProduct", [leaf("ram:Name", each.name)]),
1725
+ element("ram:SpecifiedLineTradeAgreement", [element("ram:NetPriceProductTradePrice", [leaf("ram:ChargeAmount", each.netPrice)])]),
1726
+ element("ram:SpecifiedLineTradeDelivery", [leaf("ram:BilledQuantity", each.quantity, [["unitCode", each.unit]])]),
1727
+ element("ram:SpecifiedLineTradeSettlement", [tradeTax(breakdown), element("ram:SpecifiedTradeSettlementLineMonetarySummation", [amount$2("ram:LineTotalAmount", each.netAmount)])])
1728
+ ]);
1729
+ }
1730
+ /** 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). */
1731
+ function settlement(invoice) {
1732
+ const { terms, totals, currency } = invoice;
1733
+ const period = terms.period;
1734
+ return element("ram:ApplicableHeaderTradeSettlement", [
1735
+ optional$1(terms.payment?.remittance, (remittance) => leaf("ram:PaymentReference", remittance)),
1736
+ leaf("ram:InvoiceCurrencyCode", currency),
1737
+ terms.payment === void 0 ? void 0 : paymentMeans(terms.payment),
1738
+ ...totals.breakdown.map((breakdown) => tradeTax(breakdown, { reason: terms.reasons.get(breakdown.category.id) })),
1739
+ 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))]),
1740
+ 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))]),
1741
+ element("ram:SpecifiedTradeSettlementHeaderMonetarySummation", [
1742
+ amount$2("ram:LineTotalAmount", totals.lineTotal),
1743
+ amount$2("ram:TaxBasisTotalAmount", totals.taxBasisTotal),
1744
+ amount$2("ram:TaxTotalAmount", totals.taxTotal, [["currencyID", currency]]),
1745
+ amount$2("ram:GrandTotalAmount", totals.grandTotal),
1746
+ totals.paid === null ? void 0 : amount$2("ram:TotalPrepaidAmount", totals.paid),
1747
+ amount$2("ram:DuePayableAmount", totals.duePayable)
1748
+ ])
1749
+ ]);
1750
+ }
1751
+ /** `invoice` as CII XML, UTF-8 text with its declaration, the same bytes for the same invoice. */
1752
+ function ciiXml(invoice) {
1753
+ const { terms, totals } = invoice;
1754
+ const breakdowns = new Map(totals.breakdown.map((breakdown) => [breakdown.category.id, breakdown]));
1755
+ return xmlDocument(element("rsm:CrossIndustryInvoice", [
1756
+ element("rsm:ExchangedDocumentContext", [element("ram:GuidelineSpecifiedDocumentContextParameter", [leaf("ram:ID", FACTUR_X_PROFILES$1[invoice.profile].guideline)])]),
1757
+ element("rsm:ExchangedDocument", [
1758
+ leaf("ram:ID", terms.number),
1759
+ leaf("ram:TypeCode", invoice.type),
1760
+ dateTime("ram:IssueDateTime", terms.issued)
1761
+ ]),
1762
+ element("rsm:SupplyChainTradeTransaction", [
1763
+ ...invoice.lines.map((each) => line(each, breakdowns.get(each.category.id))),
1764
+ element("ram:ApplicableHeaderTradeAgreement", [
1765
+ optional$1(terms.buyerReference, (reference) => leaf("ram:BuyerReference", reference)),
1766
+ tradeParty("ram:SellerTradeParty", terms.seller),
1767
+ tradeParty("ram:BuyerTradeParty", terms.buyer)
1768
+ ]),
1769
+ element("ram:ApplicableHeaderTradeDelivery", [optional$1(terms.delivered, (delivered) => element("ram:ActualDeliverySupplyChainEvent", [dateTime("ram:OccurrenceDateTime", delivered)]))]),
1770
+ settlement(invoice)
1771
+ ])
1772
+ ], NAMESPACES));
1773
+ }
1774
+ //#endregion
1775
+ //#region src/e-invoice-totals.ts
1776
+ /**
1777
+ * An e-invoice's totals and VAT breakdown, computed once, here, from its
1778
+ * lines (0027): the page prints them through `invoice`, `vatBasis` and
1779
+ * `vatAmount`, and the XML is written from the very same values, so the
1780
+ * two cannot part. The rules are CEN/TC 434's CII artefacts 1.3.17's, by
1781
+ * number.
1782
+ *
1783
+ * | Value | Computed as | Rule |
1784
+ * |---|---|---|
1785
+ * | BT-131 | BT-129 × BT-146, rounded once to two places: held, not written from it | EN 16931's definition; PEPPOL-EN16931-R120 |
1786
+ * | BT-106 | Σ BT-131, each a whole number of cents | BR-CO-10 |
1787
+ * | BT-109 | BT-106: there are no allowances or charges | BR-CO-13 |
1788
+ * | BT-116 | Σ BT-131 of the category's lines | BR-S-08, BR-E-08, BR-AE-08 |
1789
+ * | 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 |
1790
+ * | BT-110 | Σ BT-117 | BR-CO-14 |
1791
+ * | BT-112 | BT-109 + BT-110 | BR-CO-15 |
1792
+ * | BT-115 | BT-112 − BT-113; there is no BT-114 | BR-CO-16 |
1793
+ *
1794
+ * - **Exact.** In `@formancy/expressions`' `Decimal`, a value as an integer
1795
+ * of units at a scale; nothing passes through a JavaScript number.
1796
+ * Dividing by 100 moves the point and loses nothing, so a category's tax
1797
+ * is the exact product rounded once. CEN tests BR-CO-17 and BR-S-09
1798
+ * within one unit of the currency either way, a euro, and the exact
1799
+ * product rounded once lies inside.
1800
+ * - **Per category, once.** VAT is rounded per category, never per line:
1801
+ * an ERP that rounds each line can differ by up to half a cent a line,
1802
+ * which is said where the costs are.
1803
+ * - **Half away from zero**, as upstream's `roundDecimal` rounds and as a
1804
+ * person rounds by hand. CEN's tests round the absolute value, where half
1805
+ * away from zero and XPath's `round` agree.
1806
+ * - **A breakdown for each category a line is in**, in the order the
1807
+ * invoice declares them: BR-E-01 and BR-AE-01 refuse one for a category
1808
+ * no line has, and one invoice is one XML.
1809
+ */
1810
+ const ZERO = new Decimal(0n, 2);
1811
+ /** `amount`, which a defect of the caller's would have written at another scale than the two places the XML writes. */
1812
+ function cents(amount, what) {
1813
+ if (amount.scale !== 2) throw new RangeError(`${what} is at ${amount.scale} places, and the e-invoice's lines are read at two`);
1814
+ return amount;
1815
+ }
1816
+ const sum$1 = (amounts) => {
1817
+ let total = ZERO;
1818
+ for (const amount of amounts) total = addDecimal(total, amount);
1819
+ return total;
1820
+ };
1821
+ /**
1822
+ * A line's net amount (BT-131) as EN 16931 makes it, which the lines'
1823
+ * reader holds each line's to: its quantity (BT-129) times its net price
1824
+ * (BT-146), each as the XML writes it, rounded once to two places, half
1825
+ * away from zero, as BT-117 is. This version writes no line allowance or
1826
+ * charge and no base quantity (BT-149), which would enter it.
1827
+ */
1828
+ function lineNetAmount(quantity, netPrice) {
1829
+ return roundDecimal(multiplyDecimal(decimalFromString(quantity), decimalFromString(netPrice)), 2);
1830
+ }
1831
+ /** BT-117 of a category of `rate` over `basis`: the exact product over 100, rounded once to two places, half away from zero. */
1832
+ function tax(basis, rate) {
1833
+ const product = multiplyDecimal(basis, decimalFromString(rate));
1834
+ return roundDecimal(new Decimal(product.units, product.scale + 2), 2);
1835
+ }
1836
+ /**
1837
+ * The totals of `lines`, each in one of `categories`, as declared; `paid`
1838
+ * the amount already paid (BT-113), or null. Every amount it is handed is
1839
+ * at exactly two places, as the lines' reader writes it, and a RangeError
1840
+ * says a caller handed one that is not.
1841
+ */
1842
+ function invoiceTotals(categories, lines, paid) {
1843
+ const amounts = lines.map((line, index) => cents(line.netAmount, `line ${index}'s net amount`));
1844
+ const breakdown = categories.flatMap((category) => {
1845
+ const own = lines.flatMap((line, index) => line.category === category ? [amounts[index]] : []);
1846
+ if (own.length === 0) return [];
1847
+ const basis = sum$1(own);
1848
+ return [{
1849
+ category,
1850
+ rate: checkVatRate(category.code, category.rate).value,
1851
+ basis,
1852
+ amount: tax(basis, category.rate)
1853
+ }];
1854
+ });
1855
+ const lineTotal = sum$1(amounts);
1856
+ const taxTotal = sum$1(breakdown.map(({ amount }) => amount));
1857
+ const grandTotal = addDecimal(lineTotal, taxTotal);
1858
+ const prepaid = paid === null ? null : cents(paid, "the paid amount");
1859
+ return {
1860
+ lineTotal,
1861
+ taxBasisTotal: lineTotal,
1862
+ taxTotal,
1863
+ grandTotal,
1864
+ paid: prepaid,
1865
+ duePayable: prepaid === null ? grandTotal : subtractDecimal(grandTotal, prepaid),
1866
+ breakdown
1867
+ };
1868
+ }
1869
+ /**
1870
+ * What the e-invoice's names hold, as an expression is handed them (0027,
1871
+ * beside 0009): `invoice` each document total, `paid` only where the
1872
+ * invoice declares a paid amount, as report-core binds it; `vatBasis` and
1873
+ * `vatAmount` each declared category's basis and tax by its id, null where
1874
+ * no line is in it, which prints as nothing (0007). The very values the
1875
+ * XML is written from.
1876
+ */
1877
+ function invoiceNames$1(invoice, totals) {
1878
+ const of = (category) => totals.breakdown.find((each) => each.category.id === category.id);
1879
+ return {
1880
+ invoice: {
1881
+ lineTotal: totals.lineTotal,
1882
+ taxBasisTotal: totals.taxBasisTotal,
1883
+ taxTotal: totals.taxTotal,
1884
+ grandTotal: totals.grandTotal,
1885
+ ...invoice.paid === void 0 ? {} : { paid: totals.paid },
1886
+ duePayable: totals.duePayable
1887
+ },
1888
+ vatBasis: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.basis ?? null])),
1889
+ vatAmount: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.amount ?? null]))
1890
+ };
1891
+ }
1892
+ //#endregion
1537
1893
  //#region src/resolve-errors.ts
1538
1894
  /** What lowering a report can find wrong besides what each earlier stage finds. */
1539
1895
  const RESOLVE_ERROR_CODES = [
@@ -1543,6 +1899,12 @@ const RESOLVE_ERROR_CODES = [
1543
1899
  "asset-lookup-failed",
1544
1900
  "rounding-not-decimal",
1545
1901
  "aggregate-value-type",
1902
+ "no-qr-value",
1903
+ "empty-qr-code",
1904
+ "invalid-qr-bill",
1905
+ "invalid-epc-qr-code",
1906
+ "invalid-e-invoice",
1907
+ "e-invoice-preview",
1546
1908
  "too-many-errors"
1547
1909
  ];
1548
1910
  /** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */
@@ -1553,6 +1915,10 @@ function placed(place) {
1553
1915
  ...place.row === void 0 ? {} : { row: place.row }
1554
1916
  };
1555
1917
  }
1918
+ /** A type as a message says what a value is: "a decimal", "an integer". */
1919
+ function aType(type) {
1920
+ return `${/^[aeiou]/.test(type) ? "an" : "a"} ${type}`;
1921
+ }
1556
1922
  function fromReport(error) {
1557
1923
  return {
1558
1924
  stage: "report",
@@ -1639,13 +2005,18 @@ function raw(values) {
1639
2005
  function headerOf(render) {
1640
2006
  return render.data.header ?? {};
1641
2007
  }
2008
+ /** The e-invoice's names, read wherever `totals` is, once they are computed; none in a report that is no e-invoice. */
2009
+ function invoiceNames(render) {
2010
+ return render.invoice?.names ?? {};
2011
+ }
1642
2012
  function reportScope(render, totals) {
1643
2013
  const header = headerOf(render);
1644
2014
  return {
1645
2015
  values: {
1646
2016
  params: render.params,
1647
2017
  header,
1648
- totals: raw(totals)
2018
+ totals: raw(totals),
2019
+ ...invoiceNames(render)
1649
2020
  },
1650
2021
  currency: {
1651
2022
  params: render.params,
@@ -1670,7 +2041,8 @@ function groupScope(render, group, aggregates, by) {
1670
2041
  group: {
1671
2042
  ...raw(aggregates),
1672
2043
  ...key
1673
- }
2044
+ },
2045
+ ...invoiceNames(render)
1674
2046
  },
1675
2047
  currency: {
1676
2048
  params: render.params,
@@ -1689,7 +2061,8 @@ function rowScope(render, totals, row) {
1689
2061
  params: render.params,
1690
2062
  header,
1691
2063
  totals: raw(totals),
1692
- row: row.record
2064
+ row: row.record,
2065
+ ...invoiceNames(render)
1693
2066
  },
1694
2067
  currency: {
1695
2068
  params: render.params,
@@ -1752,6 +2125,1048 @@ function imageValue(render, ref) {
1752
2125
  return render.data.header?.[ref.field] ?? null;
1753
2126
  }
1754
2127
  //#endregion
2128
+ //#region src/inlines.ts
2129
+ /** The value `inline`, at `path`, reads in `scope`, unformatted; undefined when its evaluation failed, which is recorded. */
2130
+ function inlineValue(render, scope, inline, path) {
2131
+ switch (inline.kind) {
2132
+ case "field": return fieldValue(render, scope.record, inline.field);
2133
+ case "parameter": {
2134
+ const value = render.params[inline.parameter] ?? null;
2135
+ return value === null ? null : {
2136
+ type: parameterType(render.report, inline.parameter),
2137
+ value
2138
+ };
2139
+ }
2140
+ case "expression": return valueOf(render, scope, `${path}/expression/cel`);
2141
+ case "aggregate": return (inline.over === "group" ? scope.group : render.totals.report)?.get(inline.aggregate) ?? null;
2142
+ }
2143
+ }
2144
+ /** 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. */
2145
+ function kept(render, path, row) {
2146
+ const column = row === void 0 ? void 0 : render.invoice?.columns.get(path);
2147
+ return column === void 0 ? void 0 : { value: column[row] };
2148
+ }
2149
+ /** The value `inline` reads in `scope`, and the text it prints; undefined when either could not be had, which is recorded. */
2150
+ function printed(render, scope, inline, path, owner) {
2151
+ const read = kept(render, path, scope.row);
2152
+ const value = read === void 0 ? inlineValue(render, scope, inline, path) : read.value;
2153
+ if (value === void 0) return void 0;
2154
+ const formatted = render.formatter.format(value, inline.format, scope.currency);
2155
+ if (formatted.ok) return {
2156
+ value,
2157
+ text: formatted.text
2158
+ };
2159
+ const where = [
2160
+ owner.componentId === void 0 ? owner.said : `component ${owner.componentId}`,
2161
+ owner.columnId && `column ${owner.columnId}`,
2162
+ scope.row !== void 0 && `detail row ${scope.row}`
2163
+ ].filter(Boolean).join(", ");
2164
+ render.problems.error({
2165
+ stage: "format",
2166
+ code: formatted.code,
2167
+ path,
2168
+ message: `${where}: ${formatted.message}`,
2169
+ ...placed({
2170
+ componentId: owner.componentId,
2171
+ columnId: owner.columnId,
2172
+ row: scope.row
2173
+ })
2174
+ });
2175
+ }
2176
+ /** `inline`, at `path` in the report, as the run it prints in `scope`; undefined when it could not be, which is recorded. */
2177
+ function runOf(render, scope, inline, path, owner) {
2178
+ if (inline.kind === "text") return { text: inline.text };
2179
+ if (inline.kind === "pageNumber" || inline.kind === "pageCount") return { field: inline.kind };
2180
+ const run = printed(render, scope, inline, path, owner);
2181
+ return run && { text: run.text };
2182
+ }
2183
+ /** What a code of less than its runs would scan as, by what they are encoded in. */
2184
+ const SCANNED_AS = {
2185
+ "a QR code": "some other text",
2186
+ "a QR-bill": "some other bill",
2187
+ "an EPC QR code": "some other transfer"
2188
+ };
2189
+ /**
2190
+ * The runs at `path`, read in `scope` run by run as a paragraph's are, so
2191
+ * that what a code or an e-invoice holds and what a paragraph prints never
2192
+ * format a value apart. A page counter has no value before there are
2193
+ * pages, and report-spec refuses one wherever runs are read so; one that
2194
+ * reaches here all the same throws, naming what holds it, never read as
2195
+ * nothing.
2196
+ */
2197
+ function readRuns(render, scope, runs, path, owner) {
2198
+ const texts = [];
2199
+ const nulls = [];
2200
+ let refused = false;
2201
+ for (const [index, inline] of runs.entries()) {
2202
+ const at = `${path}/${index}`;
2203
+ 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`);
2204
+ const run = inline.kind === "text" ? {
2205
+ value: void 0,
2206
+ text: inline.text
2207
+ } : printed(render, scope, inline, at, owner);
2208
+ if (run === void 0) refused = true;
2209
+ else {
2210
+ if (run.value === null) nulls.push(at);
2211
+ texts.push(run.text);
2212
+ }
2213
+ }
2214
+ return {
2215
+ text: texts.join(""),
2216
+ nulls,
2217
+ refused
2218
+ };
2219
+ }
2220
+ /**
2221
+ * The text `runs`, at `path`, join to when they are encoded in a code,
2222
+ * read as `readRuns` reads them. Undefined when a run is refused, which is
2223
+ * recorded, naming `encoder`.
2224
+ *
2225
+ * A final render refuses a run whose value is null: a code of less than
2226
+ * its content scans as some other text, and the page does not say so. A
2227
+ * preview encodes it as nothing, as a paragraph prints it, and says it
2228
+ * did.
2229
+ *
2230
+ * `unused` is given for a text its code may leave out, and says whether
2231
+ * the text the runs print leaves its element unused. A text that does,
2232
+ * nulls and all -- a nullable field's way of saying "none" -- is no text
2233
+ * rather than one cut short, and a final render takes it as a preview
2234
+ * does; one whose other runs print something is still refused.
2235
+ */
2236
+ function joinedText(render, scope, runs, path, encoder, unused) {
2237
+ const { text, nulls, refused } = readRuns(render, scope, runs, path, encoder);
2238
+ if (!render.preview && nulls.length > 0 && unused?.(text) !== true) {
2239
+ for (const at of nulls) render.problems.error({
2240
+ stage: "resolve",
2241
+ code: "no-qr-value",
2242
+ path: at,
2243
+ message: `${encoder.said}: this run has no value, and ${encoder.code} without it would scan as ${SCANNED_AS[encoder.code]}`,
2244
+ ...placed(encoder)
2245
+ });
2246
+ return;
2247
+ }
2248
+ return refused ? void 0 : {
2249
+ text,
2250
+ lacking: render.preview && nulls.length > 0
2251
+ };
2252
+ }
2253
+ /**
2254
+ * The text the QR code `id` encodes: its `content`, at `path`, joined as
2255
+ * `joinedText` joins it. Undefined when it is refused, which is recorded,
2256
+ * naming the code. A final render refuses content that prints nothing at
2257
+ * all, a code of nothing, which scans as no code; a preview encodes it.
2258
+ */
2259
+ function encodedText(render, scope, content, path, id) {
2260
+ const joined = joinedText(render, scope, content, `${path}/content`, {
2261
+ said: `component ${id}`,
2262
+ componentId: id,
2263
+ code: "a QR code"
2264
+ });
2265
+ if (joined === void 0) return void 0;
2266
+ if (joined.text !== "" || render.preview) return joined.text;
2267
+ render.problems.error({
2268
+ stage: "resolve",
2269
+ code: "empty-qr-code",
2270
+ path: `${path}/content`,
2271
+ message: `component ${id}: its content prints nothing, and a QR code of nothing scans as no code`,
2272
+ componentId: id
2273
+ });
2274
+ }
2275
+ /** The text of runs that hold no page counter: what a table cell or a group header prints. */
2276
+ function textOfRuns(runs) {
2277
+ return runs.map((run) => "text" in run ? run.text : "").join("");
2278
+ }
2279
+ //#endregion
2280
+ //#region src/e-invoice-lines.ts
2281
+ /**
2282
+ * An e-invoice's lines (BG-25): one for each row of the table that prints
2283
+ * them, read once, before the totals, for the page and the XML alike
2284
+ * (0027).
2285
+ *
2286
+ * - **One evaluation.** The four columns the e-invoice names -- the item
2287
+ * name (BT-153), the invoiced quantity (BT-129), the net price (BT-146)
2288
+ * and the net amount (BT-131) -- are read here for every row, as the
2289
+ * table reads a cell, and kept by the path of each column's value and the
2290
+ * row's index: the table prints the very value kept (`inlines.ts`). So
2291
+ * the page and the XML cannot each read a line, and part. The line's
2292
+ * identifier (BT-126), its unit (BT-130) and its VAT category (BT-151)
2293
+ * are codes a page need not print, read from each row as an aggregate
2294
+ * reads it.
2295
+ * - **In the table's order** (`orderTable`, 0007), which the XML holds
2296
+ * them in.
2297
+ * - **Held to EN 16931's rules**, report-spec's functions over text, the
2298
+ * ones its validator applies to a literal (`en16931.ts`): a code from a
2299
+ * closed list, a net price that is not negative, a net amount that is a
2300
+ * whole number of cents, never rounded, a category the invoice declares.
2301
+ * And to what EN 16931 defines and no rule of CEN's tests: a net amount
2302
+ * that is the quantity times the net price, rounded once to the cent
2303
+ * (`lineNetAmount`), and a line identifier no other line has. A rule
2304
+ * broken is `invalid-e-invoice`, naming the row and the column or the
2305
+ * code, the term and the rule, never the value.
2306
+ * - **Printed as the XML holds it.** A quantity or a net price whose
2307
+ * column's format shows fewer places than it has is refused: the page
2308
+ * would round it, and the XML would not.
2309
+ * - **A preview holds what it has.** A final render refuses a term that
2310
+ * has no value (BR-21 to BR-26, BR-CO-04) and a table of no rows
2311
+ * (BR-16). A preview takes a term with no value as one it lacks, and
2312
+ * leaves a line whose net amount or category it lacks out of every
2313
+ * total, as an aggregate skips a null; what the data does hold it holds
2314
+ * to the same rules.
2315
+ */
2316
+ /** The key of each term of `LineTerms` the e-invoice names a column or a code by. */
2317
+ const TERM_OF = {
2318
+ name: "name",
2319
+ quantity: "quantity",
2320
+ netPrice: "netPrice",
2321
+ netAmount: "netAmount",
2322
+ id: "id",
2323
+ unit: "unit",
2324
+ vat: "category"
2325
+ };
2326
+ function refuse$3(render, place, message) {
2327
+ render.problems.error({
2328
+ stage: "resolve",
2329
+ code: "invalid-e-invoice",
2330
+ path: place.path,
2331
+ message: `${place.said}, detail row ${place.row}: ${message}`,
2332
+ ...placed(place)
2333
+ });
2334
+ }
2335
+ /** The rule a term with no value breaks: every line term is needed. */
2336
+ function required(term) {
2337
+ const rule = term.term in E_INVOICE_DECIMALS ? E_INVOICE_DECIMALS[term.term].required : E_INVOICE_TEXTS[term.term].required;
2338
+ return en16931Rule(rule, "has no value, and every line of an e-invoice has one");
2339
+ }
2340
+ /** A value as its term's text: a decimal and an integer by their own digits, a text as it is. */
2341
+ function written(value) {
2342
+ return value.type === "decimal" ? decimalToString(value.value) : String(value.value);
2343
+ }
2344
+ /**
2345
+ * The term `term` of a line, read as `value`, held to its rule: what the
2346
+ * XML writes, null where a preview has no value for it, or undefined when
2347
+ * it is refused, which is recorded at `place`.
2348
+ */
2349
+ function checked$2(render, term, value, place) {
2350
+ if (value === null || render.preview && value.type === "string" && eInvoiceBlank(value.value)) return render.preview ? null : refuse$3(render, place, `${term.what} ${required(term)}`);
2351
+ 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)}`);
2352
+ const text = written(value);
2353
+ const outcome = term.term in E_INVOICE_DECIMALS ? checkEInvoiceDecimal(term.term, text) : checkEInvoiceText(term.term, text);
2354
+ return outcome.ok ? outcome.value : refuse$3(render, place, `${term.what} ${outcome.rule}`);
2355
+ }
2356
+ /** The table the lines are the rows of, and the columns that print their terms. */
2357
+ function namedColumns(render, invoice) {
2358
+ const located = walkComponents(render.report).find(({ component }) => component.kind === "table" && component.id === invoice.lines.table);
2359
+ const table = located.component;
2360
+ return {
2361
+ table,
2362
+ columns: Object.keys(E_INVOICE_LINE_COLUMNS).map((key) => {
2363
+ const index = table.columns.findIndex((column) => column.id === invoice.lines[key]);
2364
+ const column = table.columns[index];
2365
+ return {
2366
+ key,
2367
+ id: column.id,
2368
+ value: column.value,
2369
+ path: `${located.path}/columns/${index}/value`,
2370
+ printed: new Array(render.data.detail.length).fill(null)
2371
+ };
2372
+ })
2373
+ };
2374
+ }
2375
+ /**
2376
+ * The columns whose term the XML writes with the data's own places, which
2377
+ * their format may not round: the quantity and the net price. The net
2378
+ * amount and every total are amounts the XML writes at two places, which
2379
+ * the editing core holds a format to where the template is written.
2380
+ */
2381
+ const AS_WRITTEN = /* @__PURE__ */ new Set(["quantity", "netPrice"]);
2382
+ /** The places `column` prints `value` at, where printing it there would round it, by value; undefined where it prints it as it is. */
2383
+ function roundingPlaces(column, value) {
2384
+ const format = column.value.format;
2385
+ if (!AS_WRITTEN.has(column.key) || value.type !== "decimal" || format?.kind !== "number" && format?.kind !== "currency") return void 0;
2386
+ const shown = roundDecimalAs(value.value, {
2387
+ scale: format.scale,
2388
+ mode: "half-away-from-zero"
2389
+ });
2390
+ return compareDecimal(shown, value.value) === 0 ? void 0 : format.scale;
2391
+ }
2392
+ /** 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. */
2393
+ function readColumn(render, scope, column, place) {
2394
+ const value = inlineValue(render, scope, column.value, column.path);
2395
+ if (value === void 0) return void 0;
2396
+ column.printed[place.row] = value;
2397
+ const term = E_INVOICE_LINE_COLUMNS[column.key];
2398
+ const text = checked$2(render, term, value, place);
2399
+ const places = typeof text === "string" ? roundingPlaces(column, value) : void 0;
2400
+ if (places === void 0) return text;
2401
+ 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`);
2402
+ }
2403
+ /** 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. */
2404
+ function readLine(render, invoice, table, columns, row) {
2405
+ const scope = rowScope(render, render.totals.report, row);
2406
+ const terms = {};
2407
+ let whole = true;
2408
+ const keep = (key, value) => {
2409
+ if (value === void 0) whole = false;
2410
+ else terms[TERM_OF[key]] = value;
2411
+ };
2412
+ const placeOf = (column) => ({
2413
+ path: column.path,
2414
+ said: `component ${table.id}, column ${column.id}`,
2415
+ componentId: table.id,
2416
+ columnId: column.id,
2417
+ row: row.index
2418
+ });
2419
+ for (const column of columns) {
2420
+ const text = readColumn(render, scope, column, placeOf(column));
2421
+ keep(column.key, column.key === "netAmount" && typeof text === "string" ? decimalFromString(text) : text);
2422
+ }
2423
+ const { quantity, netPrice, netAmount } = terms;
2424
+ 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`));
2425
+ for (const key of Object.keys(E_INVOICE_LINE_CODES)) {
2426
+ const code = invoice.lines[key];
2427
+ const path = `/eInvoice/lines/${key}`;
2428
+ const value = code.kind === "field" ? fieldValue(render, row.record, code.field) : valueOf(render, scope, `${path}/expression/cel`);
2429
+ if (value === void 0) {
2430
+ whole = false;
2431
+ continue;
2432
+ }
2433
+ const place = {
2434
+ path,
2435
+ said: "the e-invoice",
2436
+ row: row.index
2437
+ };
2438
+ const text = checked$2(render, E_INVOICE_LINE_CODES[key], value, place);
2439
+ if (key !== "vat" || typeof text !== "string") keep(key, text);
2440
+ else {
2441
+ const category = checkLineCategory(text, invoice.vat);
2442
+ keep(key, category.ok ? category.value : refuse$3(render, place, `${E_INVOICE_LINE_CODES.vat.what} ${category.rule}`));
2443
+ }
2444
+ }
2445
+ return whole ? {
2446
+ ...terms,
2447
+ row: row.index
2448
+ } : void 0;
2449
+ }
2450
+ /**
2451
+ * `invoice`'s lines in the table's order, each term read once and held to
2452
+ * its rule, and what the named columns printed of each row; undefined when
2453
+ * a line is refused, or could not be read, which is recorded. A final
2454
+ * render refuses a table of no rows (BR-16).
2455
+ */
2456
+ function readLines(render, invoice) {
2457
+ const { table, columns } = namedColumns(render, invoice);
2458
+ const lines = [];
2459
+ const ids = /* @__PURE__ */ new Set();
2460
+ let whole = true;
2461
+ for (const row of orderTable(render.report, table, render.data.detail).rows) {
2462
+ if (render.problems.full) return void 0;
2463
+ const line = readLine(render, invoice, table, columns, row);
2464
+ if (line === void 0) whole = false;
2465
+ else if (line.id !== null && ids.has(line.id)) {
2466
+ refuse$3(render, {
2467
+ path: "/eInvoice/lines/id",
2468
+ said: "the e-invoice",
2469
+ row: row.index
2470
+ }, `${E_INVOICE_LINE_CODES.id.what} is an earlier line's, and each line of an e-invoice has its own`);
2471
+ whole = false;
2472
+ } else {
2473
+ if (line.id !== null) ids.add(line.id);
2474
+ lines.push(line);
2475
+ }
2476
+ }
2477
+ if (!render.preview && render.data.detail.length === 0) {
2478
+ render.problems.error({
2479
+ stage: "resolve",
2480
+ code: "invalid-e-invoice",
2481
+ path: "/eInvoice/lines/table",
2482
+ 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`)}`,
2483
+ componentId: table.id
2484
+ });
2485
+ return;
2486
+ }
2487
+ return whole ? {
2488
+ lines,
2489
+ columns: new Map(columns.map(({ path, printed }) => [path, printed]))
2490
+ } : void 0;
2491
+ }
2492
+ /** The lines a final render writes: every term of each read, which a final render refuses a line without. */
2493
+ function writtenLines(lines) {
2494
+ return lines.every((line) => Object.values(line).every((term) => term !== null)) ? lines : void 0;
2495
+ }
2496
+ //#endregion
2497
+ //#region src/e-invoice-terms.ts
2498
+ /**
2499
+ * An e-invoice's terms but its lines -- its number, its dates, its seller
2500
+ * and its buyer, its categories' reasons, its payment instructions, its
2501
+ * paid amount -- each read in the report's scope once the data has
2502
+ * resolved it, and held to EN 16931's rules: report-spec's `en16931.ts`,
2503
+ * the very functions its validator applies to a literal, named by the same
2504
+ * tables.
2505
+ *
2506
+ * - **Read as a paragraph.** Each text is its runs, read as a paragraph's
2507
+ * in the report's scope (`readRuns`), so the XML holds what the same runs
2508
+ * would print. A literal passes again; a value from data is held where
2509
+ * the validator could not see it.
2510
+ * - **What may be left out is.** An optional text the data resolves to
2511
+ * blank, nulls and all, is a term the XML leaves out, as an EPC QR code's
2512
+ * optional texts are: a nullable field's null is how data says "none".
2513
+ * A needed one that prints nothing breaks its rule (BR-02, BR-06 ...);
2514
+ * one whose runs print something around a null is refused as a text cut
2515
+ * short.
2516
+ * - **What only the whole says** -- the identifiers the lines' categories
2517
+ * need of the seller and the buyer (BR-CO-26, BR-S-02, BR-E-02,
2518
+ * BR-AE-02), the time of supply (§ 14 UStG), a category's reason (BR-E-10,
2519
+ * BR-AE-10) -- is said of the categories the lines are in, once every
2520
+ * part has resolved; an invoicing period's order (BR-29) once both its
2521
+ * dates have.
2522
+ * - **A preview holds what it has**: a term it has no value for is one it
2523
+ * lacks, and what only an absence breaks it does not say. What the data
2524
+ * holds it holds to the same rules.
2525
+ *
2526
+ * A rule broken is `invalid-e-invoice` at the term, naming its business
2527
+ * term and the rule, never the value, which may be a person's name,
2528
+ * account or VAT identifier.
2529
+ */
2530
+ /** What an error names the e-invoice by: it stands in no component. */
2531
+ const OWNER = { said: "the e-invoice" };
2532
+ function refuse$2({ render }, path, message) {
2533
+ render.problems.error({
2534
+ stage: "resolve",
2535
+ code: "invalid-e-invoice",
2536
+ path,
2537
+ message: `the e-invoice: ${message}`
2538
+ });
2539
+ }
2540
+ /** The text of `term`, its runs at `path`, held to its rule. */
2541
+ function text(reader, term, runs, path) {
2542
+ if (runs === void 0) return null;
2543
+ const read = readRuns(reader.render, reader.scope, runs, path, OWNER);
2544
+ if (read.refused) return void 0;
2545
+ const rule = E_INVOICE_TEXTS[term];
2546
+ const blank = eInvoiceBlank(read.text);
2547
+ if (reader.render.preview && (blank || read.nulls.length > 0)) return null;
2548
+ if (blank && rule.required === void 0) return null;
2549
+ 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`);
2550
+ const checked = checkEInvoiceText(term, read.text);
2551
+ return checked.ok ? checked.value : refuse$2(reader, path, `${rule.what} ${checked.rule}`);
2552
+ }
2553
+ /** The date of `term`, its expression at `path`: a day on the calendar, YYYY-MM-DD. */
2554
+ function date(reader, term, expression, path) {
2555
+ if (expression === void 0) return null;
2556
+ const value = valueOf(reader.render, reader.scope, `${path}/cel`);
2557
+ if (value === void 0) return void 0;
2558
+ const rule = E_INVOICE_DATES[term];
2559
+ 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")}`);
2560
+ if (value.type !== "date" && value.type !== "string") return refuse$2(reader, path, `${rule.what} is a date, and this gives ${aType(value.type)}`);
2561
+ const checked = checkEInvoiceDate(value.value);
2562
+ return checked.ok ? checked.value : refuse$2(reader, path, `${rule.what} ${checked.rule}`);
2563
+ }
2564
+ /** `value` under `key` where it is a value; nothing where it is none or was refused. */
2565
+ const term = (key, value) => value === null || value === void 0 ? {} : { [key]: value };
2566
+ /** Whether every one of `values` was read and is there: what a term needs of each of its parts. */
2567
+ const all = (...values) => values.every((value) => value !== null && value !== void 0);
2568
+ function address$1(reader, held, path, which) {
2569
+ const terms = E_INVOICE_TEXT_TERMS[which].address;
2570
+ const line1 = text(reader, terms.line1, held.line1, `${path}/line1`);
2571
+ const line2 = text(reader, terms.line2, held.line2, `${path}/line2`);
2572
+ const postalCode = text(reader, terms.postalCode, held.postalCode, `${path}/postalCode`);
2573
+ const city = text(reader, terms.city, held.city, `${path}/city`);
2574
+ const country = text(reader, terms.country, held.country, `${path}/country`);
2575
+ if (line2 === void 0 || !all(line1, postalCode, city, country)) return void 0;
2576
+ return {
2577
+ line1,
2578
+ ...term("line2", line2),
2579
+ postalCode,
2580
+ city,
2581
+ country
2582
+ };
2583
+ }
2584
+ function party$1(reader, held, path, which) {
2585
+ const terms = E_INVOICE_TEXT_TERMS[which];
2586
+ const name = text(reader, terms.name, held.name, `${path}/name`);
2587
+ const vatId = text(reader, terms.vatId, held.vatId, `${path}/vatId`);
2588
+ const taxNumber = which === "seller" ? text(reader, E_INVOICE_TEXT_TERMS.seller.taxNumber, held.taxNumber, `${path}/taxNumber`) : null;
2589
+ const legalId = text(reader, terms.legalId, held.legalId?.id, `${path}/legalId/id`);
2590
+ const where = address$1(reader, held.address, `${path}/address`, which);
2591
+ const has = {
2592
+ vatId: vatId !== null,
2593
+ taxNumber: taxNumber !== null,
2594
+ legalId: legalId !== null
2595
+ };
2596
+ if (vatId === void 0 || taxNumber === void 0 || legalId === void 0 || !all(name, where)) return {
2597
+ party: void 0,
2598
+ has
2599
+ };
2600
+ const scheme = held.legalId?.scheme;
2601
+ const registration = legalId === null ? {} : { legalId: {
2602
+ id: legalId,
2603
+ ...scheme === void 0 ? {} : { scheme }
2604
+ } };
2605
+ return {
2606
+ party: {
2607
+ name,
2608
+ ...term("vatId", vatId),
2609
+ ...term("taxNumber", taxNumber),
2610
+ ...registration,
2611
+ address: where
2612
+ },
2613
+ has
2614
+ };
2615
+ }
2616
+ function payment(reader, invoice) {
2617
+ const held = invoice.payment;
2618
+ if (held === void 0) return {
2619
+ payment: null,
2620
+ account: void 0
2621
+ };
2622
+ const terms = E_INVOICE_TEXT_TERMS.payment;
2623
+ const account = text(reader, terms.iban, held.iban, "/eInvoice/payment/iban");
2624
+ const bic = text(reader, terms.bic, held.bic, "/eInvoice/payment/bic");
2625
+ const accountName = text(reader, terms.accountName, held.accountName, "/eInvoice/payment/accountName");
2626
+ const remittance = text(reader, terms.remittance, held.remittance, "/eInvoice/payment/remittance");
2627
+ const known = account ?? void 0;
2628
+ if (bic === void 0 || accountName === void 0 || remittance === void 0 || !all(account)) return {
2629
+ payment: void 0,
2630
+ account: known
2631
+ };
2632
+ return {
2633
+ payment: {
2634
+ means: held.means,
2635
+ account,
2636
+ ...term("bic", bic),
2637
+ ...term("accountName", accountName),
2638
+ ...term("remittance", remittance)
2639
+ },
2640
+ account: known
2641
+ };
2642
+ }
2643
+ /** 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. */
2644
+ function paidAmount(render, invoice) {
2645
+ if (invoice.paid === void 0) return null;
2646
+ const path = "/eInvoice/paid";
2647
+ const value = valueOf(render, reportScope(render, render.totals.report), `${path}/cel`);
2648
+ if (value === void 0 || value === null) return value;
2649
+ const what = E_INVOICE_DECIMALS["BT-113"].what;
2650
+ if (value.type !== "decimal") return refuse$2({ render }, path, `${what} is a decimal, and this gives ${aType(value.type)}`);
2651
+ const checked = checkEInvoiceDecimal("BT-113", decimalToString(value.value));
2652
+ return checked.ok ? decimalFromString(checked.value) : refuse$2({ render }, path, `${what} ${checked.rule}`);
2653
+ }
2654
+ /**
2655
+ * Every term of `invoice` but its lines and its totals, each read in the
2656
+ * report's scope and held to its rule, and what the whole breaks said of
2657
+ * `used`, the categories the lines are in. `terms` is undefined where a
2658
+ * term was refused, which is recorded, or a preview lacks one.
2659
+ */
2660
+ function readTerms(render, invoice, used) {
2661
+ const reader = {
2662
+ render,
2663
+ scope: reportScope(render, render.totals.report)
2664
+ };
2665
+ const number = text(reader, E_INVOICE_TEXT_TERMS.number, invoice.number, "/eInvoice/number");
2666
+ const issued = date(reader, "BT-2", invoice.issued, "/eInvoice/issued");
2667
+ const seller = party$1(reader, invoice.seller, "/eInvoice/seller", "seller");
2668
+ const buyer = party$1(reader, invoice.buyer, "/eInvoice/buyer", "buyer");
2669
+ const buyerReference = text(reader, E_INVOICE_TEXT_TERMS.buyerReference, invoice.buyerReference, "/eInvoice/buyerReference");
2670
+ const delivered = date(reader, "BT-72", invoice.delivered, "/eInvoice/delivered");
2671
+ const start = date(reader, "BT-73", invoice.period?.start, "/eInvoice/period/start");
2672
+ const end = date(reader, "BT-74", invoice.period?.end, "/eInvoice/period/end");
2673
+ const reasons = used.map((category) => [category, text(reader, E_INVOICE_TEXT_TERMS.reason, category.reason, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`)]);
2674
+ const paying = payment(reader, invoice);
2675
+ const due = date(reader, "BT-9", invoice.due, "/eInvoice/due");
2676
+ const terms = text(reader, E_INVOICE_TEXT_TERMS.terms, invoice.terms, "/eInvoice/terms");
2677
+ const ordered = typeof start === "string" && typeof end === "string" ? checkInvoicingPeriod(start, end) : void 0;
2678
+ if (ordered !== void 0) refuse$2(reader, "/eInvoice/period", ordered);
2679
+ if (!render.preview) {
2680
+ const codes = used.map(({ code }) => code);
2681
+ for (const rule of sellerIdentificationBreaks(seller.has, codes)) refuse$2(reader, "/eInvoice/seller", rule);
2682
+ const unidentified = buyerIdentificationBreak(buyer.has, codes);
2683
+ if (unidentified !== void 0) refuse$2(reader, "/eInvoice/buyer", unidentified);
2684
+ const unsupplied = supplyBreak(delivered !== null, start !== null || end !== null);
2685
+ if (unsupplied !== void 0) refuse$2(reader, "/eInvoice/delivered", unsupplied);
2686
+ for (const [category, reason] of reasons) {
2687
+ const unreasoned = vatReasonBreak(category.code, reason !== null);
2688
+ if (unreasoned !== void 0) refuse$2(reader, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`, unreasoned);
2689
+ }
2690
+ }
2691
+ const read = [
2692
+ number,
2693
+ issued,
2694
+ seller.party,
2695
+ buyer.party,
2696
+ buyerReference,
2697
+ delivered,
2698
+ start,
2699
+ end,
2700
+ paying.payment,
2701
+ due,
2702
+ terms,
2703
+ ...reasons.map(([, reason]) => reason)
2704
+ ];
2705
+ if (render.problems.failed || read.includes(void 0) || !all(number, issued, seller.party, buyer.party)) return {
2706
+ terms: void 0,
2707
+ account: paying.account
2708
+ };
2709
+ return {
2710
+ terms: {
2711
+ number,
2712
+ issued,
2713
+ seller: seller.party,
2714
+ buyer: buyer.party,
2715
+ ...term("buyerReference", buyerReference),
2716
+ ...term("delivered", delivered),
2717
+ ...start === null && end === null ? {} : { period: {
2718
+ ...term("start", start),
2719
+ ...term("end", end)
2720
+ } },
2721
+ reasons: new Map(reasons.flatMap(([category, reason]) => typeof reason === "string" ? [[category.id, reason]] : [])),
2722
+ ...term("payment", paying.payment),
2723
+ ...term("due", due),
2724
+ ...term("terms", terms)
2725
+ },
2726
+ account: paying.account
2727
+ };
2728
+ }
2729
+ //#endregion
2730
+ //#region src/lower-e-invoice.ts
2731
+ /**
2732
+ * A report's e-invoice resolved (0027): its lines and its totals before
2733
+ * anything is lowered, since the page prints them; and after the page is
2734
+ * lowered, in a final render, the XML the PDF embeds.
2735
+ *
2736
+ * 1. **The lines**, read once from the rows of the table that prints them
2737
+ * (`e-invoice-lines.ts`), each column's value kept for the table to
2738
+ * print.
2739
+ * 2. **The paid amount and the totals**, computed once from the lines
2740
+ * (`e-invoice-totals.ts`) and bound as `invoice`, `vatBasis` and
2741
+ * `vatAmount` for every scope that reads them.
2742
+ * 3. **The other terms**, read in the report's scope and held to EN
2743
+ * 16931's rules (`e-invoice-terms.ts`); a payment code is held to the
2744
+ * amount due and the account they give (`e-invoice-payable.ts`).
2745
+ * 4. **The XML** (`cii.ts`), written from those very values.
2746
+ *
2747
+ * **A preview is not the invoice.** In Germany the XML a hybrid invoice
2748
+ * embeds is the invoice, so a preview writes none and the PDF that leaves
2749
+ * it is no e-invoice; it prints the totals of what it has, and warns
2750
+ * `e-invoice-preview` whatever data it has, so that every page carries a
2751
+ * preview label, complete data or not. A final render writes the XML or
2752
+ * refuses.
2753
+ */
2754
+ function facturX(render, invoice) {
2755
+ const read = readLines(render, invoice);
2756
+ const paid = paidAmount(render, invoice);
2757
+ if (read === void 0 || paid === void 0) return void 0;
2758
+ const placed = read.lines.flatMap(({ netAmount, category }) => netAmount === null || category === null ? [] : [{
2759
+ netAmount,
2760
+ category
2761
+ }]);
2762
+ const totals = invoiceTotals(invoice.vat, placed, paid);
2763
+ const { terms, account } = readTerms(render, invoice, totals.breakdown.map(({ category }) => category));
2764
+ const lines = writtenLines(read.lines);
2765
+ const written = render.preview || terms === void 0 || lines === void 0 ? void 0 : {
2766
+ profile: invoice.profile,
2767
+ type: invoice.type,
2768
+ currency: invoice.currency,
2769
+ terms,
2770
+ lines,
2771
+ totals
2772
+ };
2773
+ return {
2774
+ reads: {
2775
+ names: invoiceNames$1(invoice, totals),
2776
+ columns: read.columns,
2777
+ payable: {
2778
+ amount: totals.duePayable,
2779
+ account
2780
+ }
2781
+ },
2782
+ written
2783
+ };
2784
+ }
2785
+ /** How each kind of e-invoice is resolved. A table over every kind, so a kind added to report-spec without a way down does not compile. */
2786
+ const RESOLVERS = { facturX };
2787
+ /**
2788
+ * `invoice`, `render`'s e-invoice, resolved before anything is lowered:
2789
+ * its lines, its totals and its terms. Undefined when its lines or its
2790
+ * totals could not be, which is recorded: nothing that prints them can be
2791
+ * lowered. A term refused is recorded, and leaves nothing to write.
2792
+ */
2793
+ function resolveEInvoice(render, invoice) {
2794
+ return RESOLVERS[invoice.kind](render, invoice);
2795
+ }
2796
+ /** What a preview of an e-invoice warns, whatever data it has. */
2797
+ 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";
2798
+ /**
2799
+ * The file the PDF of `render` embeds, once its page is lowered: in a
2800
+ * final render the XML, named as report-spec names it; in a preview none,
2801
+ * and the warning that says so. Undefined too where anything was refused,
2802
+ * which refuses the document.
2803
+ *
2804
+ * A final render with nothing to write and nothing recorded would hand on
2805
+ * a document without its XML, which a renderer draws as a plain PDF: a
2806
+ * picture of an invoice handed over as though it were one. Every way to
2807
+ * nothing records an error first, so that is a defect, and throws.
2808
+ */
2809
+ function eInvoiceFile(render, resolved, invoice) {
2810
+ if (render.preview) {
2811
+ render.problems.warn({
2812
+ stage: "resolve",
2813
+ code: "e-invoice-preview",
2814
+ path: "/eInvoice",
2815
+ message: `the e-invoice: ${PREVIEWED}`
2816
+ });
2817
+ return;
2818
+ }
2819
+ if (render.problems.failed) return void 0;
2820
+ 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");
2821
+ const profile = FACTUR_X_PROFILES$1[invoice.profile];
2822
+ return {
2823
+ xml: ciiXml(resolved.written),
2824
+ fileName: FACTUR_X$1.fileName,
2825
+ relationship: profile.relationship,
2826
+ conformanceLevel: profile.conformanceLevel
2827
+ };
2828
+ }
2829
+ //#endregion
2830
+ //#region src/e-invoice-payable.ts
2831
+ /**
2832
+ * A payment code printed with an e-invoice -- the QR-bill, an EPC QR code
2833
+ * -- held to it once both have resolved: it asks for the amount due for
2834
+ * payment (BT-115), or leaves the amount to the payer, and to be paid to
2835
+ * the e-invoice's payment account (BT-84).
2836
+ *
2837
+ * The page and the XML are one invoice, or the page is a second one: a
2838
+ * picture that asks for another amount or another account than its
2839
+ * structured part says may count as a further invoice under § 14c UStG
2840
+ * (BMF, 15 October 2025, UStAE 14c.1 (4a)). report-spec refuses what a
2841
+ * template's literals break, its currency among them; what only the data
2842
+ * decides -- an amount is always an expression, an account may be read
2843
+ * from a field -- is compared here, by value, the account as each code's
2844
+ * own rule wrote it: its spaces dropped and its letters capitals. A code
2845
+ * whose amount or account its own rules refused is not compared again.
2846
+ */
2847
+ /**
2848
+ * Records what `code`, which asks for `amount` -- null to leave it to the
2849
+ * payer -- to `account`, asks for that the e-invoice does not name; nothing
2850
+ * in a report that is no e-invoice, or where the e-invoice's account was
2851
+ * refused or a preview lacks it.
2852
+ */
2853
+ function checkPayable(render, code, amount, account) {
2854
+ const payable = render.invoice?.payable;
2855
+ if (payable === void 0) return;
2856
+ const refuse = (path, message) => render.problems.error({
2857
+ stage: "resolve",
2858
+ code: "invalid-e-invoice",
2859
+ path,
2860
+ message: `${code.said}: ${message}`,
2861
+ ...code.componentId === void 0 ? {} : { componentId: code.componentId }
2862
+ });
2863
+ 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`);
2864
+ 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`);
2865
+ }
2866
+ //#endregion
2867
+ //#region src/qr-bill.ts
2868
+ /**
2869
+ * A Swiss QR-bill made from values SIX's rules have accepted: the Swiss QR
2870
+ * Code's payload, and every text its slip prints.
2871
+ *
2872
+ * The rules a value is held to are report-spec's (`qr-bill.ts` there), one
2873
+ * set for a literal at validation and for a value from data here. What is
2874
+ * the runtime's alone is what a checked bill becomes:
2875
+ *
2876
+ * - **The payload**, in the order of IG Table 8, each element on its line.
2877
+ * - **The printed values**, grouped as the slip prints them (IG 3.5, 3.6).
2878
+ * - **The headings**, in the slip's language (IG Annex C).
2879
+ *
2880
+ * Nothing here reads a value as a number: an amount's digits are grouped
2881
+ * as text. "IG" is SIX's Swiss Implementation Guidelines for the QR-bill,
2882
+ * version 2.4 of 24 February 2026, whose payload, printing rules and
2883
+ * headings are version 2.3's, but for the Romansh headings it adds.
2884
+ */
2885
+ /**
2886
+ * IG Annex C, Table 23, version 2.4, read in its PDF's text. Version 2.3's
2887
+ * English table printed Italian's currency as "Value date" and two French
2888
+ * words wrongly, which version 2.4 and the French edition correct; and
2889
+ * version 2.4 adds Romansh, in force since 1 January 2026.
2890
+ */
2891
+ const HEADINGS = {
2892
+ de: {
2893
+ paymentPart: "Zahlteil",
2894
+ receipt: "Empfangsschein",
2895
+ account: "Konto / Zahlbar an",
2896
+ reference: "Referenz",
2897
+ additionalInformation: "Zusätzliche Informationen",
2898
+ payableBy: "Zahlbar durch",
2899
+ payableByBlank: "Zahlbar durch (Name/Adresse)",
2900
+ currency: "Währung",
2901
+ amount: "Betrag",
2902
+ acceptancePoint: "Annahmestelle",
2903
+ separate: "Vor der Einzahlung abzutrennen"
2904
+ },
2905
+ fr: {
2906
+ paymentPart: "Section paiement",
2907
+ receipt: "Récépissé",
2908
+ account: "Compte / Payable à",
2909
+ reference: "Référence",
2910
+ additionalInformation: "Informations supplémentaires",
2911
+ payableBy: "Payable par",
2912
+ payableByBlank: "Payable par (nom/adresse)",
2913
+ currency: "Monnaie",
2914
+ amount: "Montant",
2915
+ acceptancePoint: "Point de dépôt",
2916
+ separate: "A détacher avant le versement"
2917
+ },
2918
+ it: {
2919
+ paymentPart: "Sezione pagamento",
2920
+ receipt: "Ricevuta",
2921
+ account: "Conto / Pagabile a",
2922
+ reference: "Riferimento",
2923
+ additionalInformation: "Informazioni supplementari",
2924
+ payableBy: "Pagabile da",
2925
+ payableByBlank: "Pagabile da (nome/indirizzo)",
2926
+ currency: "Valuta",
2927
+ amount: "Importo",
2928
+ acceptancePoint: "Punto di accettazione",
2929
+ separate: "Da staccare prima del versamento"
2930
+ },
2931
+ en: {
2932
+ paymentPart: "Payment part",
2933
+ receipt: "Receipt",
2934
+ account: "Account / Payable to",
2935
+ reference: "Reference",
2936
+ additionalInformation: "Additional information",
2937
+ payableBy: "Payable by",
2938
+ payableByBlank: "Payable by (name/address)",
2939
+ currency: "Currency",
2940
+ amount: "Amount",
2941
+ acceptancePoint: "Acceptance point",
2942
+ separate: "Separate before paying in"
2943
+ },
2944
+ rm: {
2945
+ paymentPart: "Part da pajament",
2946
+ receipt: "Quittanza",
2947
+ account: "Conto / Da pajar a",
2948
+ reference: "Referenza",
2949
+ additionalInformation: "Infurmaziuns supplementaras",
2950
+ payableBy: "Da pajar da",
2951
+ payableByBlank: "Da pajar da (num/adressa)",
2952
+ currency: "Valuta",
2953
+ amount: "Import",
2954
+ acceptancePoint: "Post da recepziun",
2955
+ separate: "Da distatgar avant che pajar"
2956
+ }
2957
+ };
2958
+ /** An address's parts in the order the code holds them, which report-spec's table of their rules is in. */
2959
+ const ADDRESS_PARTS$1 = Object.keys(QR_BILL_ADDRESS_RULES);
2960
+ /** A party's seven lines (IG Table 8): the structured address type, S, and its parts; none at all, seven empty lines. */
2961
+ function party(address) {
2962
+ return address === null ? ["", ...ADDRESS_PARTS$1.map(() => "")] : ["S", ...ADDRESS_PARTS$1.map((part) => address[part])];
2963
+ }
2964
+ /**
2965
+ * The Swiss QR Code's text (IG 4.1.4, Table 8). Every element is on its
2966
+ * line, an empty one as an empty line, and the lines are separated by a
2967
+ * line feed, with none after the last. The ultimate creditor's lines are
2968
+ * empty: SIX keeps them for later use and they "must not be filled in".
2969
+ * Billing information, of status A, is left out when the bill has none:
2970
+ * nothing after it is ever used, since this format has no alternative
2971
+ * procedure. Version 0200 is the only one SIX allows in master version 02,
2972
+ * and coding 1 is UTF-8 restricted to the characters of IG 4.1.1.
2973
+ */
2974
+ function payload(bill) {
2975
+ return [
2976
+ "SPC",
2977
+ "0200",
2978
+ "1",
2979
+ bill.account.iban,
2980
+ ...party(bill.creditor),
2981
+ ...party(null),
2982
+ bill.amount ?? "",
2983
+ bill.currency,
2984
+ ...party(bill.debtor),
2985
+ bill.reference?.type ?? "NON",
2986
+ bill.reference?.reference ?? "",
2987
+ bill.message,
2988
+ "EPD",
2989
+ ...bill.billingInformation === "" ? [] : [bill.billingInformation]
2990
+ ].join("\n");
2991
+ }
2992
+ /** `text` in blocks of `size` characters from its start, the last block shorter. */
2993
+ function blocks(text, size) {
2994
+ const parts = [];
2995
+ for (let start = 0; start < text.length; start += size) parts.push(text.slice(start, start + size));
2996
+ return parts.join(" ");
2997
+ }
2998
+ /** A QR reference in two digits and five blocks of five; a creditor reference in blocks of four (IG 3.5.4). */
2999
+ function printedReference(reference) {
3000
+ const { type, reference: text } = reference;
3001
+ return type === "QRR" ? `${text.slice(0, 2)} ${blocks(text.slice(2), 5)}` : blocks(text, 4);
3002
+ }
3003
+ /** The amount with a space between each three digits before the point (IG 3.5.3: "CHF 1 590.00"), grouped as text. */
3004
+ function printedAmount(amount) {
3005
+ const [whole = "", cents = ""] = amount.split(".");
3006
+ const groups = [];
3007
+ for (let end = whole.length; end > 0; end -= 3) groups.unshift(whole.slice(Math.max(0, end - 3), end));
3008
+ return `${groups.join(" ")}.${cents}`;
3009
+ }
3010
+ /**
3011
+ * An address as the slip prints it, as IG 3.5.4 and SIX's style guide show
3012
+ * it: the name; the street and building number, on one line; the postal
3013
+ * code and the town. The country is printed for a party outside
3014
+ * Switzerland, Liechtenstein one of them; the guidelines do not say how,
3015
+ * and it goes before the postal code, as in "LI-9490 Vaduz".
3016
+ */
3017
+ function printedAddress(address) {
3018
+ const street = [address.street, address.buildingNumber].filter((part) => part !== "").join(" ");
3019
+ const country = address.country === "CH" ? "" : `${address.country}-`;
3020
+ return [
3021
+ address.name,
3022
+ ...street === "" ? [] : [street],
3023
+ `${country}${address.postalCode} ${address.town}`
3024
+ ];
3025
+ }
3026
+ /** The document's bill: `bill`'s payload, and every text its slip prints, in its language. */
3027
+ function qrBillPart(bill) {
3028
+ const { payableByBlank, payableBy, ...words } = HEADINGS[bill.language];
3029
+ return {
3030
+ kind: "swissQrBill",
3031
+ payload: payload(bill),
3032
+ headings: {
3033
+ ...words,
3034
+ payableBy: bill.debtor === null ? payableByBlank : payableBy
3035
+ },
3036
+ account: blocks(bill.account.iban, 4),
3037
+ creditor: printedAddress(bill.creditor),
3038
+ reference: bill.reference === null ? null : printedReference(bill.reference),
3039
+ additionalInformation: [bill.message, bill.billingInformation].filter((text) => text !== ""),
3040
+ debtor: bill.debtor === null ? null : printedAddress(bill.debtor),
3041
+ currency: bill.currency,
3042
+ amount: bill.amount === null ? null : printedAmount(bill.amount)
3043
+ };
3044
+ }
3045
+ //#endregion
3046
+ //#region src/lower-payment-part.ts
3047
+ /**
3048
+ * A report's payment part lowered to the document's: each text read in the
3049
+ * report's scope, held to SIX's rules, and made into the bill
3050
+ * (`qr-bill.ts`).
3051
+ *
3052
+ * - **Read as a paragraph.** Every text is its runs, read as a paragraph's
3053
+ * in the report's scope and joined as a QR code's content is
3054
+ * (`joinedText`): a final render refuses a run whose value is null, as
3055
+ * `no-qr-value`, since the bill's code would say less than its texts.
3056
+ * - **Held to SIX's rules.** report-spec's checks, the very functions its
3057
+ * validator applies to a literal, are applied to every text once it has
3058
+ * resolved: a literal passes again, and a value from data is held where
3059
+ * the validator could not see it. A rule broken is `invalid-qr-bill` on
3060
+ * the field, naming the rule and never the value, which may be a
3061
+ * person's name or account.
3062
+ * - **The same in a preview.** A preview prints a value that is null, or
3063
+ * one its data lacks, as nothing, as a paragraph does; the bill that
3064
+ * leaves is held to the same rules, and refused where it breaks one,
3065
+ * saying the preview had no value for it. A bill SIX refuses cannot be
3066
+ * drawn as one: its code would scan as a bill no bank pays.
3067
+ * - **The amount** is a decimal, or null for the payer to fill in. Any
3068
+ * other value is refused by its type, and a decimal is written with its
3069
+ * own digits, never rounded: one with more than two places is refused.
3070
+ * - **Printed with an e-invoice**, it asks for the amount due and to be
3071
+ * paid to the e-invoice's account (`e-invoice-payable.ts`).
3072
+ */
3073
+ const PATH = "/paymentPart";
3074
+ /** What an error in the payment part names it by: it stands in no component. */
3075
+ const PART = {
3076
+ said: "the payment part",
3077
+ code: "a QR-bill"
3078
+ };
3079
+ function refuse$1({ render }, path, message) {
3080
+ render.problems.error({
3081
+ stage: "resolve",
3082
+ code: "invalid-qr-bill",
3083
+ path,
3084
+ message
3085
+ });
3086
+ }
3087
+ /**
3088
+ * The text the runs at `path` print, held to `check`, as `what` names it in
3089
+ * an error: what the check made of it, or undefined when a run or the rule
3090
+ * refused it, which is recorded. Absent runs print nothing, which the rule
3091
+ * judges: an optional text, nothing; a required one, empty.
3092
+ */
3093
+ function checked$1(lowering, runs, path, what, check) {
3094
+ const joined = joinedText(lowering.render, lowering.scope, runs ?? [], path, PART);
3095
+ if (joined === void 0) return void 0;
3096
+ const outcome = check(joined.text);
3097
+ if (outcome.ok) return outcome.value;
3098
+ return refuse$1(lowering, path, `${what} ${outcome.rule}${joined.lacking ? "; this preview has no value for a run of it" : ""}`);
3099
+ }
3100
+ const ADDRESS_PARTS = Object.entries(QR_BILL_ADDRESS_RULES);
3101
+ /** A party's address, each part held to its rule; undefined when a part is refused, which is recorded. */
3102
+ function address(lowering, value, path, party) {
3103
+ const parts = {};
3104
+ let whole = true;
3105
+ for (const [part, rule] of ADDRESS_PARTS) {
3106
+ const text = checked$1(lowering, value[part], `${path}/${part}`, `the ${party}'s ${rule.said}`, (each) => checkQrBillText(each, rule));
3107
+ if (text === void 0) whole = false;
3108
+ else parts[part] = text;
3109
+ }
3110
+ return whole ? parts : void 0;
3111
+ }
3112
+ /** The amount as the code writes it, null for the payer to fill in, or undefined when it is refused, which is recorded. */
3113
+ function amount$1(lowering, expression) {
3114
+ if (expression === void 0) return null;
3115
+ const path = `${PATH}/amount`;
3116
+ const value = valueOf(lowering.render, lowering.scope, `${path}/cel`);
3117
+ if (value === void 0 || value === null) return value;
3118
+ 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`);
3119
+ const outcome = checkQrBillAmount$1(decimalToString(value.value));
3120
+ return outcome.ok ? outcome.value : refuse$1(lowering, path, `the amount ${outcome.rule}`);
3121
+ }
3122
+ /** `bill`, resolved and held to SIX's rules; undefined when anything of it is refused, which is recorded. */
3123
+ function swissQrBill(lowering, bill) {
3124
+ const account = checked$1(lowering, bill.account, `${PATH}/account`, "the account", checkQrBillAccount);
3125
+ const creditor = address(lowering, bill.creditor, `${PATH}/creditor`, "creditor");
3126
+ const sum = amount$1(lowering, bill.amount);
3127
+ const debtor = bill.debtor === void 0 ? null : address(lowering, bill.debtor, `${PATH}/debtor`, "debtor");
3128
+ const reference = bill.reference === void 0 ? null : checked$1(lowering, bill.reference, `${PATH}/reference`, "the reference", checkQrBillReference);
3129
+ const message = checked$1(lowering, bill.message, `${PATH}/message`, "the message", (text) => checkQrBillText(text, QR_BILL_MESSAGE_RULE));
3130
+ const billing = checked$1(lowering, bill.billingInformation, `${PATH}/billingInformation`, "the billing information", (text) => checkQrBillText(text, QR_BILL_BILLING_RULE));
3131
+ const together = message === void 0 || billing === void 0 ? void 0 : checkQrBillAdditionalInformation(message, billing);
3132
+ if (together !== void 0) refuse$1(lowering, `${PATH}/message`, together);
3133
+ if (account !== void 0 && sum !== void 0) {
3134
+ const asked = {
3135
+ said: PART.said,
3136
+ code: "the QR-bill",
3137
+ amountPath: `${PATH}/amount`,
3138
+ accountPath: `${PATH}/account`
3139
+ };
3140
+ checkPayable(lowering.render, asked, sum === null ? null : decimalFromString(sum), account.iban);
3141
+ }
3142
+ const pairing = account === void 0 || reference === void 0 ? [] : qrBillPairing(account.qrIban ? "qrIban" : "iban", reference?.type ?? "NON", bill.currency);
3143
+ for (const { field, rule } of pairing) refuse$1(lowering, `${PATH}/${field}`, rule);
3144
+ if (together !== void 0 || pairing.length > 0) return void 0;
3145
+ 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;
3146
+ return qrBillPart({
3147
+ language: bill.language,
3148
+ account,
3149
+ creditor,
3150
+ currency: bill.currency,
3151
+ amount: sum,
3152
+ debtor,
3153
+ reference,
3154
+ message,
3155
+ billingInformation: billing
3156
+ });
3157
+ }
3158
+ /** 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. */
3159
+ const PARTS = { swissQrBill };
3160
+ /** `render`'s payment part, lowered; undefined when the report has none, or when it is refused, which is recorded. */
3161
+ function lowerPaymentPart(render) {
3162
+ const part = render.report.paymentPart;
3163
+ if (part === void 0) return void 0;
3164
+ return PARTS[part.kind]({
3165
+ render,
3166
+ scope: reportScope(render, render.totals.report)
3167
+ }, part);
3168
+ }
3169
+ //#endregion
1755
3170
  //#region src/images.ts
1756
3171
  /**
1757
3172
  * An image component lowered to the bytes it draws.
@@ -1763,11 +3178,14 @@ function imageValue(render, ref) {
1763
3178
  * bytes, and a media type a report may draw, the one the template declares
1764
3179
  * for its own asset -- and copied, so that nothing the host changes
1765
3180
  * afterwards reaches the document. Whether the bytes are a picture is the
1766
- * renderer's to say (`invalid-asset`).
3181
+ * renderer's to say (`invalid-asset`): for an SVG, whether they are exactly
3182
+ * the drawing report-spec's `cleanSvg` writes, by report-spec's `checkSvg`,
3183
+ * which the renderer applies (0030).
1767
3184
  *
1768
- * The lookup is trusted to return the bytes the digest pins: the runtime has
1769
- * no hash function of its own, being free of Node and of the DOM, and does
1770
- * not check them against it.
3185
+ * The lookup is trusted to return the bytes the digest pins, and they are
3186
+ * not checked against it. Not for want of a hash: a pure SHA-256 reaches the
3187
+ * runtime through `@formancy/spec`, and checking digests is a decision of
3188
+ * its own, since it changes what every host's resolver must satisfy (0030).
1771
3189
  *
1772
3190
  * An image field with no value draws nothing, and its box is kept as space,
1773
3191
  * so that what follows it stands where it would with a picture: null prints
@@ -1775,8 +3193,11 @@ function imageValue(render, ref) {
1775
3193
  *
1776
3194
  * Each approved asset is asked for once per render, and every image that
1777
3195
  * draws it shares the one copy, so that a logo on every page header, or a
1778
- * photo drawn by forty components, is held and embedded once. An answer
1779
- * past `MAX_ASSET_BYTES` is refused before it is copied.
3196
+ * photo drawn by forty components, is held once: a PNG or a JPEG is
3197
+ * embedded once, and an SVG is drawn again wherever it prints, on every
3198
+ * page of a page region (0030). An answer past its type's limit --
3199
+ * `MAX_ASSET_BYTES`, or `MAX_SVG_BYTES` for an SVG -- is refused before it
3200
+ * is copied.
1780
3201
  */
1781
3202
  /** 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
3203
  function checkedBytes(found, declared) {
@@ -1785,7 +3206,8 @@ function checkedBytes(found, declared) {
1785
3206
  const { mediaType, bytes } = found;
1786
3207
  if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType)) return media;
1787
3208
  if (declared !== void 0 && mediaType !== declared) return media;
1788
- if (bytes.length > 20971520) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES} (20 MB)`;
3209
+ 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)`;
3210
+ if (bytes.length > MAX_ASSET_BYTES$1) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES$1} (20 MB)`;
1789
3211
  return {
1790
3212
  mediaType,
1791
3213
  bytes: new Uint8Array(bytes)
@@ -1880,49 +3302,150 @@ function imageBlock(render, component, path) {
1880
3302
  };
1881
3303
  }
1882
3304
  //#endregion
1883
- //#region src/inlines.ts
1884
- /** The value `inline` prints, read in `scope`; undefined when its evaluation failed, which is recorded. */
1885
- function valueAt(render, scope, inline, path) {
1886
- switch (inline.kind) {
1887
- case "field": return fieldValue(render, scope.record, inline.field);
1888
- case "parameter": {
1889
- const value = render.params[inline.parameter] ?? null;
1890
- return value === null ? null : {
1891
- type: parameterType(render.report, inline.parameter),
1892
- value
1893
- };
1894
- }
1895
- case "expression": return valueOf(render, scope, `${path}/expression/cel`);
1896
- case "aggregate": return (inline.over === "group" ? scope.group : render.totals.report)?.get(inline.aggregate) ?? null;
1897
- }
1898
- }
1899
- /** `inline`, at `path` in the report, as the run it prints in `scope`; undefined when it could not be, which is recorded. */
1900
- function runOf(render, scope, inline, path, owner) {
1901
- if (inline.kind === "text") return { text: inline.text };
1902
- if (inline.kind === "pageNumber" || inline.kind === "pageCount") return { field: inline.kind };
1903
- const value = valueAt(render, scope, inline, path);
1904
- if (value === void 0) return void 0;
1905
- const formatted = render.formatter.format(value, inline.format, scope.currency);
1906
- if (formatted.ok) return { text: formatted.text };
1907
- const where = [
1908
- owner.componentId && `component ${owner.componentId}`,
1909
- owner.columnId && `column ${owner.columnId}`,
1910
- scope.row !== void 0 && `detail row ${scope.row}`
1911
- ].filter(Boolean).join(", ");
3305
+ //#region src/lower-epc-qr-code.ts
3306
+ /**
3307
+ * An EPC QR code lowered to the document's block: each text read in the
3308
+ * report's scope, held to the EPC's rules, and written into the payload the
3309
+ * renderer encodes. "EPC" is EPC069-12, version 3.1, by its section.
3310
+ *
3311
+ * - **Read as a paragraph.** Every text is its runs, read as a paragraph's
3312
+ * in the report's scope and joined as a QR code's content is
3313
+ * (`joinedText`): a final render refuses a run whose value is null, as
3314
+ * `no-qr-value`, since the transfer would say less than the invoice --
3315
+ * unless the text is optional and prints nothing else.
3316
+ * - **Held to the EPC's rules.** report-spec's checks (`epc-payload.ts`),
3317
+ * the very functions its validator applies to a literal, are applied to
3318
+ * every text once it has resolved: a literal passes again, and a value
3319
+ * from data is held where the validator could not see it -- the IBAN's
3320
+ * spaces dropped and its letters made capitals, its country's, its
3321
+ * length and its check digits; the BIC, and whether the account needs
3322
+ * one; the creditor reference; each text's characters and length. A rule
3323
+ * broken is `invalid-epc-qr-code` on the field, naming the code and the
3324
+ * rule and never the value, which may be a person's name or account.
3325
+ * - **An optional text that prints nothing is unused.** A BIC, a
3326
+ * reference, a text or information the data gives empty, blank or null
3327
+ * is an element the code leaves empty, as one the template does not
3328
+ * have, in a final render as in a preview: a customer with no BIC on
3329
+ * record is paid by version 002, never refused for a BIC that is no BIC.
3330
+ * The validator refuses a blank literal instead, a second spelling of an
3331
+ * element left out.
3332
+ * - **The same in a preview.** A preview prints a value that is null, or
3333
+ * one its data lacks, as nothing, as a paragraph does; the code that
3334
+ * leaves is held to the same rules, and refused where it breaks one,
3335
+ * saying the preview had no value for it. A code the EPC refuses cannot
3336
+ * be drawn as one: it would scan as a transfer no bank makes.
3337
+ * - **The amount** is a decimal, or null for the payer to fill in. Any
3338
+ * other value is refused by its type, and a decimal is written with its
3339
+ * own digits, as short as it can be, never rounded: one with more than
3340
+ * two places is refused.
3341
+ * - **The payload** is report-spec's `epcPayload` of the checked texts,
3342
+ * held to the EPC's 331 bytes in UTF-8, which only the whole can break.
3343
+ * - **Printed with an e-invoice**, it asks for the amount due and to be
3344
+ * paid to the e-invoice's account (`e-invoice-payable.ts`).
3345
+ */
3346
+ /** What a refusal adds when a preview had no value for a run of the text it refuses. */
3347
+ const LACKED = "; this preview has no value for a run of it";
3348
+ function refuse({ render, code, encoder }, path, message) {
1912
3349
  render.problems.error({
1913
- stage: "format",
1914
- code: formatted.code,
3350
+ stage: "resolve",
3351
+ code: "invalid-epc-qr-code",
1915
3352
  path,
1916
- message: `${where}: ${formatted.message}`,
1917
- ...placed({
1918
- ...owner,
1919
- row: scope.row
1920
- })
3353
+ message: `${encoder.said}: ${message}`,
3354
+ componentId: code.id
1921
3355
  });
1922
3356
  }
1923
- /** The text of runs that hold no page counter: what a table cell or a group header prints. */
1924
- function textOfRuns(runs) {
1925
- return runs.map((run) => "text" in run ? run.text : "").join("");
3357
+ /**
3358
+ * The text `key` of the code, resolved and held to its field's rule
3359
+ * (report-spec's `EPC_TEXT_FIELDS`); undefined when a run or the rule
3360
+ * refused it, which is recorded. An optional text that prints nothing a
3361
+ * payer reads (`epcBlank`), nulls and all, is its element unused, and no
3362
+ * rule is asked.
3363
+ */
3364
+ function checked(lowering, key) {
3365
+ const runs = lowering.code[key];
3366
+ if (runs === void 0) return {
3367
+ text: "",
3368
+ lacking: false
3369
+ };
3370
+ const path = `${lowering.path}/${key}`;
3371
+ const { what, optional } = EPC_TEXT_FIELDS[key];
3372
+ const joined = joinedText(lowering.render, lowering.scope, runs, path, lowering.encoder, optional ? epcBlank : void 0);
3373
+ if (joined === void 0) return void 0;
3374
+ if (optional && epcBlank(joined.text)) return {
3375
+ text: "",
3376
+ lacking: joined.lacking
3377
+ };
3378
+ const outcome = checkEpcField(key, joined.text);
3379
+ if (outcome.ok) return {
3380
+ text: outcome.value,
3381
+ lacking: joined.lacking
3382
+ };
3383
+ return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? LACKED : ""}`);
3384
+ }
3385
+ /** The amount as the code writes it after `EUR`, '' for the payer to fill in, or undefined when it is refused, which is recorded. */
3386
+ function amount(lowering) {
3387
+ if (lowering.code.amount === void 0) return "";
3388
+ const path = `${lowering.path}/amount`;
3389
+ const value = valueOf(lowering.render, lowering.scope, `${path}/cel`);
3390
+ if (value === void 0) return void 0;
3391
+ if (value === null) return "";
3392
+ 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`);
3393
+ const outcome = checkEpcAmount(decimalToString(value.value));
3394
+ return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`);
3395
+ }
3396
+ /**
3397
+ * The block the EPC QR code `code`, at `path`, prints, read in `scope`;
3398
+ * undefined when anything of it is refused, which is recorded. Every text
3399
+ * is read and every rule broken said, not the first alone.
3400
+ */
3401
+ function epcQrCodeBlock(render, scope, code, path) {
3402
+ const lowering = {
3403
+ render,
3404
+ scope,
3405
+ code,
3406
+ path,
3407
+ encoder: {
3408
+ said: `component ${code.id}`,
3409
+ componentId: code.id,
3410
+ code: "an EPC QR code"
3411
+ }
3412
+ };
3413
+ const bic = checked(lowering, "bic");
3414
+ const beneficiary = checked(lowering, "beneficiary");
3415
+ const iban = checked(lowering, "iban");
3416
+ const sum = amount(lowering);
3417
+ const reference = checked(lowering, "reference");
3418
+ const text = checked(lowering, "text");
3419
+ const information = checked(lowering, "information");
3420
+ const pairing = epcPairing(iban?.text, bic === void 0 ? void 0 : bic.text === "" ? null : bic.text);
3421
+ for (const { field, rule } of pairing) refuse(lowering, `${path}/${field}`, `${rule}${bic?.lacking === true ? LACKED : ""}`);
3422
+ if (iban !== void 0 && sum !== void 0) checkPayable(render, {
3423
+ said: lowering.encoder.said,
3424
+ code: "the EPC QR code",
3425
+ componentId: code.id,
3426
+ amountPath: `${path}/amount`,
3427
+ accountPath: `${path}/iban`
3428
+ }, sum === "" ? null : decimalFromString(sum), iban.text);
3429
+ 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;
3430
+ const payload = epcPayload({
3431
+ bic: bic.text,
3432
+ beneficiary: beneficiary.text,
3433
+ iban: iban.text,
3434
+ amount: sum,
3435
+ purpose: code.purpose,
3436
+ reference: reference.text,
3437
+ text: text.text,
3438
+ information: information.text
3439
+ });
3440
+ const bytes = checkEpcPayload(payload);
3441
+ if (!bytes.ok) return refuse(lowering, path, `its payload ${bytes.rule}`);
3442
+ return {
3443
+ kind: "epcQrCode",
3444
+ id: code.id,
3445
+ payload,
3446
+ size: code.size,
3447
+ ...code.caption === void 0 ? {} : { caption: code.caption }
3448
+ };
1926
3449
  }
1927
3450
  //#endregion
1928
3451
  //#region src/styles.ts
@@ -2068,6 +3591,17 @@ const LOWER = {
2068
3591
  };
2069
3592
  },
2070
3593
  image: (image, { render, path }) => imageBlock(render, image, path),
3594
+ qrCode: (code, { render, scope, path }) => {
3595
+ const text = encodedText(render, scope, code.content, path, code.id);
3596
+ return text === void 0 ? void 0 : {
3597
+ kind: "qrCode",
3598
+ id: code.id,
3599
+ text,
3600
+ size: code.size,
3601
+ errorCorrection: code.errorCorrection
3602
+ };
3603
+ },
3604
+ epcQrCode: (code, { render, scope, path }) => epcQrCodeBlock(render, scope, code, path),
2071
3605
  line: (line) => ({
2072
3606
  kind: "rule",
2073
3607
  thickness: line.thickness,
@@ -2346,28 +3880,38 @@ function computeTotals(render) {
2346
3880
  * 2. the options, the parameters and the data, each checked, and every
2347
3881
  * error of the three listed together (`parameters.ts`, `data.ts`);
2348
3882
  * 3. the aggregates, exactly, over every row (`totals.ts`);
2349
- * 4. the regions, lowered component by component (`lower.ts`), tables row
3883
+ * 4. the e-invoice's lines, read once, and its totals and its terms, where
3884
+ * the report is one (`lower-e-invoice.ts`);
3885
+ * 5. the regions, lowered component by component (`lower.ts`), tables row
2350
3886
  * by row (`lower-table.ts`), images through the host's lookup
2351
- * (`images.ts`).
3887
+ * (`images.ts`), an EPC QR code's every text held to the EPC's rules
3888
+ * (`lower-epc-qr-code.ts`);
3889
+ * 6. the payment part, its every text held to SIX's rules
3890
+ * (`lower-payment-part.ts`);
3891
+ * 7. the e-invoice's XML, in a final render (`cii.ts`).
2352
3892
  *
2353
3893
  * It refuses rather than prints a wrong report: any error at any stage, and
2354
3894
  * the result is the errors, never a partial document. A preview may run on
2355
3895
  * data the provider calls incomplete or that lacks a field; it says so in
2356
3896
  * the manifest and in its warnings, and its every page carries
2357
3897
  * `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for
2358
- * the report. A final render refuses such data.
3898
+ * the report. A final render refuses such data. A preview of an e-invoice
3899
+ * writes no XML, and is labelled whatever its data:
3900
+ * `E_INVOICE_PREVIEW_LABEL` where nothing else is lacking.
2359
3901
  */
2360
3902
  /** What every page of a preview that lacks data says, at the top of its page header. */
2361
3903
  const PREVIEW_LABEL = "Preview of incomplete data: not a final report";
2362
- const LABEL = {
3904
+ /** 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. */
3905
+ const E_INVOICE_PREVIEW_LABEL = "Preview: not an e-invoice, and not a final report";
3906
+ const label = (text) => ({
2363
3907
  kind: "paragraph",
2364
- runs: [{ text: PREVIEW_LABEL }],
3908
+ runs: [{ text }],
2365
3909
  style: {
2366
3910
  size: 8,
2367
3911
  bold: true,
2368
3912
  color: "#b00020"
2369
3913
  }
2370
- };
3914
+ });
2371
3915
  /** Each parameter's value as the format writes one. */
2372
3916
  function writtenParameters(values) {
2373
3917
  return Object.fromEntries(Object.entries(values).map(([id, value]) => {
@@ -2435,17 +3979,30 @@ function resolveReport(report, data, options) {
2435
3979
  ok: false,
2436
3980
  errors: problems.errors()
2437
3981
  };
2438
- const regions = lowerRegions({
3982
+ const invoice = valid.eInvoice === void 0 ? void 0 : resolveEInvoice({
2439
3983
  ...inputs,
2440
3984
  totals
2441
- });
3985
+ }, valid.eInvoice);
3986
+ if (valid.eInvoice !== void 0 && invoice === void 0) return {
3987
+ ok: false,
3988
+ errors: problems.errors()
3989
+ };
3990
+ const render = {
3991
+ ...inputs,
3992
+ totals,
3993
+ ...invoice === void 0 ? {} : { invoice: invoice.reads }
3994
+ };
3995
+ const regions = lowerRegions(render);
3996
+ const paymentPart = lowerPaymentPart(render);
3997
+ const eInvoice = invoice === void 0 || valid.eInvoice === void 0 ? void 0 : eInvoiceFile(render, invoice, valid.eInvoice);
2442
3998
  if (problems.failed) return {
2443
3999
  ok: false,
2444
4000
  errors: problems.errors()
2445
4001
  };
2446
4002
  const { completeness, consistency } = checkedData.data;
2447
4003
  const warnings = problems.warnings();
2448
- const labelled = preview && (!completeness.complete || warnings.length > 0);
4004
+ const lacking = !completeness.complete || warnings.some(({ code }) => code !== "e-invoice-preview");
4005
+ const labelled = !preview ? void 0 : lacking ? PREVIEW_LABEL : invoice === void 0 ? void 0 : E_INVOICE_PREVIEW_LABEL;
2449
4006
  return {
2450
4007
  ok: true,
2451
4008
  document: {
@@ -2454,9 +4011,11 @@ function resolveReport(report, data, options) {
2454
4011
  creationDate
2455
4012
  },
2456
4013
  page: valid.page,
2457
- pageHeader: labelled ? [LABEL, ...regions.pageHeader] : regions.pageHeader,
4014
+ pageHeader: labelled === void 0 ? regions.pageHeader : [label(labelled), ...regions.pageHeader],
2458
4015
  pageFooter: regions.pageFooter,
2459
- body: regions.body
4016
+ body: regions.body,
4017
+ ...paymentPart === void 0 ? {} : { paymentPart },
4018
+ ...eInvoice === void 0 ? {} : { eInvoice }
2460
4019
  },
2461
4020
  manifest: {
2462
4021
  reportHash: reportHash(valid),
@@ -2472,6 +4031,6 @@ function resolveReport(report, data, options) {
2472
4031
  };
2473
4032
  }
2474
4033
  //#endregion
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 };
4034
+ export { 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_PREVIEW_LABEL, FACTUR_X, FACTUR_X_PROFILES, FORMAT_ERROR_CODES, IMAGE_REFUSAL_CODES, MAX_ASSET_BYTES, MAX_ASSET_SIDE, MAX_DATA_ERRORS, MAX_DETAIL_ROWS, MAX_FORMATTED_DIGITS, MAX_QR_BILL_ADDITIONAL_INFORMATION, MAX_STRING_LENGTH, MAX_SVG_BYTES, MAX_SVG_COORDINATE, MAX_SVG_DEPTH, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS, PREVIEW_LABEL, QR_BILL_CURRENCIES, QR_BILL_SIZE, QR_BILL_TOP, REFUSAL_CODES, RENDER_STEP_BUDGET, RESOLVE_ERROR_CODES, RenderRefusal, SVG_ELEMENTS, SVG_REFUSAL_CODES, VALUE_ERROR_CODES, averageDecimals, checkData, checkParameters, checkQrBillAmount, checkReport, checkSvg, cleanSvg, createFormatter, epcCaptionBreak, epcLeastVersion, epcModule, groupRows, imageHeader, maxDecimal, minDecimal, orderKeys, orderRows, orderTable, plainText, prepareExpressions, qrBillPageBreak, qrSymbolModules, readValue, resolveReport, roundDecimalAs, sniffImage, sumDecimals, supportedLocale };
2476
4035
 
2477
4036
  //# sourceMappingURL=index.mjs.map