@le-space/eigenbeleg 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@ The Eigenbeleg and the Kontoauszug of Le Space's tools – [Belege](https://gith
5
5
  An Eigenbeleg is a receipt the payer writes for a payment that has no receipt from the other side. It is never an invoice, and never one written for somebody else.
6
6
 
7
7
  - **A period's Eigenbeleg** (Eigenbeleg's): `valueEntries(entries, rates)` values [`@le-space/ledger`](../ledger) entries at the day's rate (`rates.rateFor(asset, day)`, e.g. from [`@le-space/rates`](../rates); `fixedRates` for tests; Aleph credits at their USD price per credit). `buildDocument({ payer, chain, network, period, entries, number, includeKinds, layout })` puts the payments to the network on it (fees, storage deposits; transfers only when included) and says of every other movement why not; `layout: 'collective'` (one Sammel-Eigenbeleg) or `'single'` (one per transaction, numbered up from the first, `nthNumber`). `eigenbelegPdf(doc, { logo })`, `eigenbelegCsv(doc)` (semicolons, decimal commas, BOM; formulas defused).
8
- - **The Kontoauszug** (Eigenbeleg's): `buildStatement({ payer, account, chain, period, entries, opening, closing, method, belege })` – opening balance, each booking with debit, credit and running balance, closing balance checked against the chain (`reconciled(difference)`: exactly, or but for dust below the twelve decimals the documents print, `isDust`, such as NEAR's 1 yocto deposit of a token transfer); Aleph credits and a payer's balance in Filecoin Pay (chain `filecoin-pay`, the entries of `@le-space/chains/filecoin-pay`'s `filecoinPayEntries`) as a monthly **Verbrauchsauszug**, each with its own note (`USAGE_NOTES`). `statementPdf(st, { logo })`. `logo: true` draws the chain's mark, small, beside the title (NEAR, Akash, Filecoin, Aleph; from `@le-space/pdf`'s `LOGOS`, sources and terms in its `assets/README.md`); off unless asked for.
8
+ - **The Kontoauszug** (Eigenbeleg's): `buildStatement({ payer, account, chain, period, entries, opening, closing, method, belege })` – opening balance, each booking with debit, credit and running balance, closing balance checked against the chain (`reconciled(difference)`: exactly, or but for dust below the twelve decimals the documents print, `isDust`, such as NEAR's 1 yocto deposit of a token transfer); Aleph credits and a payer's balance in Filecoin Pay (chain `filecoin-pay`, the entries of `@le-space/chains/filecoin-pay`'s `filecoinPayEntries`) as a monthly **Verbrauchsauszug**, each with its own note (`USAGE_NOTES`). `statementPdf(st, { logo, chart })`. Above each list of bookings stands a small diagram ([#889](https://github.com/Le-Space/belege/issues/889)), drawn as vectors from [`@le-space/charts`](../charts): the balance over the period on a Kontoauszug, the consumption per resource on a Verbrauchsauszug, per day (per month where the period is longer than a quarter), in the asset's own unit; `chart: false` leaves it out. `statementChart(st, section)` gives its series and its scene, for an API's answer or `svg(scene)`; `drawScene(page, scene, { x, top, fonts })` draws any scene on a PDF page. `logo: true` draws the chain's mark, small, beside the title (NEAR, Akash, Filecoin, Aleph; from `@le-space/pdf`'s `LOGOS`, sources and terms in its `assets/README.md`); off unless asked for.
9
9
  - **The Eigenbeleg of one booking** (Belege's, `@le-space/eigenbeleg/booking`, `/booking-pdf`): `bookingPdf(doc)` for a `BookingEigenbeleg` – a bank booking or a crypto payment, with an own wallet's transaction in full (whole hash, both addresses, every movement with the gas, the explorer link as a QR code). The booking's context is the caller's to gather. `nextSelfNumber(receipts, year)` – the range EB-YYYY-NNN.
10
10
  - **A statement Eigenbeleg** (Belege's Aleph, Akash and travel statements, `@le-space/eigenbeleg/statement-layout`): `statementLayout({ title, created, continuation })` → `head`, `field`, `rule`, `heading`, `table` (the header repeats on a new page), `signature`, `save`.
11
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/eigenbeleg",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The Eigenbeleg and the Kontoauszug of Le Space's tools: a payer's own receipt for payments without one from the other side (a period's network fees, one booking in any script), a blockchain account's statement (Aleph credits as a Verbrauchsauszug), as PDF/A-2b and CSV. Browser and Node; the rates handed in.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "type": "module",
@@ -19,7 +19,9 @@
19
19
  "./statement": "./src/statement.js",
20
20
  "./booking": "./src/booking.js",
21
21
  "./booking-pdf": "./src/booking-pdf.js",
22
- "./statement-layout": "./src/statement-layout.js"
22
+ "./statement-layout": "./src/statement-layout.js",
23
+ "./statement-chart": "./src/statement-chart.js",
24
+ "./chart-pdf": "./src/chart-pdf.js"
23
25
  },
24
26
  "files": [
25
27
  "src"
@@ -34,6 +36,7 @@
34
36
  "dependencies": {
35
37
  "pdf-lib": "1.17.1",
36
38
  "uqr": "0.1.3",
39
+ "@le-space/charts": "^0.1.0",
37
40
  "@le-space/ledger": "^0.3.0",
38
41
  "@le-space/pdf": "^0.1.1"
39
42
  },
@@ -42,7 +45,7 @@
42
45
  "prettier": "3.6.2",
43
46
  "unpdf": "1.8.1",
44
47
  "@le-space/browser-test": "0.1.0",
45
- "@le-space/chains": "^0.5.0"
48
+ "@le-space/chains": "^0.5.3"
46
49
  },
47
50
  "scripts": {
48
51
  "test": "node --test --test-reporter=spec \"test/*.test.js\"",
@@ -0,0 +1,83 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ //
3
+ // A scene of @le-space/charts on a PDF page, as vectors: rectangles, lines,
4
+ // one path per series, text in the document's embedded faces. No image, no
5
+ // transparency: the page stays PDF/A-2b, and sharp at any size.
6
+
7
+ import { LineCapStyle, rgb } from 'pdf-lib';
8
+ import { PALETTE } from '@le-space/charts';
9
+ import { pdfText } from '@le-space/pdf';
10
+
11
+ /** @typedef {import('@le-space/charts').Role} Role */
12
+
13
+ /** @param {string} hex #rrggbb */
14
+ const color = (hex) =>
15
+ rgb(
16
+ parseInt(hex.slice(1, 3), 16) / 255,
17
+ parseInt(hex.slice(3, 5), 16) / 255,
18
+ parseInt(hex.slice(5, 7), 16) / 255
19
+ );
20
+
21
+ /** Paper is light. */
22
+ const COLORS = /** @type {Record<Role, import('pdf-lib').Color>} */ (
23
+ Object.fromEntries(Object.entries(PALETTE.light).map(([role, hex]) => [role, color(hex)]))
24
+ );
25
+
26
+ /**
27
+ * How wide a text of a scene is in the document's faces: hand it to the chart, so labels sit
28
+ * where the drawn text ends.
29
+ *
30
+ * @param {import('./layout.js').Fonts} fonts
31
+ * @returns {import('@le-space/charts').Measure}
32
+ */
33
+ export const sceneMeasure = (fonts) => (text, size, bold) =>
34
+ (bold ? fonts.bold : fonts.regular).width(pdfText(text), size);
35
+
36
+ /**
37
+ * @param {import('pdf-lib').PDFPage} page
38
+ * @param {import('@le-space/charts').Scene} scene
39
+ * @param {object} o
40
+ * @param {number} o.x the scene's left edge on the page
41
+ * @param {number} o.top its top edge (PDF's y runs up, a scene's down)
42
+ * @param {import('./layout.js').Fonts} o.fonts
43
+ */
44
+ export function drawScene(page, scene, { x, top, fonts }) {
45
+ for (const s of scene.shapes) {
46
+ if (s.type === 'rect') {
47
+ if (s.w > 0 && s.h > 0)
48
+ page.drawRectangle({
49
+ x: x + s.x,
50
+ y: top - s.y - s.h,
51
+ width: s.w,
52
+ height: s.h,
53
+ color: COLORS[s.fill]
54
+ });
55
+ } else if (s.type === 'line') {
56
+ page.drawLine({
57
+ start: { x: x + s.x1, y: top - s.y1 },
58
+ end: { x: x + s.x2, y: top - s.y2 },
59
+ thickness: s.width,
60
+ color: COLORS[s.stroke]
61
+ });
62
+ } else if (s.type === 'path') {
63
+ if (s.points.length > 1)
64
+ page.drawSvgPath(s.points.map(([px, py], i) => `${i ? 'L' : 'M'}${px} ${py}`).join(' '), {
65
+ x,
66
+ y: top,
67
+ borderColor: COLORS[s.stroke],
68
+ borderWidth: s.width,
69
+ borderLineCap: LineCapStyle.Round
70
+ });
71
+ } else {
72
+ const face = s.bold ? fonts.bold : fonts.regular;
73
+ const text = pdfText(s.text);
74
+ const w = s.anchor === 'start' ? 0 : face.width(text, s.size);
75
+ face.draw(page, text, {
76
+ x: x + s.x - (s.anchor === 'end' ? w : s.anchor === 'middle' ? w / 2 : 0),
77
+ y: top - s.y,
78
+ size: s.size,
79
+ color: COLORS[s.fill]
80
+ });
81
+ }
82
+ }
83
+ }
package/src/index.js CHANGED
@@ -32,6 +32,8 @@ export {
32
32
  } from './statement.js';
33
33
  /** @typedef {import('./statement.js').MonthlyLine} MonthlyLine */
34
34
  export { statementPdf } from './statement-pdf.js';
35
+ export { statementChart } from './statement-chart.js';
36
+ export { drawScene, sceneMeasure } from './chart-pdf.js';
35
37
  export { valueEntries, fixedRates } from './value.js';
36
38
  export { nextSelfNumber, bookingNote, bookingNotInvoice } from './booking.js';
37
39
  export { bookingPdf } from './booking-pdf.js';
@@ -0,0 +1,96 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ //
3
+ // The diagram of a statement's section (#889), above its list of bookings:
4
+ // a Kontoauszug shows the balance over the period, a Verbrauchsauszug what
5
+ // was consumed, per resource. Per day; per month where the period is longer
6
+ // than a quarter. In the asset's own unit, so every figure of the diagram is
7
+ // one the tables below it hold: the running balance, a day's consumption,
8
+ // the sums of the Monatsübersicht (they stand in the legend).
9
+ //
10
+ // Series and shapes come from @le-space/charts; this file picks what a
11
+ // statement shows and gives it its German words. statement-pdf.js draws the
12
+ // scene into the PDF as vectors (chart-pdf.js); `svg(scene)` of
13
+ // @le-space/charts gives the same picture for a page.
14
+
15
+ import {
16
+ balanceSeries,
17
+ clip,
18
+ granularity,
19
+ lineChart,
20
+ stackedBars,
21
+ sumSeries
22
+ } from '@le-space/charts';
23
+ import { round } from '@le-space/ledger';
24
+
25
+ import { deNumber } from './document.js';
26
+
27
+ /** A resource as the Monatsübersicht names it. @param {string} label */
28
+ export const resourceName = (label) =>
29
+ label.replace(/^Aleph Cloud \((.*)\)$/, '$1').replace(/^storage$/, 'Speicher (storage)');
30
+
31
+ /** @param {string} bucket YYYY-MM-DD or YYYY-MM */
32
+ const bucketLabel = (bucket) => {
33
+ const [y, m, d] = bucket.split('-');
34
+ return d ? `${d}.${m}.` : `${m}/${y}`;
35
+ };
36
+
37
+ /**
38
+ * @param {import('./statement.js').Statement} st
39
+ * @param {import('./statement.js').Statement['sections'][number]} s
40
+ * @param {object} [o]
41
+ * @param {number} [o.width]
42
+ * @param {number} [o.height]
43
+ * @param {import('@le-space/charts').Measure} [o.measure] the width of a text in the renderer's font
44
+ * @returns {{ kind: 'usage', series: import('@le-space/charts').SumSeries, scene: import('@le-space/charts').Scene }
45
+ * | { kind: 'balance', series: import('@le-space/charts').BalanceSeries, scene: import('@le-space/charts').Scene }
46
+ * | null} null where there is nothing to draw: no booking, or a period of one day
47
+ */
48
+ export function statementChart(st, s, { width = 507, height = 112, measure } = {}) {
49
+ const { from, to } = st.period;
50
+ if (!s.rows.length || !(from < to)) return null;
51
+ const by = granularity(from, to);
52
+ const per = by === 'month' ? 'Monat' : 'Tag';
53
+ const unit = st.chain === 'aleph' ? 'Credits' : s.asset;
54
+ const common = { width, height, format: deNumber, bucketLabel, ...(measure ? { measure } : {}) };
55
+ const used = s.rows.filter((r) => r.usage && r.debit);
56
+ if (st.title === 'Verbrauchsauszug' && used.length) {
57
+ const series = sumSeries({
58
+ items: used.map((r) => ({ date: r.date, amount: r.debit, key: r.label })),
59
+ from,
60
+ to,
61
+ by,
62
+ others: 'Übrige'
63
+ });
64
+ const scene = stackedBars({
65
+ ...common,
66
+ title: `Verbrauch je ${per} (${unit})`,
67
+ buckets: series.buckets,
68
+ series: series.series.map((x) => ({
69
+ label: `${clip(x.others ? x.label : resourceName(x.label), 28)} · ${deNumber(round(x.total, 12))}`,
70
+ values: x.values.map(Number),
71
+ ...(x.others ? { color: /** @type {const} */ ('other') } : {})
72
+ }))
73
+ });
74
+ return { kind: 'usage', series, scene };
75
+ }
76
+ const series = balanceSeries({
77
+ opening: s.opening,
78
+ movements: s.rows.map((r) => ({ date: r.date, amount: r.credit || `-${r.debit}` })),
79
+ from,
80
+ to,
81
+ by
82
+ });
83
+ const scene = lineChart({
84
+ ...common,
85
+ title: `Kontostand je ${per} (${unit})`,
86
+ buckets: series.points.map((p) => p.bucket),
87
+ series: [
88
+ {
89
+ label: unit,
90
+ start: Number(series.opening),
91
+ values: series.points.map((p) => Number(p.value))
92
+ }
93
+ ]
94
+ });
95
+ return { kind: 'balance', series, scene };
96
+ }
@@ -5,7 +5,9 @@
5
5
  // bookings (date, text, debit, credit, running balance, EUR value), the
6
6
  // closing balance with its check against the chain, and the sums a
7
7
  // bookkeeper needs. German, for German bookkeeping. Aleph Cloud credits get
8
- // the same layout titled »Verbrauchsauszug« (`st.title`).
8
+ // the same layout titled »Verbrauchsauszug« (`st.title`). Above each list of
9
+ // bookings a small diagram (#889, statement-chart.js): the balance over the
10
+ // period, or what was consumed per day.
9
11
 
10
12
  import { rgb } from 'pdf-lib';
11
13
  import { asset, createPdfA, LOGOS, savePdfA, wrapText } from '@le-space/pdf';
@@ -14,6 +16,8 @@ import { round } from '@le-space/ledger';
14
16
  import { DATA_SOURCES, deDate, deEuro, deNumber } from './document.js';
15
17
  import { CREATOR, PRODUCER } from './pdf.js';
16
18
  import { isDust, reconciled } from './statement.js';
19
+ import { drawScene, sceneMeasure } from './chart-pdf.js';
20
+ import { statementChart } from './statement-chart.js';
17
21
  import { A4, BAND, BLACK, GREY, OK, RULE, WARN, pageLayout } from './layout.js';
18
22
 
19
23
  const M = 44;
@@ -33,13 +37,14 @@ const qty = (q) => (q ? deNumber(round(q, 12)) : '');
33
37
 
34
38
  /**
35
39
  * @param {import('./statement.js').Statement} st
36
- * @param {{ creator?: string, producer?: string, logo?: boolean }} [o] logo: the chain's
37
- * mark, small, beside the title (off unless asked for; @le-space/pdf's LOGOS)
40
+ * @param {{ creator?: string, producer?: string, logo?: boolean, chart?: boolean }} [o] logo: the chain's
41
+ * mark, small, beside the title (off unless asked for; @le-space/pdf's LOGOS). chart: the
42
+ * diagram above each list of bookings (on unless switched off)
38
43
  * @returns {Promise<Uint8Array>}
39
44
  */
40
45
  export async function statementPdf(
41
46
  st,
42
- { creator = CREATOR, producer = PRODUCER, logo = false } = {}
47
+ { creator = CREATOR, producer = PRODUCER, logo = false, chart = true } = {}
43
48
  ) {
44
49
  const created = new Date(st.issuedAt);
45
50
  // Aleph credits: a Verbrauchsauszug in the same layout, valued by its own rule.
@@ -139,6 +144,13 @@ export async function statementPdf(
139
144
  l.y -= 8;
140
145
  }
141
146
  }
147
+ // The diagram, above the list of bookings (#889); every figure in it is in the tables.
148
+ const drawn = chart ? statementChart(st, s, { width, measure: sceneMeasure(fonts) }) : null;
149
+ if (drawn) {
150
+ l.ensure(drawn.scene.height + 40);
151
+ drawScene(l.page, drawn.scene, { x: M, top: l.y, fonts });
152
+ l.y -= drawn.scene.height + 12;
153
+ }
142
154
  const head = () => {
143
155
  let x = M;
144
156
  for (const c of COLS) {