@le-space/eigenbeleg 0.2.0 → 0.5.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,12 +5,19 @@ 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
+ - **Another currency than the euro** ([eigenbeleg-agent#72](https://github.com/Le-Space/eigenbeleg-agent/issues/72)): `valueEntries(entries, rates, { currency })`, `buildDocument({ …, currency })` and `buildStatement({ …, currency })` take the document's currency, EUR when none is given – `DOCUMENT_CURRENCIES`: EUR, USD, CHF, GBP, SEK, NOK, DKK, PLN, CZK, HUF, RON, ISK, TRY (through the ECB's reference rate) and RUB (the Bank of Russia's official rate). The rates handed in are in that currency and say so (`{ rate, source, date, currency }`; `@le-space/rates` `rate(asset, date, { currency })`), `source` naming both legs; a value in one currency under a head in another is refused. The documents then say _Kurs CHF_, _Wert CHF_, amounts as `1.234,56 CHF`, sums rounded to the currency's own decimals (ISK: none), and how the value came about (`conversionText`, `usageNote`); Aleph credits in USD are Aleph's own USD price, without a rate. The fields named `eur…` (`entry.eur`, `totals.eur`, `eurOut` …) keep their names and hold the value in the document's currency, with `currency` beside them. An EUR document is the same file as before. `bookingPdf` is Belege's own booking and stays in euro.
9
10
  - **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
11
  - **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
12
 
12
13
  Every PDF has Eigenbeleg's look (`layout.js`): A4, grey labels beside their values, a note in a tinted box, page numbers at the foot, a line to sign. `creator` names the program in the metadata (`eigenbeleg` for the period's documents, `Belege` for a booking's and a statement's unless given).
13
14
 
15
+ ## The issuer's own logo
16
+
17
+ An Eigenbeleg and a Kontoauszug are issued by the payer, so the logo that belongs on them is the payer's ([#906](https://github.com/Le-Space/belege/issues/906)). `eigenbelegPdf(doc, { issuerLogo })`, `statementPdf(st, { issuerLogo })` and `bookingPdf(doc, { issuerLogo })` take the bytes of a PNG or JPEG file and draw it in the head's top right corner, level with the title, fitted into 120 × 40 pt (`ISSUER_LOGO_BOX`) with its proportions kept. The text of the head is where it is without a logo; the chain's mark (`logo: true`) stays beside the title, and a document may carry both. The package ships no such picture and fetches none: the caller hands it in.
18
+
19
+ The file goes through [`@le-space/pdf`](../pdf)'s `pdfImage` first: at most 512 kB and 2048 pixels a side, no wider than six times its height and no taller than twice its width (`IMAGE_LIMITS`); a PNG is laid on white and written again without transparency, text chunks or a colour profile, a JPEG loses EXIF, comments and its other application segments. SVG is refused, as is a JPEG in CMYK. A file that does not pass is an `ImageError` with a sentence for the person, never a document without its logo.
20
+
14
21
  ```bash
15
22
  pnpm --filter @le-space/eigenbeleg test # Node, and every document byte for byte in Chromium
16
23
  pnpm --filter @le-space/eigenbeleg pdfa-samples out/ # one of each, for veraPDF (CI runs it)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/eigenbeleg",
3
- "version": "0.2.0",
3
+ "version": "0.5.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"
@@ -35,14 +37,15 @@
35
37
  "pdf-lib": "1.17.1",
36
38
  "uqr": "0.1.3",
37
39
  "@le-space/ledger": "^0.3.0",
38
- "@le-space/pdf": "^0.1.1"
40
+ "@le-space/pdf": "^0.2.0",
41
+ "@le-space/charts": "^0.2.0"
39
42
  },
40
43
  "devDependencies": {
41
44
  "@noble/hashes": "2.4.0",
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.6.0"
46
49
  },
47
50
  "scripts": {
48
51
  "test": "node --test --test-reporter=spec \"test/*.test.js\"",
@@ -13,17 +13,20 @@ import { fromUnits } from '@le-space/ledger';
13
13
 
14
14
  import { bookingNote, bookingNotInvoice } from './booking.js';
15
15
  import { deDate, deEuro, deNumber } from './document.js';
16
- import { A4, BLACK, GREY, pageLayout } from './layout.js';
16
+ import { A4, BLACK, GREY, embedIssuerLogo, pageLayout } from './layout.js';
17
17
 
18
18
  /**
19
19
  * @param {import('./booking.js').BookingEigenbeleg} doc
20
- * @param {{ creator?: string, producer?: string }} [o] what made it: `Belege` when not given
20
+ * @param {{ creator?: string, producer?: string, issuerLogo?: Uint8Array | null }} [o] what made it: `Belege` when not given. issuerLogo: the issuer's own
21
+ * logo, a PNG or JPEG file's bytes, in the head's top right corner (none unless given; an
22
+ * ImageError of @le-space/pdf when the file is no small PNG or JPEG)
21
23
  * @returns {Promise<Uint8Array>}
22
24
  */
23
- export async function bookingPdf(doc, { creator = 'Belege', producer } = {}) {
25
+ export async function bookingPdf(doc, { creator = 'Belege', producer, issuerLogo = null } = {}) {
24
26
  const created = new Date(doc.createdAt);
25
27
  const { pdf, fonts } = await createPdfA();
26
28
  const { regular, bold, mono } = fonts;
29
+ const own = await embedIssuerLogo(pdf, issuerLogo);
27
30
  const M = 48;
28
31
  let pageNo = 1;
29
32
  const footer = (/** @type {import('./layout.js').Layout} */ l) =>
@@ -45,6 +48,7 @@ export async function bookingPdf(doc, { creator = 'Belege', producer } = {}) {
45
48
  const out = doc.amountCents < 0;
46
49
 
47
50
  // ---- head
51
+ l.issuerLogo(own, l.y);
48
52
  text('Eigenbeleg', { face: bold, size: 20 });
49
53
  text(`Nr. ${doc.number}`, { face: bold, size: 12 });
50
54
  gap(2);
@@ -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/csv.js CHANGED
@@ -8,9 +8,10 @@
8
8
  // where anyone can write anything.
9
9
 
10
10
  import { round } from '@le-space/ledger';
11
- import { kindText } from './document.js';
11
+ import { currencyPlaces, kindText } from './document.js';
12
12
 
13
- const HEADER = [
13
+ /** The head; rate and value name the document's currency. @param {string} currency */
14
+ const header = (currency) => [
14
15
  'Belegnummer',
15
16
  'Position',
16
17
  'Datum (UTC)',
@@ -24,8 +25,8 @@ const HEADER = [
24
25
  'Asset',
25
26
  'Token-Contract',
26
27
  'Menge',
27
- 'Kurs EUR',
28
- 'Wert EUR',
28
+ `Kurs ${currency}`,
29
+ `Wert ${currency}`,
29
30
  'Kursquelle',
30
31
  'Transaktions-Hash',
31
32
  'Explorer',
@@ -50,8 +51,10 @@ function cell(v) {
50
51
  * @returns {string}
51
52
  */
52
53
  export function eigenbelegCsv(doc) {
54
+ const currency = doc.currency ?? 'EUR';
53
55
  /** @type {unknown[][]} */
54
- const rows = [HEADER];
56
+ const rows = [header(currency)];
57
+ const places = currencyPlaces(currency);
55
58
  const numberOf = (/** @type {number | string} */ pos) =>
56
59
  doc.layout === 'single' ? (doc.transactions[Number(pos) - 1]?.number ?? '') : doc.number;
57
60
  /** @param {import('./value.js').ValuedEntry} e @param {string | number} pos @param {boolean} on @param {string} why */
@@ -95,8 +98,8 @@ export function eigenbelegCsv(doc) {
95
98
  '',
96
99
  '',
97
100
  '',
98
- num(round(`-${doc.totals.eurExact}`, 2)),
99
- `gerundet auf Cent, ungerundet ${doc.totals.eurExact === '0' ? '0' : '-' + num(doc.totals.eurExact)}`,
101
+ num(round(`-${doc.totals.eurExact}`, places)),
102
+ `${currency === 'EUR' ? 'gerundet auf Cent' : places ? `gerundet auf ${places} Nachkommastellen` : 'gerundet auf ganze Beträge'}, ungerundet ${doc.totals.eurExact === '0' ? '0' : '-' + num(doc.totals.eurExact)}`,
100
103
  '',
101
104
  '',
102
105
  'ja',
package/src/document.js CHANGED
@@ -60,6 +60,88 @@ export function noInvoice(chain, chainName) {
60
60
  export const NOT_AN_INVOICE =
61
61
  'Dies ist keine Rechnung und kein Beleg eines Dritten. Le Space stellt keine Rechnungen für andere aus.';
62
62
 
63
+ /**
64
+ * The currencies a document can be kept in (Le-Space/eigenbeleg-agent#72),
65
+ * each with the decimals its totals are rounded to (ISO 4217) and where its
66
+ * rate against the euro comes from: the ECB's reference rate, or the Bank of
67
+ * Russia's official rate. EUR is the default, and what every document was in
68
+ * before. The caller's rates must be in the document's currency
69
+ * (`valueEntries(entries, rates, { currency })`; @le-space/rates
70
+ * `rate(asset, date, { currency })`).
71
+ */
72
+ export const DOCUMENT_CURRENCIES = Object.freeze(
73
+ /** @type {Record<string, { places: number, via: 'ecb' | 'cbr' | null }>} */ ({
74
+ EUR: { places: 2, via: null },
75
+ USD: { places: 2, via: 'ecb' },
76
+ CHF: { places: 2, via: 'ecb' },
77
+ GBP: { places: 2, via: 'ecb' },
78
+ SEK: { places: 2, via: 'ecb' },
79
+ NOK: { places: 2, via: 'ecb' },
80
+ DKK: { places: 2, via: 'ecb' },
81
+ PLN: { places: 2, via: 'ecb' },
82
+ CZK: { places: 2, via: 'ecb' },
83
+ HUF: { places: 2, via: 'ecb' },
84
+ RON: { places: 2, via: 'ecb' },
85
+ ISK: { places: 0, via: 'ecb' },
86
+ TRY: { places: 2, via: 'ecb' },
87
+ RUB: { places: 2, via: 'cbr' }
88
+ })
89
+ );
90
+
91
+ /** The currency of a document, checked: EUR when none is given. @param {unknown} [currency] */
92
+ export function documentCurrency(currency = 'EUR') {
93
+ if (typeof currency !== 'string' || !Object.hasOwn(DOCUMENT_CURRENCIES, currency))
94
+ throw new Error(`currency: one of ${Object.keys(DOCUMENT_CURRENCIES).join(', ')}`);
95
+ return currency;
96
+ }
97
+
98
+ /** The decimals a currency's totals are rounded to. @param {string} currency */
99
+ export const currencyPlaces = (currency) => DOCUMENT_CURRENCIES[documentCurrency(currency)].places;
100
+
101
+ /**
102
+ * How a value in euro became one in the document's currency, as the documents
103
+ * say it after naming the euro rate; '' for EUR. The rate is named for what it
104
+ * is: the ECB's reference rate, or the Bank of Russia's official rate.
105
+ *
106
+ * @param {string} currency
107
+ */
108
+ export function conversionText(currency) {
109
+ const ecb = 'zum Euro-Referenzkurs der EZB des Tages oder des letzten davor';
110
+ if (documentCurrency(currency) === 'EUR') return '';
111
+ if (currency === 'USD')
112
+ return `von CoinGecko dessen USD-Kurs desselben Zeitpunkts, sonst über den Euro in USD umgerechnet ${ecb}`;
113
+ if (DOCUMENT_CURRENCIES[currency].via === 'cbr')
114
+ return `über den Euro in ${currency} umgerechnet zum amtlichen Kurs der Bank von Russland, gültig am Tag (bis 01.03.2022 ${ecb})`;
115
+ return `über den Euro in ${currency} umgerechnet ${ecb}`;
116
+ }
117
+
118
+ /**
119
+ * The currency an entry was valued in, and that it is the document's: a value
120
+ * in francs under a head that says EUR would be a wrong booking.
121
+ *
122
+ * @param {import('./value.js').ValuedEntry[]} entries
123
+ * @param {string} currency
124
+ */
125
+ export function checkValued(entries, currency) {
126
+ for (const e of entries) {
127
+ const valued = e.eur ? (e.eur.currency ?? 'EUR') : currency;
128
+ if (valued !== currency)
129
+ throw new Error(`an entry is valued in ${valued}, the document is in ${currency}`);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * A rate's name without its day (`… vom 2026-08-10`), each leg of it: the day
135
+ * is each position's.
136
+ *
137
+ * @param {string} source
138
+ */
139
+ export const sourceName = (source) =>
140
+ source
141
+ .split(' × ')
142
+ .map((leg) => leg.replace(/ \d{4}-\d{2}-\d{2}.*$/, '').replace(/ vom$/, ''))
143
+ .join(' × ');
144
+
63
145
  /** Kinds that go on the Eigenbeleg unless the payer chooses otherwise. */
64
146
  export const DEFAULT_KINDS = ['fee', 'storage'];
65
147
 
@@ -146,7 +228,7 @@ export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
146
228
  * @property {{ address: string, label: string }} from the own address that paid
147
229
  * @property {{ address: string, label: string }} to who received the payment
148
230
  * @property {Movement[]} movements every movement of the transaction the period has
149
- * @property {string} eurExact what is on the Eigenbeleg, in EUR, positive
231
+ * @property {string} eurExact what is on the Eigenbeleg, in the document's currency, positive
150
232
  */
151
233
 
152
234
  /**
@@ -160,6 +242,9 @@ export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
160
242
  * @param {string[]} [p.includeKinds]
161
243
  * @param {string} [p.issuedAt] ISO; now when not given
162
244
  * @param {'collective' | 'single'} [p.layout]
245
+ * @param {string} [p.currency] the document's currency (DOCUMENT_CURRENCIES), EUR when not
246
+ * given; the entries are valued in it. The fields named `eur…` hold the values in this
247
+ * currency: they keep the name they had when every document was in euro.
163
248
  */
164
249
  export function buildDocument({
165
250
  payer,
@@ -170,10 +255,13 @@ export function buildDocument({
170
255
  number,
171
256
  includeKinds = DEFAULT_KINDS,
172
257
  issuedAt,
173
- layout = 'collective'
258
+ layout = 'collective',
259
+ currency: asked
174
260
  }) {
175
261
  if (layout !== 'collective' && layout !== 'single')
176
262
  throw new Error('layout: collective or single');
263
+ const currency = documentCurrency(asked);
264
+ checkValued(entries, currency);
177
265
  checkPayer(payer);
178
266
  const kinds = new Set(includeKinds);
179
267
  const own = new Set(payer.addresses);
@@ -276,23 +364,18 @@ export function buildDocument({
276
364
  network,
277
365
  testnet: network !== 'mainnet',
278
366
  period,
367
+ currency,
279
368
  positions,
280
369
  excluded,
281
370
  totals: {
282
371
  quantities,
283
- // What was paid, as a positive amount, rounded to cents.
284
- eur: round(eurExact.replace(/^-/, ''), 2),
372
+ // What was paid, as a positive amount, rounded to cents (the currency's smallest unit).
373
+ eur: round(eurExact.replace(/^-/, ''), currencyPlaces(currency)),
285
374
  eurExact: eurExact.replace(/^-/, '')
286
375
  },
287
376
  // The rate's name without its day (`… vom 2026-08-10`): the day is each position's.
288
377
  sources: [
289
- ...new Set(
290
- positions.map((p) =>
291
- /** @type {any} */ (p.entry.eur).source
292
- .replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
293
- .replace(/ vom$/, '')
294
- )
295
- )
378
+ ...new Set(positions.map((p) => sourceName(/** @type {any} */ (p.entry.eur).source)))
296
379
  ],
297
380
  note: noInvoice(chain, chainName).note,
298
381
  notInvoice: NOT_AN_INVOICE
@@ -344,12 +427,29 @@ export function deNumber(amount) {
344
427
  return `${neg ? '−' : ''}${grouped}${frac ? ',' + frac : ''}`;
345
428
  }
346
429
 
347
- /** A euro amount with fixed decimals: `0.0017` → `0,0017 €`. @param {string} amount @param {number} places */
348
- export function deEuro(amount, places = 2) {
430
+ /** An amount with fixed decimals and no unit: `0.0017` → `0,0017`. @param {string} amount @param {number} places */
431
+ export function deFixed(amount, places = 2) {
349
432
  const r = round(String(amount), places);
350
433
  const [int, frac = ''] = r.replace(/^-/, '').split('.');
351
434
  const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
352
- return `${r.startsWith('-') ? '−' : ''}${grouped},${frac.padEnd(places, '0')} €`;
435
+ return `${r.startsWith('-') ? '−' : ''}${grouped}${places ? `,${frac.padEnd(places, '0')}` : ''}`;
436
+ }
437
+
438
+ /** A euro amount with fixed decimals: `0.0017` → `0,0017 €`. @param {string} amount @param {number} places */
439
+ export function deEuro(amount, places = 2) {
440
+ return `${deFixed(amount, places)} €`;
441
+ }
442
+
443
+ /**
444
+ * An amount in a document's currency: `12,34 €`, and for every other currency
445
+ * its code (`12,34 CHF`) – kr and $ are several currencies' signs.
446
+ *
447
+ * @param {string} amount
448
+ * @param {string} currency
449
+ * @param {number} [places] the currency's own when not given
450
+ */
451
+ export function deMoney(amount, currency, places = currencyPlaces(currency)) {
452
+ return `${deFixed(amount, places)} ${currency === 'EUR' ? '€' : currency}`;
353
453
  }
354
454
 
355
455
  /** `2026-10-05` → `05.10.2026`. @param {string} date */
package/src/index.js CHANGED
@@ -16,7 +16,13 @@ export {
16
16
  DATA_SOURCES,
17
17
  deNumber,
18
18
  deEuro,
19
- deDate
19
+ deFixed,
20
+ deMoney,
21
+ deDate,
22
+ DOCUMENT_CURRENCIES,
23
+ documentCurrency,
24
+ currencyPlaces,
25
+ conversionText
20
26
  } from './document.js';
21
27
  export { eigenbelegCsv } from './csv.js';
22
28
  export { eigenbelegPdf, CREATOR, PRODUCER } from './pdf.js';
@@ -28,14 +34,20 @@ export {
28
34
  STATEMENT_NOTE,
29
35
  USAGE_NOTE,
30
36
  USAGE_NOTES,
31
- FILECOIN_PAY_USAGE_NOTE
37
+ FILECOIN_PAY_USAGE_NOTE,
38
+ usageNote
32
39
  } from './statement.js';
33
40
  /** @typedef {import('./statement.js').MonthlyLine} MonthlyLine */
34
41
  export { statementPdf } from './statement-pdf.js';
42
+ export { statementChart } from './statement-chart.js';
43
+ export { drawScene, sceneMeasure } from './chart-pdf.js';
35
44
  export { valueEntries, fixedRates } from './value.js';
36
45
  export { nextSelfNumber, bookingNote, bookingNotInvoice } from './booking.js';
37
46
  export { bookingPdf } from './booking-pdf.js';
38
47
  export { statementLayout } from './statement-layout.js';
48
+ export { ISSUER_LOGO_BOX } from './layout.js';
49
+ // What an issuer's logo may be, and the error a file that is not gets (issuerLogo of the PDFs).
50
+ export { ImageError, IMAGE_LIMITS } from '@le-space/pdf';
39
51
  /** @typedef {import('./value.js').Rate} Rate */
40
52
  /** @typedef {import('./value.js').Rates} Rates */
41
53
  /** @typedef {import('./value.js').ValuedEntry} ValuedEntry */
package/src/layout.js CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { rgb } from 'pdf-lib';
13
13
  import { encode } from 'uqr';
14
- import { pdfText, wrapText } from '@le-space/pdf';
14
+ import { embedPdfImage, pdfImage, pdfText, wrapText } from '@le-space/pdf';
15
15
 
16
16
  /** @typedef {import('@le-space/pdf').Face} Face */
17
17
  /** @typedef {{ regular: Face, bold: Face, mono: Face }} Fonts */
@@ -26,6 +26,20 @@ export const BAND = rgb(0.93, 0.94, 0.95);
26
26
  export const WARN = rgb(0.6, 0.12, 0.08);
27
27
  export const OK = rgb(0.1, 0.42, 0.2);
28
28
 
29
+ /** The room the issuer's logo is fitted into, in points: wide enough for a word mark, as high as a title and its line below. */
30
+ export const ISSUER_LOGO_BOX = /** @type {readonly [number, number]} */ ([120, 40]);
31
+
32
+ /**
33
+ * The issuer's own logo for a document: the bytes of a PNG or JPEG file,
34
+ * checked and reduced to an opaque picture (@le-space/pdf's pdfImage, whose
35
+ * ImageError says what is wrong with a file), embedded once. Null without one.
36
+ *
37
+ * @param {import('pdf-lib').PDFDocument} pdf
38
+ * @param {Uint8Array | null | undefined} file
39
+ */
40
+ export const embedIssuerLogo = async (pdf, file) =>
41
+ file ? embedPdfImage(pdf, pdfImage(file)) : null;
42
+
29
43
  /**
30
44
  * @typedef {object} Column
31
45
  * @property {string} title
@@ -130,6 +144,22 @@ export function pageLayout(pdf, fonts, { margin = 48, bottom = 14, leavePage, en
130
144
  });
131
145
  },
132
146
 
147
+ /**
148
+ * The issuer's logo in the head's top right corner: fitted into
149
+ * ISSUER_LOGO_BOX keeping its proportions, its top at `top`, its right
150
+ * edge at the margin. The text of the head is where it is without one.
151
+ *
152
+ * @param {import('pdf-lib').PDFImage | null} image
153
+ * @param {number} top
154
+ */
155
+ issuerLogo(image, top) {
156
+ if (!image) return;
157
+ const k = Math.min(ISSUER_LOGO_BOX[0] / image.width, ISSUER_LOGO_BOX[1] / image.height);
158
+ const width = image.width * k;
159
+ const height = image.height * k;
160
+ l.page.drawImage(image, { x: A4[0] - margin - width, y: top - height, width, height });
161
+ },
162
+
133
163
  /** @param {number} [thickness] @param {Color} [color] */
134
164
  rule(thickness = 0.6, color = RULE) {
135
165
  l.page.drawLine({
package/src/pdf.js CHANGED
@@ -9,8 +9,17 @@
9
9
  import { asset, createPdfA, LOGOS, savePdfA } from '@le-space/pdf';
10
10
  import { round } from '@le-space/ledger';
11
11
 
12
- import { DATA_SOURCES, deDate, deEuro, deNumber, noInvoice } from './document.js';
13
- import { A4, BLACK, GREY, WARN, pageLayout } from './layout.js';
12
+ import {
13
+ DATA_SOURCES,
14
+ conversionText,
15
+ currencyPlaces,
16
+ deDate,
17
+ deMoney,
18
+ deNumber,
19
+ noInvoice,
20
+ sourceName
21
+ } from './document.js';
22
+ import { A4, BLACK, GREY, WARN, embedIssuerLogo, pageLayout } from './layout.js';
14
23
 
15
24
  /** What made the file, unless the caller says otherwise. */
16
25
  export const CREATOR = 'eigenbeleg';
@@ -18,13 +27,15 @@ export const PRODUCER = 'eigenbeleg (Le Space UG), pdf-lib';
18
27
 
19
28
  /**
20
29
  * @param {import('./document.js').EigenbelegDocument} doc
21
- * @param {{ creator?: string, producer?: string, logo?: boolean }} [o] logo: the chain's
22
- * mark, small, beside the title (off unless asked for; @le-space/pdf's LOGOS)
30
+ * @param {{ creator?: string, producer?: string, logo?: boolean, issuerLogo?: Uint8Array | null }} [o] logo: the chain's
31
+ * mark, small, beside the title (off unless asked for; @le-space/pdf's LOGOS). issuerLogo: the issuer's own
32
+ * logo, a PNG or JPEG file's bytes, in the head's top right corner (none unless given; an
33
+ * ImageError of @le-space/pdf when the file is no small PNG or JPEG)
23
34
  * @returns {Promise<Uint8Array>}
24
35
  */
25
36
  export async function eigenbelegPdf(
26
37
  doc,
27
- { creator = CREATOR, producer = PRODUCER, logo = false } = {}
38
+ { creator = CREATOR, producer = PRODUCER, logo = false, issuerLogo = null } = {}
28
39
  ) {
29
40
  const created = new Date(doc.issuedAt);
30
41
  const title = `Eigenbeleg ${doc.number}`;
@@ -35,7 +46,18 @@ export async function eigenbelegPdf(
35
46
  logo && Object.hasOwn(LOGOS, doc.chain)
36
47
  ? await pdf.embedPng(await asset(LOGOS[doc.chain]))
37
48
  : null;
49
+ const own = await embedIssuerLogo(pdf, issuerLogo);
38
50
  const M = 48;
51
+ // The document's currency (EUR unless another): its code in the column heads, its decimals in the sums.
52
+ const cur = doc.currency ?? 'EUR';
53
+ const places = currencyPlaces(cur);
54
+ /** @param {string} amount @param {number} [p] */
55
+ const money = (amount, p = places) => deMoney(amount, cur, p);
56
+ /** What a rounded amount of zero was below: a cent, or the currency's smallest unit. */
57
+ const below =
58
+ cur === 'EUR'
59
+ ? 'unter einem Cent'
60
+ : `unter ${money(places ? `0.${'1'.padStart(places, '0')}` : '1')}`;
39
61
  let pageNo = 1;
40
62
  let current = doc.number;
41
63
  const footerRight = `Daten: ${DATA_SOURCES[doc.chain] ?? doc.chainName} · Kurse: siehe Kursquelle`;
@@ -70,6 +92,7 @@ export async function eigenbelegPdf(
70
92
  );
71
93
  gap(4);
72
94
  }
95
+ l.issuerLogo(own, l.y);
73
96
  heading('Eigenbeleg', { face: bold, size: 20 }, mark);
74
97
  text(`Nr. ${number}`, { face: bold, size: 12 });
75
98
  gap(2);
@@ -104,8 +127,8 @@ export async function eigenbelegPdf(
104
127
  const columns = [
105
128
  { title: 'Bewegung', width: 150 },
106
129
  { title: 'Menge', width: 118, right: true },
107
- { title: 'Kurs EUR', width: 52, right: true },
108
- { title: 'Wert EUR', width: 66, right: true },
130
+ { title: `Kurs ${cur}`, width: 52, right: true },
131
+ { title: `Wert ${cur}`, width: 66, right: true },
109
132
  { title: 'Auf dem Beleg', width: width - 386 }
110
133
  ];
111
134
 
@@ -148,14 +171,14 @@ export async function eigenbelegPdf(
148
171
  `${m.what}${e.type === 'received' ? ' (Eingang)' : ''}`,
149
172
  `${deNumber(e.amount)} ${e.asset}`,
150
173
  e.eur ? deNumber(e.eur.rate) : '—',
151
- e.eur ? deEuro(e.eur.value, 4) : '—',
174
+ e.eur ? money(e.eur.value, 4) : '—',
152
175
  m.onIt ? 'ja' : `nein – ${m.why}`
153
176
  ],
154
177
  { color: m.onIt ? BLACK : GREY }
155
178
  );
156
179
  }
157
180
  l.ensure(12);
158
- l.right(`Auf dem Beleg: ${deEuro(t.eurExact, 4)}`, A4[0] - M, 8.5, bold);
181
+ l.right(`Auf dem Beleg: ${money(t.eurExact, 4)}`, A4[0] - M, 8.5, bold);
159
182
  l.y -= 14;
160
183
  }
161
184
 
@@ -166,6 +189,8 @@ export async function eigenbelegPdf(
166
189
  text(sources.length ? `${sources.join('; ')} – jeweils für den Tag der Zahlung (UTC).` : '—', {
167
190
  size: 8.5
168
191
  });
192
+ if (cur !== 'EUR' && sources.length)
193
+ text(`Werte in ${cur}: ${conversionText(cur)}.`, { size: 8.5 });
169
194
  gap(6);
170
195
  if (excluded.length) {
171
196
  text('Nicht auf diesem Eigenbeleg', { face: bold, size: 8.5, color: GREY });
@@ -198,15 +223,11 @@ export async function eigenbelegPdf(
198
223
  ts.flatMap((t) =>
199
224
  t.movements
200
225
  .filter((m) => m.onIt)
201
- .map((m) =>
202
- /** @type {any} */ (m.entry.eur).source
203
- .replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
204
- .replace(/ vom$/, '')
205
- )
226
+ .map((m) => sourceName(/** @type {any} */ (m.entry.eur).source))
206
227
  )
207
228
  )
208
229
  ];
209
- /** The amount line: a label on the left, the euro amount on the right. @param {string} label @param {string} total */
230
+ /** The amount line: a label on the left, the amount on the right. @param {string} label @param {string} total */
210
231
  const amountLine = (label, total) => {
211
232
  l.ensure(40);
212
233
  l.at(label, M, 10, bold);
@@ -231,9 +252,9 @@ export async function eigenbelegPdf(
231
252
  );
232
253
  transaction(t, { big: true });
233
254
  const what = [...new Set(t.movements.filter((m) => m.onIt).map((m) => m.what))].join(', ');
234
- amountLine('Betrag', deEuro(t.eurExact, 2));
235
- if (round(t.eurExact, 2) === '0' && t.eurExact !== '0')
236
- text(`Ungerundet ${deEuro(t.eurExact, 8)} (unter einem Cent).`, { size: 8, color: GREY });
255
+ amountLine('Betrag', money(t.eurExact));
256
+ if (round(t.eurExact, places) === '0' && t.eurExact !== '0')
257
+ text(`Ungerundet ${money(t.eurExact, 8)} (${below}).`, { size: 8, color: GREY });
237
258
  gap(4);
238
259
  field('Was wurde bezahlt', `${what} an ${t.to.label || t.to.address}`);
239
260
  field('Warum kein Fremdbeleg', noInvoice(doc.chain, doc.chainName).why);
@@ -258,14 +279,14 @@ export async function eigenbelegPdf(
258
279
  const n = doc.transactions.length;
259
280
  amountLine(
260
281
  `Summe (${n} ${n === 1 ? 'Position' : 'Positionen'}): ${qty}`,
261
- deEuro(doc.totals.eur, 2)
282
+ money(doc.totals.eur)
262
283
  );
263
284
  const exact = /^0(\.0*)?$/.test(round(doc.totals.eurExact, 4))
264
- ? deEuro(doc.totals.eurExact, 8)
265
- : deEuro(doc.totals.eurExact, 4);
285
+ ? money(doc.totals.eurExact, 8)
286
+ : money(doc.totals.eurExact, 4);
266
287
  const subCent = doc.totals.eur === '0' && doc.totals.eurExact !== '0';
267
288
  text(
268
- `Ungerundet ${exact}${subCent ? ' (unter einem Cent)' : ''}; jede Position zum Tageskurs ihres Zahlungstages.`,
289
+ `Ungerundet ${exact}${subCent ? ` (${below})` : ''}; jede Position zum Tageskurs ihres Zahlungstages.`,
269
290
  { size: 8, color: GREY }
270
291
  );
271
292
  }
@@ -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,27 +5,32 @@
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';
12
14
  import { round } from '@le-space/ledger';
13
15
 
14
- import { DATA_SOURCES, deDate, deEuro, deNumber } from './document.js';
16
+ import { DATA_SOURCES, conversionText, deDate, deFixed, deMoney, deNumber } from './document.js';
15
17
  import { CREATOR, PRODUCER } from './pdf.js';
16
18
  import { isDust, reconciled } from './statement.js';
17
- import { A4, BAND, BLACK, GREY, OK, RULE, WARN, pageLayout } from './layout.js';
19
+ import { drawScene, sceneMeasure } from './chart-pdf.js';
20
+ import { statementChart } from './statement-chart.js';
21
+ import { A4, BAND, BLACK, GREY, OK, RULE, WARN, embedIssuerLogo, pageLayout } from './layout.js';
18
22
 
19
23
  const M = 44;
20
24
  const DARK = { thickness: 0.8, color: rgb(0.2, 0.2, 0.2) };
21
25
 
22
- const COLS = [
26
+ /** The table of bookings; its last column names the statement's currency. @param {string} currency */
27
+ const columns = (currency) => [
23
28
  { title: 'Buchungstag', width: 52 },
24
29
  { title: 'Vorgang', width: 175 },
25
30
  { title: 'Soll', width: 72, right: true },
26
31
  { title: 'Haben', width: 72, right: true },
27
32
  { title: 'Saldo', width: 80, right: true },
28
- { title: 'Wert EUR', width: 56, right: true }
33
+ { title: `Wert ${currency}`, width: 56, right: true }
29
34
  ];
30
35
 
31
36
  /** Quantities in the table: at most 12 decimals, the CSV keeps them all. @param {string} q */
@@ -33,19 +38,30 @@ const qty = (q) => (q ? deNumber(round(q, 12)) : '');
33
38
 
34
39
  /**
35
40
  * @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)
41
+ * @param {{ creator?: string, producer?: string, logo?: boolean, chart?: boolean, issuerLogo?: Uint8Array | null }} [o] logo: the chain's
42
+ * mark, small, beside the title (off unless asked for; @le-space/pdf's LOGOS). chart: the
43
+ * diagram above each list of bookings (on unless switched off). issuerLogo: the issuer's own
44
+ * logo, a PNG or JPEG file's bytes, in the top right corner beside the title (none unless given; an
45
+ * ImageError of @le-space/pdf when the file is no small PNG or JPEG)
38
46
  * @returns {Promise<Uint8Array>}
39
47
  */
40
48
  export async function statementPdf(
41
49
  st,
42
- { creator = CREATOR, producer = PRODUCER, logo = false } = {}
50
+ { creator = CREATOR, producer = PRODUCER, logo = false, chart = true, issuerLogo = null } = {}
43
51
  ) {
44
52
  const created = new Date(st.issuedAt);
45
53
  // Aleph credits: a Verbrauchsauszug in the same layout, valued by its own rule.
46
54
  const aleph = st.chain === 'aleph';
47
55
  // Filecoin Pay: the same, in USDFC and by rail.
48
56
  const pay = st.chain === 'filecoin-pay';
57
+ // The statement's currency (EUR unless another): its code in the column heads and sums.
58
+ const cur = st.currency ?? 'EUR';
59
+ const COLS = columns(cur);
60
+ /** @param {string} amount */
61
+ const money = (amount) => deMoney(amount, cur);
62
+ /** What the values are: in euro as it always said, or how they became another currency. @param {string} eur @param {string} rate */
63
+ const valued = (eur, rate) =>
64
+ cur === 'EUR' ? `Euro-Werte ${eur}` : `Werte in ${cur}: ${rate}, ${conversionText(cur)}`;
49
65
  const title = `${st.title} ${st.number}`;
50
66
  const subject = `${st.title} ${st.chainName} ${st.account}, ${deDate(st.period.from)} – ${deDate(st.period.to)}`;
51
67
  const { pdf, fonts } = await createPdfA();
@@ -54,6 +70,7 @@ export async function statementPdf(
54
70
  logo && Object.hasOwn(LOGOS, st.chain)
55
71
  ? await pdf.embedPng(await asset(LOGOS[st.chain]))
56
72
  : null;
73
+ const own = await embedIssuerLogo(pdf, issuerLogo);
57
74
  const l = pageLayout(pdf, fonts, {
58
75
  margin: M,
59
76
  bottom: 16,
@@ -97,6 +114,7 @@ export async function statementPdf(
97
114
  l.y -= 12;
98
115
  }
99
116
  l.y = Math.min(l.y, leftEnd) - 14;
117
+ l.issuerLogo(own, l.y);
100
118
  l.title(st.title, { face: bold, size: 18 }, mark);
101
119
  text('Konto', { face: bold, size: 7.5, color: GREY });
102
120
  text(st.account, { face: mono, size: 9 });
@@ -120,25 +138,26 @@ export async function statementPdf(
120
138
  l.ensure(14 + lines.length * 11 + 8);
121
139
  l.at('Monatsübersicht', M, 8, bold, GREY);
122
140
  l.right(pay ? s.asset : 'Credits', M + 371 - 4, 7.5, bold, GREY);
123
- l.right('Wert EUR', M + 507 - 4, 7.5, bold, GREY);
141
+ l.right(`Wert ${cur}`, M + 507 - 4, 7.5, bold, GREY);
124
142
  l.y -= 12;
125
143
  for (const ml of lines) {
126
144
  const total = ml === m.usageTotal;
127
145
  const f = total ? bold : regular;
128
146
  l.at(ml.label, M + (total ? 0 : 8), 8, f);
129
147
  l.right(qty(ml.amount), M + 371 - 4, 8, f);
130
- l.right(
131
- ml.eur ? deEuro(ml.eur, 4).replace(' €', '') : '—',
132
- M + 507 - 4,
133
- 8,
134
- f,
135
- ml.eur ? BLACK : GREY
136
- );
148
+ l.right(ml.eur ? deFixed(ml.eur, 4) : '—', M + 507 - 4, 8, f, ml.eur ? BLACK : GREY);
137
149
  l.y -= 11;
138
150
  }
139
151
  l.y -= 8;
140
152
  }
141
153
  }
154
+ // The diagram, above the list of bookings (#889); every figure in it is in the tables.
155
+ const drawn = chart ? statementChart(st, s, { width, measure: sceneMeasure(fonts) }) : null;
156
+ if (drawn) {
157
+ l.ensure(drawn.scene.height + 40);
158
+ drawScene(l.page, drawn.scene, { x: M, top: l.y, fonts });
159
+ l.y -= drawn.scene.height + 12;
160
+ }
142
161
  const head = () => {
143
162
  let x = M;
144
163
  for (const c of COLS) {
@@ -189,7 +208,7 @@ export async function statementPdf(
189
208
  l.right(qty(r.balance), x + COLS[4].width - 4, 8, regular);
190
209
  x += COLS[4].width;
191
210
  l.right(
192
- r.eur ? deEuro(r.eur, 4).replace(' €', '') : '—',
211
+ r.eur ? deFixed(r.eur, 4) : '—',
193
212
  x + COLS[5].width - 4,
194
213
  8,
195
214
  regular,
@@ -237,10 +256,14 @@ export async function statementPdf(
237
256
  l.y -= 4;
238
257
  text(
239
258
  pay
240
- ? `Ausgänge ${deEuro(s.eurOut)} · Eingänge ${deEuro(s.eurIn)} · davon Verbrauch (Aufwand) ${deEuro(s.eurUsage)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – Euro-Werte zum Tageskurs von USDC, an den US-Dollar gebunden wie ${s.asset} (Kurs 00:00 UTC: CoinGecko, sonst Kraken).`
259
+ ? `Ausgänge ${money(s.eurOut)} · Eingänge ${money(s.eurIn)} · davon Verbrauch (Aufwand) ${money(s.eurUsage)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – ${valued(`zum Tageskurs von USDC, an den US-Dollar gebunden wie ${s.asset} (Kurs 00:00 UTC: CoinGecko, sonst Kraken)`, `Tageskurs von USDC, an den US-Dollar gebunden wie ${s.asset} (Kurs 00:00 UTC: CoinGecko, sonst Kraken)`)}.`
241
260
  : aleph
242
- ? `Ausgänge ${deEuro(s.eurOut)} · Eingänge ${deEuro(s.eurIn)} · davon Verbrauch (Aufwand) ${deEuro(s.eurUsage)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – Euro-Werte: USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Listenpreis) × EZB-Referenzkurs USD/EUR des Tages.`
243
- : `Ausgänge ${deEuro(s.eurOut)} · Eingänge ${deEuro(s.eurIn)} · davon Netzwerkgebühren (Aufwand) ${deEuro(s.eurFees)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – Euro-Werte zum Tageskurs (Kurs 00:00 UTC: CoinGecko, sonst Kraken).`,
261
+ ? `Ausgänge ${money(s.eurOut)} · Eingänge ${money(s.eurIn)} · davon Verbrauch (Aufwand) ${money(s.eurUsage)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – ${
262
+ cur === 'EUR'
263
+ ? 'Euro-Werte: USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Listenpreis) × EZB-Referenzkurs USD/EUR des Tages'
264
+ : `Werte in ${cur}: USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Listenpreis)${cur === 'USD' ? '' : `, ${conversionText(cur)}`}`
265
+ }.`
266
+ : `Ausgänge ${money(s.eurOut)} · Eingänge ${money(s.eurIn)} · davon Netzwerkgebühren (Aufwand) ${money(s.eurFees)}${s.unvalued ? ` · ${s.unvalued} Buchung(en) ohne Kurs` : ''} – ${valued('zum Tageskurs (Kurs 00:00 UTC: CoinGecko, sonst Kraken)', 'Tageskurs (Kurs 00:00 UTC: CoinGecko, sonst Kraken)')}.`,
244
267
  { size: 7.5, color: GREY }
245
268
  );
246
269
  l.y -= 12;
package/src/statement.js CHANGED
@@ -20,7 +20,13 @@
20
20
  // 10⁻²⁴ NEAR), so an account that moved tokens is off by a few yocto.
21
21
 
22
22
  import { normalize, sum } from '@le-space/ledger';
23
- import { CHAIN_NAMES, kindText } from './document.js';
23
+ import {
24
+ CHAIN_NAMES,
25
+ checkValued,
26
+ conversionText,
27
+ documentCurrency,
28
+ kindText
29
+ } from './document.js';
24
30
 
25
31
  /** Smaller than the twelve decimals the documents print (and not zero). @param {string} difference */
26
32
  export const isDust = (difference) => /^-?0\.0{12}\d*$/.test(difference);
@@ -54,6 +60,25 @@ export const USAGE_NOTES = /** @type {Record<string, string>} */ ({
54
60
  'filecoin-pay': FILECOIN_PAY_USAGE_NOTE
55
61
  });
56
62
 
63
+ /**
64
+ * The note of a Verbrauchsauszug in the document's currency: what its values
65
+ * are, said for that currency. EUR: the notes above, as they were.
66
+ *
67
+ * @param {string} chain from USAGE_NOTES
68
+ * @param {string} currency
69
+ */
70
+ export function usageNote(chain, currency) {
71
+ const note = USAGE_NOTES[chain];
72
+ if (currency === 'EUR') return note;
73
+ const head = note.slice(0, note.indexOf('Euro-Wert:'));
74
+ if (chain === 'aleph') {
75
+ const price =
76
+ 'USD-Preis je Credit (letzter Kauf am oder vor dem Tag, sonst Alephs Listenpreis von 1 USD je 1.000.000 Credits)';
77
+ return `${head}Wert in ${currency}: ${price}${currency === 'USD' ? '' : `, ${conversionText(currency)}`}.`;
78
+ }
79
+ return `${head}Wert in ${currency}: USDFC ist an den US-Dollar gebunden und wird zum Tageskurs von USDC bewertet, ${conversionText(currency)}.`;
80
+ }
81
+
57
82
  export const STATEMENT_NOTE =
58
83
  'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
59
84
  'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
@@ -69,7 +94,7 @@ export const STATEMENT_NOTE =
69
94
  * @property {string} debit amount out, positive, or ''
70
95
  * @property {string} credit amount in, positive, or ''
71
96
  * @property {string} balance running balance after it
72
- * @property {string} eur signed EUR value at the day's rate, or ''
97
+ * @property {string} eur signed value at the day's rate, in the statement's currency (EUR unless another), or ''
73
98
  * @property {string} beleg the Eigenbeleg's number, when the booking has one
74
99
  * @property {boolean} fee
75
100
  * @property {boolean} usage consumption billed from the balance (Aleph credits, a Filecoin Pay settlement)
@@ -144,6 +169,8 @@ export function monthly(rows) {
144
169
  * @param {Map<string, string>} [p.belege] hash → Eigenbeleg number
145
170
  * @param {string} [p.number]
146
171
  * @param {string} [p.issuedAt]
172
+ * @param {string} [p.currency] the statement's currency (DOCUMENT_CURRENCIES), EUR when not
173
+ * given; the entries are valued in it, and the fields named `eur…` hold values in it
147
174
  */
148
175
  export function buildStatement({
149
176
  payer,
@@ -158,8 +185,11 @@ export function buildStatement({
158
185
  at = null,
159
186
  belege = new Map(),
160
187
  number,
161
- issuedAt
188
+ issuedAt,
189
+ currency: asked
162
190
  }) {
191
+ const currency = documentCurrency(asked);
192
+ checkValued(entries, currency);
163
193
  // An Aleph credit purchase (kind `swap`) is the payment on another chain; the
164
194
  // credits it bought are the incoming row. Only that row belongs on the statement.
165
195
  const mine = entries.filter(
@@ -236,11 +266,12 @@ export function buildStatement({
236
266
  network,
237
267
  testnet: network !== 'mainnet',
238
268
  period,
269
+ currency,
239
270
  method,
240
271
  at,
241
272
  sections,
242
273
  unlisted: mine.filter((e) => !e.priceAs && !assets.includes(e.asset)).length,
243
- note: usage ? USAGE_NOTES[chain] : STATEMENT_NOTE
274
+ note: usage ? usageNote(chain, currency) : STATEMENT_NOTE
244
275
  };
245
276
  }
246
277
 
package/src/value.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
- // Every entry with its euro value on the day it was made. Where the rate
2
+ // Every entry with its value on the day it was made: in euro, or in the
3
+ // document's currency when another is asked for (`currency`; the rates handed
4
+ // in are then in that currency, and say so). Where the rate
3
5
  // comes from is the caller's (the pipeline asks @le-space/rates); this file
4
6
  // only applies it, and names a fixed rate for tests and offline demos.
5
7
  //
@@ -10,17 +12,22 @@
10
12
 
11
13
  import { multiply } from '@le-space/ledger';
12
14
 
15
+ import { documentCurrency } from './document.js';
16
+
13
17
  /**
14
18
  * @typedef {object} Rate
15
- * @property {string} rate EUR per unit, decimal string
19
+ * @property {string} rate EUR per unit (or the document currency's), decimal string
16
20
  * @property {string} source human-readable: where and which moment, printed on the document
17
21
  * @property {string} date YYYY-MM-DD the rate is for
22
+ * @property {string} [currency] what the rate is in; EUR when not given
18
23
  */
19
24
 
20
25
  /** @typedef {{ rateFor: (asset: string, date: string) => Promise<Rate | null> }} Rates */
21
26
 
22
27
  /**
23
- * @typedef {import('@le-space/ledger').LedgerEntry & { eur: { value: string, rate: string, source: string } | null }} ValuedEntry
28
+ * @typedef {import('@le-space/ledger').LedgerEntry & { eur: { value: string, rate: string, source: string, currency?: string } | null }} ValuedEntry
29
+ * `eur`: the value, named so since every document was in euro; in another
30
+ * currency it carries that `currency`
24
31
  */
25
32
 
26
33
  /**
@@ -29,10 +36,21 @@ import { multiply } from '@le-space/ledger';
29
36
  * `unitPrice` in USD (Aleph credits) is valued at that price and the day's rate for USD.
30
37
  *
31
38
  * @param {import('@le-space/ledger').LedgerEntry[]} entries
32
- * @param {Rates} rates
39
+ * @param {Rates} rates in the document's currency
40
+ * @param {{ currency?: string }} [o] the document's currency (DOCUMENT_CURRENCIES), EUR when not given
33
41
  * @returns {Promise<ValuedEntry[]>}
34
42
  */
35
- export async function valueEntries(entries, rates) {
43
+ export async function valueEntries(entries, rates, { currency: asked } = {}) {
44
+ const currency = documentCurrency(asked);
45
+ // An EUR value stays as it always was; another currency is named on it.
46
+ const mark = currency === 'EUR' ? {} : { currency };
47
+ /** A rate in another currency than the document's is the caller's mistake, not a value. @param {string} asset @param {string} date */
48
+ const rateFor = async (asset, date) => {
49
+ const r = await rates.rateFor(asset, date);
50
+ if (r && (r.currency ?? 'EUR') !== currency)
51
+ throw new Error(`a rate in ${r.currency ?? 'EUR'} for a document in ${currency}`);
52
+ return r;
53
+ };
36
54
  const out = [];
37
55
  for (const e of entries) {
38
56
  const unit =
@@ -40,35 +58,58 @@ export async function valueEntries(entries, rates) {
40
58
  /** @type {any} */ (e).unitPrice
41
59
  );
42
60
  if (!e.priceAs && e.success && unit?.currency === 'USD' && unit.amount) {
43
- const usd = await rates.rateFor('USD', e.date);
44
61
  const how = unit.source === 'purchase' ? 'Kaufpreis' : 'Listenpreis';
62
+ // A document in USD: Aleph's own price, no rate at all.
63
+ if (currency === 'USD') {
64
+ out.push({
65
+ ...e,
66
+ eur: {
67
+ value: multiply(e.amount, unit.amount, 8),
68
+ rate: unit.amount,
69
+ source: `Aleph ${how} ${unit.amount} USD je Credit`,
70
+ ...mark
71
+ }
72
+ });
73
+ continue;
74
+ }
75
+ const usd = await rateFor('USD', e.date);
45
76
  out.push({
46
77
  ...e,
47
78
  eur: usd
48
79
  ? {
49
80
  value: multiply(multiply(e.amount, unit.amount, 12), usd.rate, 8),
50
81
  rate: multiply(unit.amount, usd.rate, 14),
51
- source: `Aleph ${how} ${unit.amount} USD je Credit × ${usd.source}`
82
+ source: `Aleph ${how} ${unit.amount} USD je Credit × ${usd.source}`,
83
+ ...mark
52
84
  }
53
85
  : null
54
86
  });
55
87
  continue;
56
88
  }
57
- const r = e.priceAs && e.success ? await rates.rateFor(e.priceAs, e.date) : null;
89
+ const r = e.priceAs && e.success ? await rateFor(e.priceAs, e.date) : null;
58
90
  out.push({
59
91
  ...e,
60
- eur: r ? { value: multiply(e.amount, r.rate, 8), rate: r.rate, source: r.source } : null
92
+ eur: r
93
+ ? { value: multiply(e.amount, r.rate, 8), rate: r.rate, source: r.source, ...mark }
94
+ : null
61
95
  });
62
96
  }
63
97
  return out;
64
98
  }
65
99
 
66
- /** Fixed rates, for tests and offline demos. @param {Record<string, string>} table `NEAR:2026-10-05` → `3.8796` @returns {Rates} */
67
- export function fixedRates(table) {
100
+ /**
101
+ * Fixed rates, for tests and offline demos.
102
+ *
103
+ * @param {Record<string, string>} table `NEAR:2026-10-05` → `3.8796`
104
+ * @param {string} [currency] what the table's rates are in; EUR when not given
105
+ * @returns {Rates}
106
+ */
107
+ export function fixedRates(table, currency) {
108
+ const mark = currency && currency !== 'EUR' ? { currency } : {};
68
109
  return {
69
110
  async rateFor(asset, date) {
70
111
  const rate = table[`${asset}:${date}`] ?? table[asset];
71
- return rate ? { rate, source: `fester Testkurs (${asset})`, date } : null;
112
+ return rate ? { rate, source: `fester Testkurs (${asset})`, date, ...mark } : null;
72
113
  }
73
114
  };
74
115
  }