@formancy/report-core 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,4 +1,4 @@
1
- import { DATASET_ROLES, EXPRESSION_NAMES, GROUP_KEY, REGION_NAMES, VALUE_SCOPES, componentAt, isIdentifier, reportHash, validateReport, walkComponents } from "@formancy/report-spec";
1
+ import { DATASET_ROLES, EXPRESSION_NAMES, E_INVOICE_DATES, E_INVOICE_DECIMALS, E_INVOICE_LINE_CODES, E_INVOICE_LINE_COLUMNS, E_INVOICE_NAMES, GROUP_KEY, INVOICE_TOTALS, QR_BILL_ADDRESS_RULES, REGION_NAMES, VALUE_SCOPES, VAT_BREAKDOWN, componentAt, isIdentifier, reportHash, validateReport, walkComponents } from "@formancy/report-spec";
2
2
  import { Decimal, compile, decimalFromString, parse, referencedPaths, rewritePath } from "@formancy/expressions";
3
3
  //#region src/outcome.ts
4
4
  /**
@@ -16,6 +16,7 @@ const REFUSAL_CODES = [
16
16
  "into-itself",
17
17
  "kind-mismatch",
18
18
  "immutable-property",
19
+ "already-declared",
19
20
  "unknown-command",
20
21
  "invalid-arguments",
21
22
  "invalid-document",
@@ -38,6 +39,39 @@ function quote(text) {
38
39
  return JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}...` : text);
39
40
  }
40
41
  //#endregion
42
+ //#region src/ids.ts
43
+ /**
44
+ * The ids new things take: a prefix itself when it is free, and otherwise
45
+ * the prefix numbered. One rule for a component the palette inserts, a
46
+ * copy a duplicate makes and an image a person adds (0033), so that the
47
+ * ids an author reads in the outline and in the report's images are made
48
+ * alike, and every one is an identifier the validator accepts. A copy is
49
+ * numbered from its original's base, `intro-2` copied being `intro-3`; a
50
+ * file's name is numbered as it stands, `img-4711` taken being `img-4711-2`.
51
+ */
52
+ /** The longest identifier the format allows: `isIdentifier`'s rule in report-spec, at most 64 characters. */
53
+ const IDENTIFIER_LENGTH = 64;
54
+ /** A trailing number an id was given to make it unique: `-2` in `intro-2`. */
55
+ const NUMBERED = /-\d+$/;
56
+ /** `prefix` if `taken` lacks it, otherwise `base` -- the prefix without a number it was given, unless one is said -- numbered from 2, within the identifier's length. */
57
+ function freshId(prefix, taken, base = prefix.replace(NUMBERED, "")) {
58
+ if (!taken.has(prefix)) return prefix;
59
+ for (let number = 2;; number += 1) {
60
+ const suffix = `-${number}`;
61
+ const id = `${base.slice(0, IDENTIFIER_LENGTH - suffix.length)}${suffix}`;
62
+ if (!taken.has(id)) return id;
63
+ }
64
+ }
65
+ /** A RangeError naming `said` when `prefix` is not an identifier, which would give an id the validator refuses. */
66
+ function checkPrefix(prefix, said = prefix) {
67
+ if (!isIdentifier(prefix)) throw new RangeError(`${quote(said)} is not an identifier: lower-case letters, digits and hyphens, starting with a letter`);
68
+ }
69
+ /** `freshId` of `prefix`, once `checkPrefix` has held it to the identifier rule. */
70
+ function nextId(prefix, taken, said = prefix) {
71
+ checkPrefix(prefix, said);
72
+ return freshId(prefix, taken);
73
+ }
74
+ //#endregion
41
75
  //#region src/lists.ts
42
76
  /**
43
77
  * Copy-on-write edits to lists and objects: the vocabulary every command is
@@ -108,6 +142,8 @@ function oneList() {
108
142
  const CONTAINERS = {
109
143
  text: void 0,
110
144
  image: void 0,
145
+ qrCode: void 0,
146
+ epcQrCode: void 0,
111
147
  line: void 0,
112
148
  rectangle: void 0,
113
149
  spacer: void 0,
@@ -218,10 +254,6 @@ function updateAt(report, pointer, update) {
218
254
  * outside the list is refused, never clamped, so that a keyboard move and a
219
255
  * pointer drop that name the same place do the same thing.
220
256
  */
221
- /** The longest identifier the format allows: `isIdentifier`'s rule in report-spec, at most 64 characters. */
222
- const IDENTIFIER_LENGTH = 64;
223
- /** A trailing number an id was given to make it unique: `-2` in `intro-2`. */
224
- const NUMBERED = /-\d+$/;
225
257
  function missing(id) {
226
258
  return refuse("not-found", `no component is ${quote(id)}`, { componentId: id });
227
259
  }
@@ -287,16 +319,6 @@ function updateComponent(report, id, kind, patch) {
287
319
  report: updateAt(report, found.path, (component) => patched(component, patch))
288
320
  };
289
321
  }
290
- /** `prefix` if no component has it, otherwise its base numbered from 2, within the identifier's length. */
291
- function freshId(prefix, taken) {
292
- if (!taken.has(prefix)) return prefix;
293
- const base = prefix.replace(NUMBERED, "");
294
- for (let number = 2;; number += 1) {
295
- const suffix = `-${number}`;
296
- const id = `${base.slice(0, IDENTIFIER_LENGTH - suffix.length)}${suffix}`;
297
- if (!taken.has(id)) return id;
298
- }
299
- }
300
322
  function idsOf(report) {
301
323
  return new Set(walkComponents(report).map(({ component }) => component.id));
302
324
  }
@@ -308,6 +330,8 @@ function idsOf(report) {
308
330
  const NAMED_AFTER = {
309
331
  text: "text",
310
332
  image: "image",
333
+ qrCode: "qr-code",
334
+ epcQrCode: "epc-qr-code",
311
335
  line: "line",
312
336
  rectangle: "rectangle",
313
337
  spacer: "spacer",
@@ -326,9 +350,7 @@ const NAMED_AFTER = {
326
350
  * validator refuses.
327
351
  */
328
352
  function nextComponentId(report, prefix) {
329
- const named = Object.hasOwn(NAMED_AFTER, prefix) ? NAMED_AFTER[prefix] : prefix;
330
- if (!isIdentifier(named)) throw new RangeError(`${quote(prefix)} is not an identifier: lower-case letters, digits and hyphens, starting with a letter`);
331
- return freshId(named, idsOf(report));
353
+ return nextId(Object.hasOwn(NAMED_AFTER, prefix) ? NAMED_AFTER[prefix] : prefix, idsOf(report), prefix);
332
354
  }
333
355
  /** A copy of `component` and all it holds, each given a fresh id, recorded in `taken` as it is given. */
334
356
  function renamed(component, taken) {
@@ -404,6 +426,26 @@ function moveParameter(report, id, index) {
404
426
  function putAsset(report, id, asset) {
405
427
  return withList(report, "assets", put(report.assets, id, asset));
406
428
  }
429
+ /** The asset appended under `id`; refused as `already-declared` when the report declares one under it already. */
430
+ function addAsset(report, id, asset) {
431
+ if (report.assets.some((existing) => existing.id === id)) return refuse("already-declared", `an asset is already declared as ${quote(id)}; an add never replaces one`, { path: "/assets" });
432
+ return withList(report, "assets", put(report.assets, id, asset));
433
+ }
434
+ /**
435
+ * An id no asset of `report` has, and none of `handed`: `base` itself when
436
+ * it is free, and otherwise `base-2`, `base-3` and so on, shortened so that
437
+ * its number fits, as a new component's is. The base is a file's name,
438
+ * folded, so a number it ends in is its own and is numbered too:
439
+ * `img-4711` taken gives `img-4711-2`. Assets are a namespace of their own
440
+ * (0007), so a component's id does not count; `handed` holds the ids a
441
+ * builder has handed a host already, which an undo may declare again for
442
+ * the bytes it handed under them (0033). Throws a RangeError for a base
443
+ * that is not an identifier.
444
+ */
445
+ function nextAssetId(report, base, handed = /* @__PURE__ */ new Set()) {
446
+ checkPrefix(base);
447
+ return freshId(base, /* @__PURE__ */ new Set([...handed, ...report.assets.map(({ id }) => id)]), base);
448
+ }
407
449
  function removeAsset(report, id) {
408
450
  return withList(report, "assets", remove(report.assets, id, "/assets", "asset"));
409
451
  }
@@ -735,6 +777,7 @@ const COMMANDS = Object.freeze({
735
777
  putParameter,
736
778
  removeParameter,
737
779
  moveParameter,
780
+ addAsset,
738
781
  putAsset,
739
782
  removeAsset,
740
783
  putAggregate,
@@ -831,6 +874,7 @@ const ARGUMENTS = {
831
874
  putParameter: ["text", "object"],
832
875
  removeParameter: ["text"],
833
876
  moveParameter: ["text", "index"],
877
+ addAsset: ["text", "object"],
834
878
  putAsset: ["text", "object"],
835
879
  removeAsset: ["text"],
836
880
  putAggregate: ["text", "object"],
@@ -1361,11 +1405,11 @@ const DIAGNOSTIC_SEVERITIES = {
1361
1405
  "expression-syntax": "error",
1362
1406
  /** An expression past a structural limit of `@formancy/expressions`: too deep, too many nodes, too long a list. */
1363
1407
  "expression-limit": "error",
1364
- /** An expression whose types do not meet, each member read as the type it is declared: an integer parameter added to a string, a decimal field compared with an integer, a decimal converted with dec() again. */
1408
+ /** An expression whose types do not meet, each member read as the type it is declared: an integer parameter added to a string, a decimal field compared with an integer, a decimal converted with dec() again; a QR-bill's or an EPC QR code's amount that gives anything but a decimal or null; or an e-invoice's date, paid amount or line term that gives what its term is not. */
1365
1409
  "expression-type": "error",
1366
1410
  /** An expression its place does not allow: a condition that is not a boolean, a function its kind forbids. */
1367
1411
  "expression-policy": "error",
1368
- /** An expression that reads a name, or a member of one, that nothing declares, or a member of a single value. */
1412
+ /** An expression that reads a name, or a member of one, that nothing declares, or a member of a single value; or an e-invoice's total where there is none, or where it is computed from. */
1369
1413
  "expression-unknown-name": "error",
1370
1414
  /** An expression that reads `row` or `group` where there is no row or group. */
1371
1415
  "expression-out-of-scope": "error",
@@ -1387,6 +1431,10 @@ const DIAGNOSTIC_SEVERITIES = {
1387
1431
  "format-rounds-again": "error",
1388
1432
  /** A rounding declared on an aggregate that computes an integer, a date or an instant, which have no places to round: the runtime refuses it. */
1389
1433
  "rounding-not-decimal": "error",
1434
+ /** A total an e-invoice's XML holds -- a document total, or a declared VAT category's basis or amount -- that no text or table of the page prints: the page would show another invoice than the one it carries. */
1435
+ "e-invoice-total-unprinted": "error",
1436
+ /** A format that prints what an e-invoice's XML holds otherwise: a total or a line's net amount at fewer than two places, or in another currency than the e-invoice's; a line's net price in another currency; a line's name in another case. The page would show another invoice than the one it carries. */
1437
+ "e-invoice-format-differs": "error",
1390
1438
  /** A print style nothing uses. */
1391
1439
  "unused-style": "warning",
1392
1440
  /** An asset nothing draws. */
@@ -1420,12 +1468,15 @@ function diagnostic(code, message, where) {
1420
1468
  /**
1421
1469
  * The parts of a report the diagnostics read: every expression, with the
1422
1470
  * scope its place gives it and what it is for, and every style, asset,
1423
- * field, parameter and aggregate named outside an expression.
1471
+ * field, parameter and aggregate named outside an expression -- in the
1472
+ * components, in the payment part and in the e-invoice.
1424
1473
  *
1425
1474
  * One walk, so that where an expression stands is decided once: the
1426
1475
  * diagnostics and `compileReport`, which the runtime compiles a report with,
1427
1476
  * both take its sites from here.
1428
1477
  */
1478
+ /** A run of one of an e-invoice's texts: text, whatever it computes. */
1479
+ const TEXT = { what: "a text of the e-invoice" };
1429
1480
  /** What one walk collects into, and the places it is collecting from. */
1430
1481
  var Collector = class {
1431
1482
  expressions = [];
@@ -1435,16 +1486,26 @@ var Collector = class {
1435
1486
  fields = [];
1436
1487
  parameters = [];
1437
1488
  aggregates = [];
1438
- expression(expression, path, scope, kind, owner = {}) {
1489
+ lines;
1490
+ constructor(lines) {
1491
+ this.lines = lines;
1492
+ }
1493
+ expression(expression, path, scope, kind, owner = {}, term, format) {
1439
1494
  if (expression === void 0) return;
1440
1495
  this.expressions.push({
1441
1496
  cel: expression.cel,
1442
1497
  scope,
1443
1498
  kind,
1444
1499
  path: `${path}/cel`,
1445
- ...owner
1500
+ ...owner,
1501
+ ...term === void 0 ? {} : { term },
1502
+ ...format === void 0 ? {} : { format }
1446
1503
  });
1447
1504
  }
1505
+ /** The term the column `column` of the table `table` prints of each line, when the e-invoice names it. */
1506
+ lineTerm(table, column) {
1507
+ return this.lines?.table === table ? this.lines.columns.get(column) : void 0;
1508
+ }
1448
1509
  style(style) {
1449
1510
  if (style !== void 0) this.styles.push(style);
1450
1511
  }
@@ -1460,7 +1521,7 @@ var Collector = class {
1460
1521
  if (format.currency.kind === "field") this.fields.push(format.currency.field);
1461
1522
  if (format.currency.kind === "parameter") this.parameters.push(format.currency.parameter);
1462
1523
  }
1463
- inline(inline, path, scope, owner) {
1524
+ inline(inline, path, scope, owner, term) {
1464
1525
  if (inline.kind === "field") this.fields.push(inline.field);
1465
1526
  if (inline.kind === "parameter") this.parameters.push(inline.parameter);
1466
1527
  if (inline.kind === "aggregate") this.aggregates.push(inline.aggregate);
@@ -1470,11 +1531,42 @@ var Collector = class {
1470
1531
  path: `${path}/format`,
1471
1532
  ...owner
1472
1533
  });
1473
- if (inline.kind === "expression") this.expression(inline.expression, `${path}/expression`, scope, "computed", owner);
1534
+ if (inline.kind === "expression") this.expression(inline.expression, `${path}/expression`, scope, "computed", owner, term, inline.format);
1474
1535
  if ("format" in inline) this.format(inline.format);
1475
1536
  }
1476
- inlines(inlines, path, scope, owner) {
1477
- for (const [index, inline] of inlines.entries()) this.inline(inline, `${path}/${index}`, scope, owner);
1537
+ inlines(inlines, path, scope, owner, term) {
1538
+ for (const [index, inline] of inlines.entries()) this.inline(inline, `${path}/${index}`, scope, owner, term);
1539
+ }
1540
+ /** A text of an e-invoice, read as a paragraph's in the report's scope; absent, it holds none. */
1541
+ invoiceText(inlines, path) {
1542
+ if (inlines !== void 0) this.inlines(inlines, path, "report", {}, TEXT);
1543
+ }
1544
+ /** A code read from each of an e-invoice's lines: a detail field, or an expression in the row's scope. */
1545
+ lineCode(value, path, term) {
1546
+ if (value.kind === "field") this.fields.push(value.field);
1547
+ else this.expression(value.expression, `${path}/expression`, "row", "computed", {}, term);
1548
+ }
1549
+ /** A payment code's amount: a value, read in the report's scope. */
1550
+ amount(expression, path, of, owner) {
1551
+ if (expression !== void 0) this.expressions.push({
1552
+ cel: expression.cel,
1553
+ scope: "report",
1554
+ kind: "computed",
1555
+ path: `${path}/cel`,
1556
+ ...owner,
1557
+ amount: of
1558
+ });
1559
+ }
1560
+ /** A text a code holds, read as a paragraph's in the report's scope; absent, it holds none. */
1561
+ optionalInlines(inlines, path, owner) {
1562
+ if (inlines !== void 0) this.inlines(inlines, path, "report", owner);
1563
+ }
1564
+ /** Each part of an address, in the order the code holds them; a party absent holds none. */
1565
+ address(address, path) {
1566
+ for (const part of Object.keys(QR_BILL_ADDRESS_RULES)) {
1567
+ const runs = address?.[part];
1568
+ if (runs !== void 0) this.inlines(runs, `${path}/${part}`, "report", {});
1569
+ }
1478
1570
  }
1479
1571
  footer(rows, path, scope, owner) {
1480
1572
  for (const [index, row] of (rows ?? []).entries()) {
@@ -1495,6 +1587,19 @@ const READERS = {
1495
1587
  if (image.source.kind === "asset") into.assets.push(image.source.asset);
1496
1588
  else into.fields.push(image.source.field);
1497
1589
  },
1590
+ qrCode: (code, path, into) => into.inlines(code.content, `${path}/content`, "report", { componentId: code.id }),
1591
+ epcQrCode: (code, path, into) => {
1592
+ const owner = { componentId: code.id };
1593
+ into.optionalInlines(code.bic, `${path}/bic`, owner);
1594
+ into.inlines(code.beneficiary, `${path}/beneficiary`, "report", owner);
1595
+ into.inlines(code.iban, `${path}/iban`, "report", owner);
1596
+ into.amount(code.amount, `${path}/amount`, "an EPC QR code", owner);
1597
+ for (const key of [
1598
+ "reference",
1599
+ "text",
1600
+ "information"
1601
+ ]) into.optionalInlines(code[key], `${path}/${key}`, owner);
1602
+ },
1498
1603
  line: NOTHING,
1499
1604
  rectangle: NOTHING,
1500
1605
  spacer: NOTHING,
@@ -1510,7 +1615,7 @@ const READERS = {
1510
1615
  componentId: table.id,
1511
1616
  columnId: column.id
1512
1617
  };
1513
- into.inline(column.value, `${at}/value`, "row", owner);
1618
+ into.inline(column.value, `${at}/value`, "row", owner, into.lineTerm(table.id, column.id));
1514
1619
  into.expression(column.visibleWhen, `${at}/visibleWhen`, "report", "visible", owner);
1515
1620
  into.style(column.style);
1516
1621
  into.rules(column.styleWhen, `${at}/styleWhen`, "row", owner);
@@ -1526,9 +1631,99 @@ const READERS = {
1526
1631
  into.footer(table.totals, `${path}/totals`, "report", owner);
1527
1632
  }
1528
1633
  };
1529
- /** Every expression and every name the report holds, in document order, the aggregates' expressions last. */
1634
+ /**
1635
+ * What each kind of payment part holds. A table over every kind, as
1636
+ * READERS is. A bill stands in no component: its texts are read as a
1637
+ * paragraph's in the report's scope, named by their paths alone, in the
1638
+ * order the code holds them.
1639
+ */
1640
+ const PAYMENT_PARTS = { swissQrBill: (bill, path, into) => {
1641
+ into.inlines(bill.account, `${path}/account`, "report", {});
1642
+ into.address(bill.creditor, `${path}/creditor`);
1643
+ into.amount(bill.amount, `${path}/amount`, "a QR-bill", {});
1644
+ into.address(bill.debtor, `${path}/debtor`);
1645
+ for (const key of [
1646
+ "reference",
1647
+ "message",
1648
+ "billingInformation"
1649
+ ]) into.optionalInlines(bill[key], `${path}/${key}`, {});
1650
+ } };
1651
+ /** A date term: a date, read as its ISO string, as a date field is. */
1652
+ const date = (term) => ({
1653
+ what: E_INVOICE_DATES[term].what,
1654
+ types: ["date"]
1655
+ });
1656
+ /** The keys of a table over every key of `T`: one added to the format without being read here does not compile. */
1657
+ const keysOf = (table) => Object.keys(table);
1658
+ /** The texts of each party and of its address, and of the payment instructions, in the order the type holds them. */
1659
+ const SELLER_TEXTS = keysOf({
1660
+ name: true,
1661
+ vatId: true,
1662
+ taxNumber: true
1663
+ });
1664
+ const BUYER_TEXTS = keysOf({
1665
+ name: true,
1666
+ vatId: true
1667
+ });
1668
+ const ADDRESS_TEXTS = keysOf({
1669
+ line1: true,
1670
+ line2: true,
1671
+ postalCode: true,
1672
+ city: true,
1673
+ country: true
1674
+ });
1675
+ const PAYMENT_TEXTS = keysOf({
1676
+ iban: true,
1677
+ bic: true,
1678
+ accountName: true,
1679
+ remittance: true
1680
+ });
1681
+ /** A party's texts, its legal registration's and its address's, in the order the type holds them. */
1682
+ function party(held, texts, path, into) {
1683
+ for (const key of texts) into.invoiceText(held[key], `${path}/${String(key)}`);
1684
+ into.invoiceText(held.legalId?.id, `${path}/legalId/id`);
1685
+ for (const part of ADDRESS_TEXTS) into.invoiceText(held.address[part], `${path}/address/${part}`);
1686
+ }
1687
+ /**
1688
+ * What each kind of e-invoice holds. A table over every kind, as
1689
+ * PAYMENT_PARTS is. An e-invoice stands in no component: its texts are
1690
+ * read as a paragraph's in the report's scope, its dates and its paid
1691
+ * amount as values there, and its line codes in each row's, as what an
1692
+ * aggregate reads from each row is; each is named by its path alone, in
1693
+ * the order the type holds them. The columns its lines are printed by are
1694
+ * read where they stand, in the table.
1695
+ */
1696
+ const E_INVOICES = { facturX: (invoice, path, into) => {
1697
+ into.invoiceText(invoice.number, `${path}/number`);
1698
+ into.expression(invoice.issued, `${path}/issued`, "report", "computed", {}, date("BT-2"));
1699
+ party(invoice.seller, SELLER_TEXTS, `${path}/seller`, into);
1700
+ party(invoice.buyer, BUYER_TEXTS, `${path}/buyer`, into);
1701
+ into.invoiceText(invoice.buyerReference, `${path}/buyerReference`);
1702
+ into.expression(invoice.delivered, `${path}/delivered`, "report", "computed", {}, date("BT-72"));
1703
+ into.expression(invoice.period?.start, `${path}/period/start`, "report", "computed", {}, date("BT-73"));
1704
+ into.expression(invoice.period?.end, `${path}/period/end`, "report", "computed", {}, date("BT-74"));
1705
+ for (const [index, category] of invoice.vat.entries()) into.invoiceText(category.reason, `${path}/vat/${index}/reason`);
1706
+ for (const key of Object.keys(E_INVOICE_LINE_CODES)) into.lineCode(invoice.lines[key], `${path}/lines/${key}`, E_INVOICE_LINE_CODES[key]);
1707
+ for (const key of PAYMENT_TEXTS) into.invoiceText(invoice.payment?.[key], `${path}/payment/${key}`);
1708
+ into.expression(invoice.due, `${path}/due`, "report", "computed", {}, date("BT-9"));
1709
+ into.invoiceText(invoice.terms, `${path}/terms`);
1710
+ into.expression(invoice.paid, `${path}/paid`, "report", "computed", {}, {
1711
+ what: E_INVOICE_DECIMALS["BT-113"].what,
1712
+ types: ["decimal"]
1713
+ });
1714
+ } };
1715
+ /** The table an e-invoice's lines are the rows of, and the term each column it names prints. */
1716
+ function lineColumns(invoice) {
1717
+ if (invoice === void 0) return void 0;
1718
+ const named = Object.keys(E_INVOICE_LINE_COLUMNS);
1719
+ return {
1720
+ table: invoice.lines.table,
1721
+ columns: new Map(named.map((key) => [invoice.lines[key], E_INVOICE_LINE_COLUMNS[key]]))
1722
+ };
1723
+ }
1724
+ /** Every expression and every name the report holds, in document order -- the components, the payment part, the e-invoice -- the aggregates' expressions last. */
1530
1725
  function reportParts(report) {
1531
- const into = new Collector();
1726
+ const into = new Collector(lineColumns(report.eInvoice));
1532
1727
  for (const { component, path } of walkComponents(report)) {
1533
1728
  const owner = { componentId: component.id };
1534
1729
  into.expression(component.visibleWhen, `${path}/visibleWhen`, "report", "visible", owner);
@@ -1536,6 +1731,8 @@ function reportParts(report) {
1536
1731
  into.rules(component.styleWhen, `${path}/styleWhen`, "report", owner);
1537
1732
  READERS[component.kind](component, path, into);
1538
1733
  }
1734
+ if (report.paymentPart !== void 0) PAYMENT_PARTS[report.paymentPart.kind](report.paymentPart, "/paymentPart", into);
1735
+ if (report.eInvoice !== void 0) E_INVOICES[report.eInvoice.kind](report.eInvoice, "/eInvoice", into);
1539
1736
  for (const [index, aggregate] of report.aggregates.entries()) {
1540
1737
  if (aggregate.of?.kind === "field") into.fields.push(aggregate.of.field);
1541
1738
  if (aggregate.of?.kind === "expression") into.expression(aggregate.of.expression, `/aggregates/${index}/of/expression`, "row", "computed");
@@ -1547,6 +1744,238 @@ function expressionSites(report) {
1547
1744
  return reportParts(report).expressions;
1548
1745
  }
1549
1746
  //#endregion
1747
+ //#region src/expressions/members.ts
1748
+ /**
1749
+ * The type an expression reads each readable field and parameter type as.
1750
+ *
1751
+ * - Exact numbers keep their exactness: an integer is `int`, a decimal
1752
+ * `decimal`, never a double.
1753
+ * - A `date` and a `datetime` are read as their ISO strings. Neither has a
1754
+ * zone, and a CEL timestamp is an instant: making one from a date would
1755
+ * need a zone the report does not have, and `@formancy/expressions`
1756
+ * refuses to guess one. Their ISO forms compare in calendar order.
1757
+ * - An `instant` has a zone, so it is a `timestamp`.
1758
+ * - An `image` is not readable: its value is an asset id, which is drawn,
1759
+ * never printed or computed with (0007).
1760
+ */
1761
+ const EXPRESSION_TYPES = {
1762
+ string: "string",
1763
+ integer: "int",
1764
+ decimal: "decimal",
1765
+ boolean: "bool",
1766
+ date: "string",
1767
+ datetime: "string",
1768
+ instant: "timestamp"
1769
+ };
1770
+ /** Every name the format binds, in some scope or in an e-invoice. A test holds this to the union of `EXPRESSION_NAMES` and `E_INVOICE_NAMES`. */
1771
+ const SCOPE_NAMES = [
1772
+ "params",
1773
+ "header",
1774
+ "row",
1775
+ "totals",
1776
+ "group",
1777
+ "invoice",
1778
+ "vatBasis",
1779
+ "vatAmount"
1780
+ ];
1781
+ /** The type a field of `type` is read as; undefined for an image, which is not read. */
1782
+ function readAs(type) {
1783
+ return type === void 0 || type === "image" ? void 0 : EXPRESSION_TYPES[type];
1784
+ }
1785
+ function fieldsOf(dataset) {
1786
+ const members = /* @__PURE__ */ new Map();
1787
+ for (const field of dataset?.fields ?? []) {
1788
+ const type = readAs(field.type);
1789
+ if (type !== void 0) members.set(field.id, {
1790
+ type,
1791
+ nullable: field.nullable
1792
+ });
1793
+ }
1794
+ return members;
1795
+ }
1796
+ function parametersOf(report) {
1797
+ return new Map(report.parameters.map((parameter) => [parameter.id, {
1798
+ type: EXPRESSION_TYPES[parameter.type],
1799
+ nullable: !parameter.required && parameter.default === void 0
1800
+ }]));
1801
+ }
1802
+ /**
1803
+ * `group.key`, the value the report's group is keyed by: the field grouped
1804
+ * by, read as its type and null where it may be, since the rows without a
1805
+ * value are a group of their own. Undefined when the report's table does
1806
+ * not group, or groups by a field nothing can read.
1807
+ */
1808
+ function groupKeyOf(report) {
1809
+ for (const { component } of walkComponents(report)) {
1810
+ if (component.kind !== "table" || component.group === void 0) continue;
1811
+ const by = component.group.by.field;
1812
+ const field = report.datasets.detail?.fields.find(({ id }) => id === by);
1813
+ const type = readAs(field?.type);
1814
+ return field === void 0 || type === void 0 ? void 0 : [GROUP_KEY, {
1815
+ type,
1816
+ nullable: field.nullable
1817
+ }];
1818
+ }
1819
+ }
1820
+ /** The image fields of a dataset: drawn, and never read as a value. */
1821
+ function imagesOf(dataset) {
1822
+ return new Set((dataset?.fields ?? []).filter(({ type }) => type === "image").map(({ id }) => id));
1823
+ }
1824
+ /**
1825
+ * The types each function totals (0007), for an aggregate over an
1826
+ * expression; one over a field the validator has already checked. A sum and
1827
+ * an average take integers and decimals; a minimum and a maximum those,
1828
+ * instants, and dates and date-times as the ISO strings they are read as; a
1829
+ * count counts what is not null, whatever it is. `dyn` -- a value that may
1830
+ * be null -- is taken by all of them: what it holds is known only at render.
1831
+ */
1832
+ const TOTALS = {
1833
+ count: "any",
1834
+ sum: /* @__PURE__ */ new Set([
1835
+ "int",
1836
+ "decimal",
1837
+ "dyn"
1838
+ ]),
1839
+ avg: /* @__PURE__ */ new Set([
1840
+ "int",
1841
+ "decimal",
1842
+ "dyn"
1843
+ ]),
1844
+ min: /* @__PURE__ */ new Set([
1845
+ "int",
1846
+ "decimal",
1847
+ "timestamp",
1848
+ "string",
1849
+ "dyn"
1850
+ ]),
1851
+ max: /* @__PURE__ */ new Set([
1852
+ "int",
1853
+ "decimal",
1854
+ "timestamp",
1855
+ "string",
1856
+ "dyn"
1857
+ ])
1858
+ };
1859
+ /**
1860
+ * What each function computes from what it reads (0007): a count is an
1861
+ * integer and an average a decimal; a sum, minimum or maximum is the type it
1862
+ * read, `dyn` when that is not known. Over no rows, a count and a sum are 0
1863
+ * and the others null.
1864
+ */
1865
+ const COMPUTES = {
1866
+ count: () => ({
1867
+ type: "int",
1868
+ nullable: false
1869
+ }),
1870
+ sum: (read) => ({
1871
+ type: read ?? "dyn",
1872
+ nullable: false
1873
+ }),
1874
+ avg: () => ({
1875
+ type: "decimal",
1876
+ nullable: true
1877
+ }),
1878
+ min: (read) => ({
1879
+ type: read ?? "dyn",
1880
+ nullable: true
1881
+ }),
1882
+ max: (read) => ({
1883
+ type: read ?? "dyn",
1884
+ nullable: true
1885
+ })
1886
+ };
1887
+ //#endregion
1888
+ //#region src/expressions/e-invoice.ts
1889
+ /** A document total: computed over every line, 0.00 over none. */
1890
+ const TOTAL = {
1891
+ type: "decimal",
1892
+ nullable: false
1893
+ };
1894
+ /** A category's basis or amount: null when no line is in it. */
1895
+ const BREAKDOWN = {
1896
+ type: "decimal",
1897
+ nullable: true
1898
+ };
1899
+ /**
1900
+ * What each name holds in a report whose e-invoice is `invoice`, its paid
1901
+ * amount read as `paid`; nothing in a report that is none. The totals in
1902
+ * report-spec's order, the categories in the order the e-invoice declares
1903
+ * them.
1904
+ */
1905
+ function invoiceMembers(invoice, paid) {
1906
+ if (invoice === void 0) return {
1907
+ invoice: /* @__PURE__ */ new Map(),
1908
+ vatBasis: /* @__PURE__ */ new Map(),
1909
+ vatAmount: /* @__PURE__ */ new Map()
1910
+ };
1911
+ const totals = Object.keys(INVOICE_TOTALS).flatMap((id) => {
1912
+ if (id !== "paid") return [[id, TOTAL]];
1913
+ return paid === void 0 ? [] : [[id, paid]];
1914
+ });
1915
+ const categories = () => new Map(invoice.vat.map(({ id }) => [id, BREAKDOWN]));
1916
+ return {
1917
+ invoice: new Map(totals),
1918
+ vatBasis: categories(),
1919
+ vatAmount: categories()
1920
+ };
1921
+ }
1922
+ /**
1923
+ * What `invoice.paid` is read as, from how the e-invoice's paid amount
1924
+ * compiled: a decimal, null where the expression may give null. One that
1925
+ * did not compile has no type anyone could check a read of: it is read as
1926
+ * a value that may be anything, so its fault is reported once, where it is.
1927
+ */
1928
+ function paidMember(outcome) {
1929
+ if (!outcome.ok) return {
1930
+ type: "dyn",
1931
+ nullable: true
1932
+ };
1933
+ return {
1934
+ type: "decimal",
1935
+ nullable: outcome.compiled.program.resultType !== "decimal"
1936
+ };
1937
+ }
1938
+ /**
1939
+ * Why the expression at `site` cannot read the e-invoice's names, said
1940
+ * after the name; undefined where it can. `invoiced` says whether the
1941
+ * report is an e-invoice.
1942
+ */
1943
+ function invoiceRefusal(site, invoiced) {
1944
+ if (!invoiced) return "has a value only in a report that is an e-invoice, and this report is none";
1945
+ if (site.path.startsWith("/aggregates/")) return "holds what the e-invoice computes after every aggregate, and an aggregate's expression cannot read it";
1946
+ if (site.term === void 0) return void 0;
1947
+ return `holds the totals the e-invoice computes from its lines, and ${site.columnId === void 0 ? site.term.what : `the column that prints ${site.term.what}`} is part of what they are computed from or written with: it cannot read them`;
1948
+ }
1949
+ /** What a field of each type is, as a message says it. */
1950
+ const SAID = {
1951
+ string: "a text",
1952
+ integer: "an integer",
1953
+ decimal: "a decimal",
1954
+ boolean: "a boolean",
1955
+ date: "a date, read as its ISO string",
1956
+ datetime: "a date and a time",
1957
+ instant: "an instant",
1958
+ image: "an image"
1959
+ };
1960
+ /**
1961
+ * What breaks the term of the expression at `site`, which gives `type`; or
1962
+ * undefined, when it has no term of a type or gives one the term takes. A
1963
+ * term takes what an expression reads each type of field it may be as,
1964
+ * and a value that may be null, checked as `dyn`, which the render checks
1965
+ * again once it holds the value. A date is taken as the ISO string a date
1966
+ * field is read as, so whether a text is a date is the render's to say.
1967
+ */
1968
+ function termBreak(site, type) {
1969
+ const term = site.term;
1970
+ if (term?.types === void 0) return void 0;
1971
+ if ((/* @__PURE__ */ new Set(["dyn", ...term.types.map((field) => readAs(field))])).has(type)) return void 0;
1972
+ const what = `${term.what} is ${term.types.map((field) => SAID[field]).join(" or ")}, and ${site.columnId === void 0 ? "this expression" : "this column's value"} gives ${type}`;
1973
+ return term.types.length === 1 && term.types[0] === "decimal" && (type === "int" || type === "string") ? {
1974
+ message: what,
1975
+ hint: "dec() makes a decimal of an integer, or of a string of digits"
1976
+ } : { message: what };
1977
+ }
1978
+ //#endregion
1550
1979
  //#region src/expressions/reproducible.ts
1551
1980
  /**
1552
1981
  * Calls a report expression may not make: the clock and a random draw.
@@ -1772,9 +2201,9 @@ function readSpans(source, path) {
1772
2201
  * One expression compiled where it stands, with every member it reads
1773
2202
  * checked as the type it is.
1774
2203
  *
1775
- * `@formancy/expressions` 0.5.0 declares a variable only by its whole name:
1776
- * a declaration of `row.amount` is a variable with a dot in its name, which
1777
- * an expression reading `row.amount` never finds. So each read of a member
2204
+ * `@formancy/expressions` 0.6.0, as 0.5.0, declares a variable only by its
2205
+ * whole name: a declaration of `row.amount` is a variable with a dot in its
2206
+ * name, which an expression reading `row.amount` never finds. So each read of a member
1778
2207
  * is spliced, by upstream's own `rewritePath`, which verifies every splice
1779
2208
  * by parsing the result again, into a read of one variable -- `row.amount`
1780
2209
  * becomes `row_amount` -- declared with the member's type. The real checker
@@ -1785,8 +2214,11 @@ function readSpans(source, path) {
1785
2214
  *
1786
2215
  * What a scope does not bind, a member nothing declares, a member of a
1787
2216
  * single value and an image field read as a value are found first, from
1788
- * the paths the parser says the expression reads. The clock and a random
1789
- * draw, which the compiler allows, are refused last (plan 15).
2217
+ * the paths the parser says the expression reads; so is an e-invoice's
2218
+ * total read where it cannot be (`e-invoice.ts`). The clock and a random
2219
+ * draw, which the compiler allows, are refused last (plan 15), and then
2220
+ * what its place needs it to give: a payment code's amount, an
2221
+ * e-invoice's term.
1790
2222
  */
1791
2223
  /**
1792
2224
  * The code for each kind of error the compiler gives. It gives the first
@@ -1813,7 +2245,10 @@ const MEMBERS_ARE = {
1813
2245
  header: "field of the header dataset",
1814
2246
  row: "field of the detail dataset",
1815
2247
  totals: "aggregate",
1816
- group: "aggregate"
2248
+ group: "aggregate",
2249
+ invoice: "total of the e-invoice",
2250
+ vatBasis: "VAT category of the e-invoice",
2251
+ vatAmount: "VAT category of the e-invoice"
1817
2252
  };
1818
2253
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
1819
2254
  /**
@@ -1856,13 +2291,23 @@ function eachRead(site, path, code, message) {
1856
2291
  const spans = readSpans(site.cel, path);
1857
2292
  return spans.length === 0 ? [diagnostic(code, message, at(site))] : spans.map((span) => diagnostic(code, message, at(site, span)));
1858
2293
  }
1859
- /** The diagnostics for a read of `path` that the scope's names and their members do not allow; none for one they do. */
1860
- function readProblems(site, path, members, images) {
2294
+ const INVOICE_NAMES = E_INVOICE_NAMES;
2295
+ /** The names `site` reads, in a report that is an e-invoice when `invoiced` says so. */
2296
+ function namesAt(site, invoiced) {
2297
+ const refusal = invoiceRefusal(site, invoiced);
2298
+ return {
2299
+ names: refusal === void 0 ? [...EXPRESSION_NAMES[site.scope], ...INVOICE_NAMES] : EXPRESSION_NAMES[site.scope],
2300
+ refusal
2301
+ };
2302
+ }
2303
+ /** The diagnostics for a read of `path` that the site's names and their members do not allow; none for one they do. */
2304
+ function readProblems(site, path, members, images, { names, refusal }) {
1861
2305
  const { name, member, rest } = pathParts(path);
1862
- if (!EXPRESSION_NAMES[site.scope].includes(name)) {
2306
+ if (refusal !== void 0 && INVOICE_NAMES.includes(name)) return eachRead(site, name, "expression-unknown-name", `${name} ${refusal}`);
2307
+ if (!names.includes(name)) {
1863
2308
  const scopes = VALUE_SCOPES.filter((scope) => EXPRESSION_NAMES[scope].includes(name));
1864
2309
  if (scopes.length > 0) return eachRead(site, name, "expression-out-of-scope", `${name} has a value only in ${scopes.map((scope) => WHERE[scope]).join(" and ")}`);
1865
- return eachRead(site, name, "expression-unknown-name", `${quote(name)} is not a name an expression reads; here it reads ${EXPRESSION_NAMES[site.scope].join(", ")}`);
2310
+ return eachRead(site, name, "expression-unknown-name", `${quote(name)} is not a name an expression reads; here it reads ${names.join(", ")}`);
1866
2311
  }
1867
2312
  if (rest === "" && member === void 0) return [];
1868
2313
  const scoped = name;
@@ -1915,25 +2360,28 @@ function refused(site, error, source, reads) {
1915
2360
  * since every read of a member by its id is spliced away. Positions only
1916
2361
  * when `source` is the author's, character for character.
1917
2362
  */
1918
- function wholeReads(site, paths, source) {
2363
+ function wholeReads(site, paths, source, names) {
1919
2364
  const exact = source.length === site.cel.length;
1920
- return paths.filter((path) => EXPRESSION_NAMES[site.scope].includes(path)).flatMap((name) => readSpans(source, name).map((span) => diagnostic("expression-dynamic-read", `${name} is read whole; an expression reads each ${MEMBERS_ARE[name]} by its id, as ${name}.<id>`, at(site, exact ? span : void 0))));
2365
+ return paths.filter((path) => names.includes(path)).flatMap((name) => readSpans(source, name).map((span) => diagnostic("expression-dynamic-read", `${name} is read whole; an expression reads each ${MEMBERS_ARE[name]} by its id, as ${name}.<id>`, at(site, exact ? span : void 0))));
1921
2366
  }
1922
2367
  /**
1923
- * `site` compiled against what its scope binds in this report, or every
1924
- * reason it cannot be: a read its scope does not allow, each where it is;
1925
- * the compiler's first error; or each call to the clock or a random draw.
2368
+ * `site` compiled against what its scope binds in this report -- a report
2369
+ * that is an e-invoice when `invoiced` says so -- or every reason it
2370
+ * cannot be: a read its scope does not allow, each where it is; the
2371
+ * compiler's first error; each call to the clock or a random draw; or a
2372
+ * value its place does not take.
1926
2373
  */
1927
- function compileSite(site, members, images) {
2374
+ function compileSite(site, members, images, invoiced) {
1928
2375
  const parsed = parse(site.cel);
1929
2376
  if (!parsed.ok) return failed([refused(site, parsed.error, site.cel, [])]);
1930
2377
  const paths = referencedPaths(parsed.ast);
1931
- const problems = paths.flatMap((path) => readProblems(site, path, members, images));
2378
+ const names = namesAt(site, invoiced);
2379
+ const problems = paths.flatMap((path) => readProblems(site, path, members, images, names));
1932
2380
  if (problems.length > 0) return failed(problems);
1933
2381
  const reads = readsOf$1(paths, members);
1934
2382
  const flat = flattened(site, reads);
1935
2383
  if (!("source" in flat)) return failed([flat]);
1936
- const whole = wholeReads(site, paths, flat.source);
2384
+ const whole = wholeReads(site, paths, flat.source, names.names);
1937
2385
  if (whole.length > 0) return failed(whole);
1938
2386
  const variables = Object.fromEntries(reads.map((read) => [read.variable, read.nullable ? "dyn" : read.type]));
1939
2387
  const compiled = compile(flat.source, {
@@ -1949,6 +2397,13 @@ function compileSite(site, members, images) {
1949
2397
  }
1950
2398
  const inexact = [...inexactOperations(flat.source, site.kind, variables).map(({ kind, span }) => diagnostic("expression-inexact", INEXACT[kind].message, at(site, exact ? span : void 0, INEXACT[kind].hint))), ...unboundedCalls(flat.source, site.kind, variables).map(({ name, span }) => diagnostic("expression-unbounded", UNBOUNDED(name), at(site, exact ? span : void 0)))].sort((a, b) => (a.position?.start ?? 0) - (b.position?.start ?? 0));
1951
2399
  if (inexact.length > 0) return failed(inexact);
2400
+ const type = compiled.program.resultType;
2401
+ if (site.amount !== void 0 && !AMOUNTS.has(type)) {
2402
+ const hint = type === "int" || type === "string" ? "dec() makes a decimal of an integer, or of a string of digits" : void 0;
2403
+ return failed([diagnostic("expression-type", `${site.amount}'s amount is a decimal, or null to leave it for the payer, and this expression gives ${type}`, at(site, void 0, hint))]);
2404
+ }
2405
+ const broken = termBreak(site, type);
2406
+ if (broken !== void 0) return failed([diagnostic("expression-type", broken.message, at(site, void 0, broken.hint))]);
1952
2407
  return {
1953
2408
  ok: true,
1954
2409
  compiled: {
@@ -1958,6 +2413,17 @@ function compileSite(site, members, images) {
1958
2413
  }
1959
2414
  };
1960
2415
  }
2416
+ /**
2417
+ * What a payment code's amount -- a QR-bill's, an EPC QR code's -- may
2418
+ * give: one rule for both. A decimal, null, or a value that may be
2419
+ * either -- a decimal that may be null is checked as `dyn` -- which the
2420
+ * render, seeing the value, checks again.
2421
+ */
2422
+ const AMOUNTS = /* @__PURE__ */ new Set([
2423
+ "decimal",
2424
+ "null",
2425
+ "dyn"
2426
+ ]);
1961
2427
  /** What to say of each inexact operation, and what to write instead. */
1962
2428
  const INEXACT = {
1963
2429
  "double-literal": {
@@ -2040,144 +2506,6 @@ function cycleDiagnostic(id, site, reads, unordered) {
2040
2506
  });
2041
2507
  }
2042
2508
  //#endregion
2043
- //#region src/expressions/members.ts
2044
- /**
2045
- * The type an expression reads each readable field and parameter type as.
2046
- *
2047
- * - Exact numbers keep their exactness: an integer is `int`, a decimal
2048
- * `decimal`, never a double.
2049
- * - A `date` and a `datetime` are read as their ISO strings. Neither has a
2050
- * zone, and a CEL timestamp is an instant: making one from a date would
2051
- * need a zone the report does not have, and `@formancy/expressions`
2052
- * refuses to guess one. Their ISO forms compare in calendar order.
2053
- * - An `instant` has a zone, so it is a `timestamp`.
2054
- * - An `image` is not readable: its value is an asset id, which is drawn,
2055
- * never printed or computed with (0007).
2056
- */
2057
- const EXPRESSION_TYPES = {
2058
- string: "string",
2059
- integer: "int",
2060
- decimal: "decimal",
2061
- boolean: "bool",
2062
- date: "string",
2063
- datetime: "string",
2064
- instant: "timestamp"
2065
- };
2066
- /** Every name the format binds, in some scope. A test holds this to the union of `EXPRESSION_NAMES`. */
2067
- const SCOPE_NAMES = [
2068
- "params",
2069
- "header",
2070
- "row",
2071
- "totals",
2072
- "group"
2073
- ];
2074
- /** The type a field of `type` is read as; undefined for an image, which is not read. */
2075
- function readAs(type) {
2076
- return type === void 0 || type === "image" ? void 0 : EXPRESSION_TYPES[type];
2077
- }
2078
- function fieldsOf(dataset) {
2079
- const members = /* @__PURE__ */ new Map();
2080
- for (const field of dataset?.fields ?? []) {
2081
- const type = readAs(field.type);
2082
- if (type !== void 0) members.set(field.id, {
2083
- type,
2084
- nullable: field.nullable
2085
- });
2086
- }
2087
- return members;
2088
- }
2089
- function parametersOf(report) {
2090
- return new Map(report.parameters.map((parameter) => [parameter.id, {
2091
- type: EXPRESSION_TYPES[parameter.type],
2092
- nullable: !parameter.required && parameter.default === void 0
2093
- }]));
2094
- }
2095
- /**
2096
- * `group.key`, the value the report's group is keyed by: the field grouped
2097
- * by, read as its type and null where it may be, since the rows without a
2098
- * value are a group of their own. Undefined when the report's table does
2099
- * not group, or groups by a field nothing can read.
2100
- */
2101
- function groupKeyOf(report) {
2102
- for (const { component } of walkComponents(report)) {
2103
- if (component.kind !== "table" || component.group === void 0) continue;
2104
- const by = component.group.by.field;
2105
- const field = report.datasets.detail?.fields.find(({ id }) => id === by);
2106
- const type = readAs(field?.type);
2107
- return field === void 0 || type === void 0 ? void 0 : [GROUP_KEY, {
2108
- type,
2109
- nullable: field.nullable
2110
- }];
2111
- }
2112
- }
2113
- /** The image fields of a dataset: drawn, and never read as a value. */
2114
- function imagesOf(dataset) {
2115
- return new Set((dataset?.fields ?? []).filter(({ type }) => type === "image").map(({ id }) => id));
2116
- }
2117
- /**
2118
- * The types each function totals (0007), for an aggregate over an
2119
- * expression; one over a field the validator has already checked. A sum and
2120
- * an average take integers and decimals; a minimum and a maximum those,
2121
- * instants, and dates and date-times as the ISO strings they are read as; a
2122
- * count counts what is not null, whatever it is. `dyn` -- a value that may
2123
- * be null -- is taken by all of them: what it holds is known only at render.
2124
- */
2125
- const TOTALS = {
2126
- count: "any",
2127
- sum: /* @__PURE__ */ new Set([
2128
- "int",
2129
- "decimal",
2130
- "dyn"
2131
- ]),
2132
- avg: /* @__PURE__ */ new Set([
2133
- "int",
2134
- "decimal",
2135
- "dyn"
2136
- ]),
2137
- min: /* @__PURE__ */ new Set([
2138
- "int",
2139
- "decimal",
2140
- "timestamp",
2141
- "string",
2142
- "dyn"
2143
- ]),
2144
- max: /* @__PURE__ */ new Set([
2145
- "int",
2146
- "decimal",
2147
- "timestamp",
2148
- "string",
2149
- "dyn"
2150
- ])
2151
- };
2152
- /**
2153
- * What each function computes from what it reads (0007): a count is an
2154
- * integer and an average a decimal; a sum, minimum or maximum is the type it
2155
- * read, `dyn` when that is not known. Over no rows, a count and a sum are 0
2156
- * and the others null.
2157
- */
2158
- const COMPUTES = {
2159
- count: () => ({
2160
- type: "int",
2161
- nullable: false
2162
- }),
2163
- sum: (read) => ({
2164
- type: read ?? "dyn",
2165
- nullable: false
2166
- }),
2167
- avg: () => ({
2168
- type: "decimal",
2169
- nullable: true
2170
- }),
2171
- min: (read) => ({
2172
- type: read ?? "dyn",
2173
- nullable: true
2174
- }),
2175
- max: (read) => ({
2176
- type: read ?? "dyn",
2177
- nullable: true
2178
- })
2179
- };
2180
- //#endregion
2181
2509
  //#region src/expressions/compile-report.ts
2182
2510
  /** The CEL types a member can be declared as, of all the types an expression can give. */
2183
2511
  const SCALARS = /* @__PURE__ */ new Set([
@@ -2189,6 +2517,8 @@ const SCALARS = /* @__PURE__ */ new Set([
2189
2517
  "timestamp",
2190
2518
  "dyn"
2191
2519
  ]);
2520
+ /** Where an e-invoice's paid amount stands: `invoice.paid` is what it gives. */
2521
+ const PAID = "/eInvoice/paid/cel";
2192
2522
  /** Every expression in `report` -- a report the validator accepts -- compiled where it stands. */
2193
2523
  function compileReport(report) {
2194
2524
  return compiledSites(report, expressionSites(report));
@@ -2205,10 +2535,12 @@ function compiledSites(report, sites) {
2205
2535
  const { order, unordered } = aggregateOrder(report, reads);
2206
2536
  const cyclic = new Set(unordered);
2207
2537
  const known = /* @__PURE__ */ new Map();
2538
+ const invoiced = report.eInvoice !== void 0;
2208
2539
  const base = {
2209
2540
  params: parametersOf(report),
2210
2541
  header: fieldsOf(report.datasets.header),
2211
- row: fieldsOf(report.datasets.detail)
2542
+ row: fieldsOf(report.datasets.detail),
2543
+ ...invoiceMembers(void 0, void 0)
2212
2544
  };
2213
2545
  const outcomes = /* @__PURE__ */ new Map();
2214
2546
  /** What `aggregate` computes, its expression compiled against the totals before it; and why it cannot be computed, when it cannot. */
@@ -2222,7 +2554,7 @@ function compiledSites(report, sites) {
2222
2554
  ...base,
2223
2555
  totals: known,
2224
2556
  group: known
2225
- }, images);
2557
+ }, images, invoiced);
2226
2558
  outcomes.set(site.path, outcome);
2227
2559
  if (!outcome.ok) return COMPUTES[aggregate.fn](void 0);
2228
2560
  const result = outcome.compiled.program.resultType;
@@ -2245,15 +2577,24 @@ function compiledSites(report, sites) {
2245
2577
  });
2246
2578
  const totals = new Map(report.aggregates.map(({ id }) => [id, known.get(id)]));
2247
2579
  const key = groupKeyOf(report);
2580
+ const group = key === void 0 ? totals : new Map([...totals, key]);
2581
+ const paid = byPath.get(PAID);
2582
+ const paidOutcome = paid === void 0 ? void 0 : compileSite(paid, {
2583
+ ...base,
2584
+ totals,
2585
+ group
2586
+ }, images, invoiced);
2587
+ if (paidOutcome !== void 0) outcomes.set(PAID, paidOutcome);
2248
2588
  const members = {
2249
2589
  ...base,
2250
2590
  totals,
2251
- group: key === void 0 ? totals : new Map([...totals, key])
2591
+ group,
2592
+ ...invoiceMembers(report.eInvoice, paidOutcome === void 0 ? void 0 : paidMember(paidOutcome))
2252
2593
  };
2253
2594
  const expressions = /* @__PURE__ */ new Map();
2254
2595
  const diagnostics = [];
2255
2596
  for (const site of sites) {
2256
- const outcome = outcomes.get(site.path) ?? compileSite(site, members, images);
2597
+ const outcome = outcomes.get(site.path) ?? compileSite(site, members, images, invoiced);
2257
2598
  const aggregate = site.path.startsWith("/aggregates/") ? report.aggregates[Number(site.path.split("/")[2])]?.id : void 0;
2258
2599
  if (aggregate !== void 0 && cyclic.has(aggregate)) diagnostics.push(cycleDiagnostic(aggregate, site, reads, cyclic));
2259
2600
  else if (outcome.ok) expressions.set(site.path, outcome.compiled);
@@ -2364,6 +2705,147 @@ function contentDiagnostics(report) {
2364
2705
  return found;
2365
2706
  }
2366
2707
  //#endregion
2708
+ //#region src/diagnostics/e-invoice.ts
2709
+ /**
2710
+ * What an e-invoice asks of the page that prints it: every total its XML
2711
+ * holds printed, and printed as the XML holds it.
2712
+ *
2713
+ * The runtime computes each total once, for the page and the XML (0027),
2714
+ * so where both show one they show the same value. What nothing there can
2715
+ * make agree is a total the page never shows, or one it shows otherwise:
2716
+ * the picture would be another invoice than the one it carries, which
2717
+ * § 14c UStG may count as a second.
2718
+ *
2719
+ * - **`e-invoice-total-unprinted`.** Each total the XML always holds -- the
2720
+ * total without VAT (BT-109, or the sum of the lines, BT-106, which
2721
+ * equals it with no allowances or charges), the VAT total (BT-110), the
2722
+ * total with VAT (BT-112), and the basis and the amount of each declared
2723
+ * category (BT-116, BT-117) -- is an error when no run of a text or of a
2724
+ * table reads it; so are the paid amount (BT-113) and the amount due
2725
+ * (BT-115), where a paid amount is declared.
2726
+ * - **`e-invoice-format-differs`.** A run that reads a total prints it at
2727
+ * two places at least, in the e-invoice's currency named as a code, or
2728
+ * as a plain number; so does the column of a line's net amount (BT-131),
2729
+ * and the net price's (BT-146) prints in that currency. A line's name
2730
+ * (BT-153) is printed in the case the data gives it. A quantity's and a
2731
+ * price's places are the data's, and the runtime holds them row by row.
2732
+ *
2733
+ * It is the template's, not the data's: a run behind a condition counts as
2734
+ * printing what it reads, and which categories the lines use is known
2735
+ * only at render, so every declared one is held. It sees that a total is
2736
+ * read by what prints, not what is printed beside it, nor whether it
2737
+ * prints the total at all rather than something computed from it. What
2738
+ * shows a person no text -- a condition, a style rule, a QR code, a
2739
+ * payment code's amount -- prints nothing.
2740
+ */
2741
+ /** The components whose runs print as text. */
2742
+ const PRINTS = /* @__PURE__ */ new Set(["text", "table"]);
2743
+ /** Every run of a text or a table that parses, with what it reads. */
2744
+ function printingRuns(report, sites) {
2745
+ const kinds = new Map(walkComponents(report).map(({ component }) => [component.id, component.kind]));
2746
+ return sites.flatMap((site) => {
2747
+ const kind = site.componentId === void 0 ? void 0 : kinds.get(site.componentId);
2748
+ if (site.kind !== "computed" || kind === void 0 || !PRINTS.has(kind)) return [];
2749
+ const parsed = parse(site.cel);
2750
+ if (!parsed.ok) return [];
2751
+ const reads = referencedPaths(parsed.ast).map(pathParts).flatMap(({ name, member }) => member === void 0 ? [] : [`${name}.${member}`]);
2752
+ return [{
2753
+ site,
2754
+ reads: [...new Set(reads)]
2755
+ }];
2756
+ });
2757
+ }
2758
+ /** Every e-invoice total no run of the page prints, one diagnostic each, at what it is a total of. */
2759
+ function unprintedTotals(invoice, runs) {
2760
+ const totals = [
2761
+ {
2762
+ what: INVOICE_TOTALS.taxBasisTotal,
2763
+ path: "/eInvoice",
2764
+ reads: ["invoice.taxBasisTotal", "invoice.lineTotal"]
2765
+ },
2766
+ {
2767
+ what: INVOICE_TOTALS.taxTotal,
2768
+ path: "/eInvoice",
2769
+ reads: ["invoice.taxTotal"]
2770
+ },
2771
+ {
2772
+ what: INVOICE_TOTALS.grandTotal,
2773
+ path: "/eInvoice",
2774
+ reads: ["invoice.grandTotal"]
2775
+ },
2776
+ ...invoice.paid === void 0 ? [] : [{
2777
+ what: INVOICE_TOTALS.paid,
2778
+ path: "/eInvoice",
2779
+ reads: ["invoice.paid"]
2780
+ }, {
2781
+ what: INVOICE_TOTALS.duePayable,
2782
+ path: "/eInvoice",
2783
+ reads: ["invoice.duePayable"]
2784
+ }],
2785
+ ...invoice.vat.flatMap(({ id }, index) => ["vatBasis", "vatAmount"].map((name) => ({
2786
+ what: `${VAT_BREAKDOWN[name]} of the category ${quote(id)}`,
2787
+ path: `/eInvoice/vat/${index}`,
2788
+ reads: [`${name}.${id}`]
2789
+ })))
2790
+ ];
2791
+ const printed = new Set(runs.flatMap(({ reads }) => reads));
2792
+ return totals.filter(({ reads }) => !reads.some((read) => printed.has(read))).map(({ what, path, reads }) => diagnostic("e-invoice-total-unprinted", `${what} is in the e-invoice's XML, and no text or table of the page prints it: print it as ${reads.join(" or ")}, so the page shows the invoice it carries`, { path }));
2793
+ }
2794
+ /** What a format that shows an amount at fewer places than the XML's two says, `by` naming what prints it; undefined where it shows them all. */
2795
+ function placesBreak(format, by) {
2796
+ if (format?.kind !== "number" && format?.kind !== "currency" || format.scale >= 2) return void 0;
2797
+ return `is an amount the XML holds to the cent, and ${by} prints it at ${format.scale} places, rounding it again: print it at two places or more`;
2798
+ }
2799
+ /** What a currency format that names another currency than the e-invoice's says, `by` naming what prints it; undefined where it names that one, or none. */
2800
+ function currencyBreak(format, currency, by) {
2801
+ if (format?.kind !== "currency") return void 0;
2802
+ const source = format.currency;
2803
+ if (source.kind === "code" && source.code === currency) return void 0;
2804
+ return `is an amount in the e-invoice's currency, ${currency} (BT-5), and ${by} prints it in ${source.kind === "code" ? source.code : `the currency a ${source.kind} gives`}: name ${currency} as its currency`;
2805
+ }
2806
+ /** The format a column's value is printed with, if any. */
2807
+ const formatOf = (value) => "format" in value ? value.format : void 0;
2808
+ /** Every run that prints a total otherwise than the XML holds it, and every column of a line that does: one diagnostic each, at the format. */
2809
+ function formatsThatDiffer(report, invoice, runs) {
2810
+ const found = [];
2811
+ for (const { site, reads } of runs) {
2812
+ const total = reads.find((read) => E_INVOICE_NAMES.includes(read.split(".")[0]));
2813
+ if (total === void 0) continue;
2814
+ const broken = placesBreak(site.format, "this run") ?? currencyBreak(site.format, invoice.currency, "this run");
2815
+ if (broken !== void 0) found.push(diagnostic("e-invoice-format-differs", `${total} ${broken}`, {
2816
+ path: site.path.replace(/\/expression\/cel$/, "/format"),
2817
+ componentId: site.componentId,
2818
+ columnId: site.columnId
2819
+ }));
2820
+ }
2821
+ const located = walkComponents(report).find(({ component }) => component.kind === "table" && component.id === invoice.lines.table);
2822
+ if (located === void 0) return found;
2823
+ const table = located.component;
2824
+ const columnBreaks = {
2825
+ name: (format) => format?.kind === "text" && format.transform !== void 0 ? `is written into the XML as the data gives it, and its column prints it in ${format.transform} case: print it without a transform` : void 0,
2826
+ netAmount: (format) => placesBreak(format, "its column") ?? currencyBreak(format, invoice.currency, "its column"),
2827
+ netPrice: (format) => currencyBreak(format, invoice.currency, "its column")
2828
+ };
2829
+ for (const [key, broken] of Object.entries(columnBreaks)) {
2830
+ const index = table.columns.findIndex(({ id }) => id === invoice.lines[key]);
2831
+ const column = table.columns[index];
2832
+ const said = column === void 0 ? void 0 : broken(formatOf(column.value));
2833
+ if (column !== void 0 && said !== void 0) found.push(diagnostic("e-invoice-format-differs", `${E_INVOICE_LINE_COLUMNS[key].what} ${said}`, {
2834
+ path: `${located.path}/columns/${index}/value/format`,
2835
+ componentId: table.id,
2836
+ columnId: column.id
2837
+ }));
2838
+ }
2839
+ return found;
2840
+ }
2841
+ /** What the page of an e-invoice report fails to print as the XML holds it: the totals it does not print, then the formats that print otherwise. */
2842
+ function eInvoiceDiagnostics(report, sites) {
2843
+ const invoice = report.eInvoice;
2844
+ if (invoice === void 0) return [];
2845
+ const runs = printingRuns(report, sites);
2846
+ return [...unprintedTotals(invoice, runs), ...formatsThatDiffer(report, invoice, runs)];
2847
+ }
2848
+ //#endregion
2367
2849
  //#region src/diagnostics/rounding.ts
2368
2850
  /** The types a rounding has places in. */
2369
2851
  const ROUNDED = /* @__PURE__ */ new Set(["decimal", "dyn"]);
@@ -2453,8 +2935,8 @@ function unusedDiagnostics(report, parts) {
2453
2935
  /**
2454
2936
  * Every diagnostic for `report`, a report the validator accepts -- a
2455
2937
  * session's document is one. Expressions first, in document order, the
2456
- * aggregates' last, then roundings, then content, then unused declarations
2457
- * in the order they are declared. The expressions' are `compileReport`'s,
2938
+ * aggregates' last, then roundings, then the e-invoice's unprinted totals,
2939
+ * then content, then unused declarations in the order they are declared. The expressions' are `compileReport`'s,
2458
2940
  * so the editor reports exactly what the runtime refuses.
2459
2941
  */
2460
2942
  function diagnose(report) {
@@ -2463,11 +2945,12 @@ function diagnose(report) {
2463
2945
  return [
2464
2946
  ...compiled.diagnostics,
2465
2947
  ...roundingDiagnostics(report, parts.printedTotals, compiled.members.totals),
2948
+ ...eInvoiceDiagnostics(report, parts.expressions),
2466
2949
  ...contentDiagnostics(report),
2467
2950
  ...unusedDiagnostics(report, parts)
2468
2951
  ];
2469
2952
  }
2470
2953
  //#endregion
2471
- export { ARGUMENTS, COMMANDS, DEFAULT_HISTORY_LIMIT, DIAGNOSTIC_CODES, DIAGNOSTIC_SEVERITIES, EXPRESSION_TYPES, REFUSAL_CODES, SCOPE_NAMES, UNREPRODUCIBLE_FUNCTIONS, compileReport, describedCommand, diagnose, duplicateComponent, expressionSites, expressionValues, insertColumn, insertComponent, insertFooterRow, locationOf, locations, moveColumn, moveComponent, moveFooterRow, moveParameter, nextComponentId, openReportSession, putAggregate, putAsset, putDataset, putField, putFooterCell, putParameter, putStyle, removeAggregate, removeAsset, removeColumn, removeComponent, removeDataset, removeField, removeFooterCell, removeFooterRow, removeParameter, removeStyle, replaceDocument, setGroup, setLocale, setPage, setSort, setTitle, tryEdit, updateColumn, updateComponent, updateFooterRow, validLocations };
2954
+ export { ARGUMENTS, COMMANDS, DEFAULT_HISTORY_LIMIT, DIAGNOSTIC_CODES, DIAGNOSTIC_SEVERITIES, EXPRESSION_TYPES, REFUSAL_CODES, SCOPE_NAMES, UNREPRODUCIBLE_FUNCTIONS, addAsset, compileReport, describedCommand, diagnose, duplicateComponent, expressionSites, expressionValues, insertColumn, insertComponent, insertFooterRow, locationOf, locations, moveColumn, moveComponent, moveFooterRow, moveParameter, nextAssetId, nextComponentId, openReportSession, putAggregate, putAsset, putDataset, putField, putFooterCell, putParameter, putStyle, removeAggregate, removeAsset, removeColumn, removeComponent, removeDataset, removeField, removeFooterCell, removeFooterRow, removeParameter, removeStyle, replaceDocument, setGroup, setLocale, setPage, setSort, setTitle, tryEdit, updateColumn, updateComponent, updateFooterRow, validLocations };
2472
2955
 
2473
2956
  //# sourceMappingURL=index.mjs.map