@le-space/eigenbeleg 0.0.0-stage → 0.1.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
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @le-space/eigenbeleg
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Eigenbeleg and the Kontoauszug of Le Space's tools – [Belege](https://github.com/Le-Space/belege) and the [Eigenbeleg](https://github.com/Le-Space/eigenbeleg-agent) API and web UI: what they say, drawn as PDF/A-2b ([`@le-space/pdf`](../pdf), text in any script) and written as CSV. Runs in a browser and in Node; the same document is the same file in both. The documents are German, for German bookkeeping.
4
+
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
+
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)`, `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; Aleph credits as a monthly **Verbrauchsauszug**. `statementPdf(st)`.
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
+ - **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
+ 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
+ ```bash
15
+ pnpm --filter @le-space/eigenbeleg test # Node, and every document byte for byte in Chromium
16
+ pnpm --filter @le-space/eigenbeleg pdfa-samples out/ # one of each, for veraPDF (CI runs it)
17
+ ```
18
+
19
+ The model, the CSV, the Kontoauszug and the PDF layout came from Eigenbeleg's `packages/eigenbeleg` at e6cde90; the booking's Eigenbeleg and the statement layout from Belege's `app/src/lib/receipts/eigenbeleg*.js` and `app/src/lib/pdf/statement-layout.js` (moved with their history). AGPL-3.0-or-later.
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@le-space/eigenbeleg",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
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
+ "license": "AGPL-3.0-or-later",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Le-Space/belege.git",
10
+ "directory": "packages/eigenbeleg"
11
+ },
12
+ "homepage": "https://github.com/Le-Space/belege/tree/main/packages/eigenbeleg#readme",
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": "./src/index.js",
16
+ "./document": "./src/document.js",
17
+ "./value": "./src/value.js",
18
+ "./csv": "./src/csv.js",
19
+ "./statement": "./src/statement.js",
20
+ "./booking": "./src/booking.js",
21
+ "./booking-pdf": "./src/booking-pdf.js",
22
+ "./statement-layout": "./src/statement-layout.js"
23
+ },
24
+ "files": [
25
+ "src"
26
+ ],
27
+ "engines": {
28
+ "node": ">=22"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "provenance": true
33
+ },
34
+ "dependencies": {
35
+ "pdf-lib": "1.17.1",
36
+ "uqr": "0.1.3",
37
+ "@le-space/ledger": "^0.3.0",
38
+ "@le-space/pdf": "^0.1.0"
39
+ },
40
+ "devDependencies": {
41
+ "@noble/hashes": "2.4.0",
42
+ "prettier": "3.6.2",
43
+ "unpdf": "1.8.1",
44
+ "@le-space/chains": "^0.3.0",
45
+ "@le-space/browser-test": "0.1.0"
46
+ },
47
+ "scripts": {
48
+ "test": "node --test --test-reporter=spec \"test/*.test.js\"",
49
+ "lint": "prettier --check src test scripts",
50
+ "pdfa-samples": "node scripts/pdfa-samples.js"
51
+ }
6
52
  }
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Draws the Eigenbeleg of one booking (booking.js) as an A4 PDF/A-2b in
3
+ // Eigenbeleg's layout (layout.js), with text in any script (@le-space/pdf):
4
+ // the head with the number, issuer and date, the note, the payment, an own
5
+ // wallet's transaction in full with its explorer link as a QR code, the
6
+ // amount, what was paid and why there is no receipt from the other side, and
7
+ // a line to sign.
8
+ //
9
+ // The text is German: the document is for German bookkeeping.
10
+
11
+ import { createPdfA, savePdfA } from '@le-space/pdf';
12
+ import { fromUnits } from '@le-space/ledger';
13
+
14
+ import { bookingNote, bookingNotInvoice } from './booking.js';
15
+ import { deDate, deEuro, deNumber } from './document.js';
16
+ import { A4, BLACK, GREY, pageLayout } from './layout.js';
17
+
18
+ /**
19
+ * @param {import('./booking.js').BookingEigenbeleg} doc
20
+ * @param {{ creator?: string, producer?: string }} [o] what made it: `Belege` when not given
21
+ * @returns {Promise<Uint8Array>}
22
+ */
23
+ export async function bookingPdf(doc, { creator = 'Belege', producer } = {}) {
24
+ const created = new Date(doc.createdAt);
25
+ const { pdf, fonts } = await createPdfA();
26
+ const { regular, bold, mono } = fonts;
27
+ const M = 48;
28
+ let pageNo = 1;
29
+ const footer = (/** @type {import('./layout.js').Layout} */ l) =>
30
+ regular.draw(l.page, `${doc.number} · Seite ${pageNo}`, {
31
+ x: M,
32
+ y: M / 2,
33
+ size: 7,
34
+ color: GREY
35
+ });
36
+ const l = pageLayout(pdf, fonts, {
37
+ margin: M,
38
+ leavePage: footer,
39
+ enterPage: () => {
40
+ pageNo++;
41
+ }
42
+ });
43
+ const { text, gap, field } = l;
44
+ const width = l.width;
45
+ const out = doc.amountCents < 0;
46
+
47
+ // ---- head
48
+ text('Eigenbeleg', { face: bold, size: 20 });
49
+ text(`Nr. ${doc.number}`, { face: bold, size: 12 });
50
+ gap(2);
51
+ text('Beleg für eine Zahlung, zu der es keinen Beleg der Gegenseite gibt.', { size: 10 });
52
+ gap(10);
53
+ const top = l.y;
54
+ const half = width / 2 - 10;
55
+ text('Aussteller', { face: bold, size: 8.5, color: GREY, max: half });
56
+ text(doc.issuer || '—', { face: bold, size: 10, max: half });
57
+ if (doc.issuerAddress) text(doc.issuerAddress, { size: 9.5, max: half });
58
+ const leftEnd = l.y;
59
+ l.y = top;
60
+ const rx = M + width / 2 + 10;
61
+ text('Ausgestellt am', { x: rx, face: bold, size: 8.5, color: GREY });
62
+ text(`${deDate(doc.createdAt)}, ${doc.createdAt.slice(11, 16)} UTC`, { x: rx });
63
+ gap(3);
64
+ text(out ? 'Empfänger' : 'Zahlende Seite', { x: rx, face: bold, size: 8.5, color: GREY });
65
+ text(doc.counterparty || '—', { x: rx });
66
+ l.y = Math.min(l.y, leftEnd);
67
+ gap(8);
68
+ text('Konto', { face: bold, size: 8.5, color: GREY });
69
+ text(doc.account || '—', { size: 9.5 });
70
+ gap(10);
71
+ l.box(bookingNote(Boolean(doc.chain)));
72
+ gap(12);
73
+
74
+ // ---- the payment
75
+ field('Datum der Zahlung', deDate(doc.date));
76
+ if (doc.purpose && doc.purpose !== doc.description) field('Verwendungszweck', doc.purpose);
77
+ if (doc.crypto) {
78
+ const c = doc.crypto;
79
+ field('Menge', `${deNumber(fromUnits(c.quantity, c.decimals))} ${c.asset}`);
80
+ field(
81
+ 'Kurs',
82
+ `${deNumber(c.rate)} EUR je ${c.asset} · ${c.source}${c.at ? `, ${deDate(c.at)}` : ''}`
83
+ );
84
+ }
85
+ gap(8);
86
+
87
+ if (doc.chain) {
88
+ const c = doc.chain;
89
+ const side = 96;
90
+ const textMax = width - side - 12;
91
+ l.ensure(150);
92
+ l.rule();
93
+ gap(8);
94
+ const qrTop = l.y;
95
+ text(`Zahlung auf ${c.chain}${c.at ? ` · ${deDate(c.at)} ${c.at.slice(11, 19)} UTC` : ''}`, {
96
+ face: bold,
97
+ size: 9.5,
98
+ max: textMax
99
+ });
100
+ gap(2);
101
+ /** @param {import('./booking.js').Party} p */
102
+ const party = (p) => {
103
+ const note = [p.label, p.own ? 'eigene Wallet' : ''].filter(Boolean).join(', ');
104
+ if (!p.address) return note || '—';
105
+ return note && p.address !== p.label ? `${p.address} (${note})` : p.address;
106
+ };
107
+ field('Transaktion', c.hash, { face: mono, size: 7.5, max: textMax });
108
+ field('Von', party(c.from), { face: mono, size: 7.5, max: textMax });
109
+ field('An', party(c.to), { face: mono, size: 7.5, max: textMax });
110
+ if (c.explorerUrl) {
111
+ field('Block-Explorer', c.explorerUrl, { face: mono, size: 6.5, max: textMax });
112
+ l.qr(c.explorerUrl, A4[0] - M - side, qrTop, side);
113
+ l.y = Math.min(l.y, qrTop - side - 4);
114
+ }
115
+ gap(3);
116
+ const columns = [
117
+ { title: 'Bewegung', width: 170 },
118
+ { title: 'Menge', width: 150, right: true },
119
+ { title: 'Wert EUR', width: 90, right: true },
120
+ { title: 'Gebucht', width: width - 410 }
121
+ ];
122
+ const header = () =>
123
+ l.row(
124
+ columns,
125
+ columns.map((x) => x.title),
126
+ { face: bold, color: GREY }
127
+ );
128
+ header();
129
+ for (const m of c.movements)
130
+ l.row(columns, [m.what, m.quantity || '—', m.euro || '—', m.booked ? 'ja' : 'nein'], {
131
+ color: m.booked ? BLACK : GREY,
132
+ header
133
+ });
134
+ gap(6);
135
+ } else if (doc.txRef) field('Referenz', doc.txRef, { face: mono, size: 7.5 });
136
+
137
+ // ---- the amount, what and why
138
+ l.ensure(40);
139
+ l.rule();
140
+ gap(8);
141
+ l.at('Betrag', M, 10, bold);
142
+ l.right(deEuro(fromUnits(String(doc.amountCents), 2), 2), A4[0] - M, 11, bold);
143
+ l.y -= 18;
144
+ field('Was wurde bezahlt', doc.description);
145
+ field('Warum kein Fremdbeleg', doc.reason);
146
+ field('Erstellt', `${deDate(doc.createdAt)}${doc.createdBy ? ` von ${doc.createdBy}` : ''}`);
147
+
148
+ // ---- what it is not, and the line to sign
149
+ gap(8);
150
+ text(bookingNotInvoice(creator), { size: 8.5, color: GREY });
151
+ gap(24);
152
+ l.ensure(40);
153
+ l.page.drawLine({
154
+ start: { x: M, y: l.y },
155
+ end: { x: M + 230, y: l.y },
156
+ thickness: 0.6,
157
+ color: BLACK
158
+ });
159
+ l.y -= 4;
160
+ text('Ort, Datum, Unterschrift', { size: 8, color: GREY });
161
+ footer(l);
162
+
163
+ return savePdfA(pdf, {
164
+ title: `Eigenbeleg ${doc.number}`,
165
+ author: doc.issuer,
166
+ subject: `Eigenbeleg für eine Zahlung am ${deDate(doc.date)}`,
167
+ creator,
168
+ ...(producer ? { producer } : {}),
169
+ created,
170
+ seed: `${doc.number}|${doc.createdAt}|${doc.issuer}`
171
+ });
172
+ }
package/src/booking.js ADDED
@@ -0,0 +1,88 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // The Eigenbeleg of one booking, as Belege writes it: a receipt the company
3
+ // writes itself for a payment that has no receipt from the other side – a
4
+ // bank booking, or a payment on a blockchain that issues no invoices.
5
+ //
6
+ // It says what was paid, to whom (or by whom), when and how much, and why
7
+ // there is no receipt from the other side; who wrote it and when, with a line
8
+ // to sign. For a crypto payment it also carries quantity, rate with its
9
+ // source, and – for an own wallet's booking – the transaction in full: the
10
+ // whole hash, sender and receiver with their full addresses, and every
11
+ // movement of the transaction the books know, the gas included (Belege #126).
12
+ // The booking's context (its account, the address book, the other legs) is
13
+ // the caller's to gather; booking-pdf.js draws the document.
14
+ //
15
+ // The numbers are a range per year: EB-YYYY-NNN.
16
+ //
17
+ // Moved from Belege's app/src/lib/receipts/eigenbeleg.js (its types and the
18
+ // number range); the rest of that file stays in the app.
19
+
20
+ const NUMBER = /^EB-(\d{4})-(\d{3,})$/;
21
+
22
+ /**
23
+ * The next number in the Eigenbeleg range of a year: EB-2026-001, EB-2026-002, …
24
+ *
25
+ * @param {Record<string, any>[]} receipts all of them, set aside ones too
26
+ * @param {string} year YYYY
27
+ */
28
+ export function nextSelfNumber(receipts, year) {
29
+ let highest = 0;
30
+ for (const r of receipts) {
31
+ const m = NUMBER.exec(String(r.selfNumber ?? ''));
32
+ if (m && m[1] === year) highest = Math.max(highest, Number(m[2]));
33
+ }
34
+ return `EB-${year}-${String(highest + 1).padStart(3, '0')}`;
35
+ }
36
+
37
+ /**
38
+ * @typedef {object} Party one side of a wallet transaction
39
+ * @property {string} label a name from the address book, '' when none
40
+ * @property {string} address the whole address
41
+ * @property {boolean} own an own wallet
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} ChainDetails an own wallet's transaction, in full
46
+ * @property {string} chain the chain's name
47
+ * @property {string} hash the whole transaction hash, never shortened
48
+ * @property {string} explorerUrl
49
+ * @property {string} at ISO 8601, when the block was made ('' when not known)
50
+ * @property {Party} from
51
+ * @property {Party} to
52
+ * @property {{ what: string, quantity: string, euro: string, booked: boolean }[]} movements
53
+ * every movement of the transaction the books know: its legs, the gas, and a
54
+ * swap's side that is not booked (a token not in the chain's list); quantity
55
+ * and euro as they are printed
56
+ */
57
+
58
+ /**
59
+ * @typedef {object} BookingEigenbeleg what the PDF shows
60
+ * @property {string} number
61
+ * @property {string} issuer our company, '' when none is set
62
+ * @property {string} [issuerAddress] its postal address, lines separated by \n
63
+ * @property {string} date YYYY-MM-DD, of the payment
64
+ * @property {number} amountCents signed, from the account's view
65
+ * @property {string} account
66
+ * @property {string} counterparty
67
+ * @property {string} purpose the bank's purpose, as the booking has it
68
+ * @property {string} description what was paid for
69
+ * @property {string} reason why there is no receipt from the other side
70
+ * @property {string} txRef '' when none
71
+ * @property {{ asset: string, quantity: string, decimals: number, rate: string, source: string, at: string } | null} crypto
72
+ * quantity in the asset's smallest unit; source as it is printed (e.g. "CoinGecko")
73
+ * @property {ChainDetails | null} [chain] an own wallet's transaction in full
74
+ * @property {string} createdAt ISO 8601
75
+ * @property {string} createdBy who wrote it (a name, or the identity's DID)
76
+ */
77
+
78
+ /** The note in the box on top. @param {boolean} onChain */
79
+ export const bookingNote = (onChain) =>
80
+ `Eigenbeleg. Für diese Zahlung gibt es keinen Beleg der Gegenseite. Ausgestellt auf Grundlage der Buchung${
81
+ onChain
82
+ ? ' und der öffentlichen Transaktion; sie ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.'
83
+ : '.'
84
+ }`;
85
+
86
+ /** What it is not, above the line to sign. @param {string} creator */
87
+ export const bookingNotInvoice = (creator) =>
88
+ `Erstellt mit ${creator}. Ein Eigenbeleg ersetzt einen fehlenden Beleg der Gegenseite; er ist keine Rechnung und berechtigt nicht zum Vorsteuerabzug. Ob er anerkannt wird, klärt die Steuerberatung.`;
package/src/csv.js ADDED
@@ -0,0 +1,106 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // The Eigenbeleg as CSV, for a German spreadsheet or bookkeeping import:
3
+ // semicolons, decimal commas, UTF-8 with BOM, CRLF. Every entry of the
4
+ // period is a line, the ones not on the Eigenbeleg too, with the reason.
5
+ //
6
+ // A cell that starts like a formula (= + - @) is prefixed with ' so a
7
+ // spreadsheet shows it as text: account names and memos come from the chain,
8
+ // where anyone can write anything.
9
+
10
+ import { round } from '@le-space/ledger';
11
+ import { KIND_TEXT } from './document.js';
12
+
13
+ const HEADER = [
14
+ 'Belegnummer',
15
+ 'Position',
16
+ 'Datum (UTC)',
17
+ 'Uhrzeit (UTC)',
18
+ 'Chain',
19
+ 'Netz',
20
+ 'Eigene Adresse',
21
+ 'Art',
22
+ 'Richtung',
23
+ 'Gegenpartei',
24
+ 'Asset',
25
+ 'Token-Contract',
26
+ 'Menge',
27
+ 'Kurs EUR',
28
+ 'Wert EUR',
29
+ 'Kursquelle',
30
+ 'Transaktions-Hash',
31
+ 'Explorer',
32
+ 'Auf Eigenbeleg',
33
+ 'Hinweis'
34
+ ];
35
+
36
+ const DIRECTION = { sent: 'Ausgang', received: 'Eingang', fee: 'Gebühr' };
37
+
38
+ /** `-0.5` → `-0,5` (a plain number for a spreadsheet: no grouping). @param {string} s */
39
+ const num = (s) => String(s).replace('.', ',');
40
+
41
+ /** @param {unknown} v */
42
+ function cell(v) {
43
+ let s = String(v ?? '');
44
+ if (/^[=+\-@\t\r]/.test(s) && !/^-?\d+(,\d+)?$/.test(s)) s = `'${s}`;
45
+ return /[;"\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
46
+ }
47
+
48
+ /**
49
+ * @param {import('./document.js').EigenbelegDocument} doc
50
+ * @returns {string}
51
+ */
52
+ export function eigenbelegCsv(doc) {
53
+ /** @type {unknown[][]} */
54
+ const rows = [HEADER];
55
+ const numberOf = (/** @type {number | string} */ pos) =>
56
+ doc.layout === 'single' ? (doc.transactions[Number(pos) - 1]?.number ?? '') : doc.number;
57
+ /** @param {import('./value.js').ValuedEntry} e @param {string | number} pos @param {boolean} on @param {string} why */
58
+ const line = (e, pos, on, why) => [
59
+ on ? numberOf(pos) : '',
60
+ pos,
61
+ e.date,
62
+ e.time.slice(11, 19),
63
+ e.chain,
64
+ e.network,
65
+ e.account,
66
+ KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
67
+ DIRECTION[e.type],
68
+ e.counterpartyLabel ? `${e.counterpartyLabel} (${e.counterparty})` : e.counterparty,
69
+ e.asset,
70
+ e.contract,
71
+ num(e.amount),
72
+ e.eur ? num(e.eur.rate) : '',
73
+ e.eur ? num(e.eur.value) : '',
74
+ e.eur?.source ?? '',
75
+ e.hash,
76
+ e.explorerUrl,
77
+ on ? 'ja' : 'nein',
78
+ why
79
+ ];
80
+ for (const p of doc.positions) rows.push(line(p.entry, p.pos, true, ''));
81
+ for (const x of doc.excluded) rows.push(line(x.entry, '', false, x.why));
82
+ rows.push([]);
83
+ rows.push([
84
+ doc.layout === 'single' ? '' : doc.number,
85
+ 'Summe',
86
+ '',
87
+ '',
88
+ doc.chain,
89
+ doc.network,
90
+ '',
91
+ '',
92
+ '',
93
+ '',
94
+ '',
95
+ '',
96
+ '',
97
+ '',
98
+ num(round(`-${doc.totals.eurExact}`, 2)),
99
+ `gerundet auf Cent, ungerundet ${doc.totals.eurExact === '0' ? '0' : '-' + num(doc.totals.eurExact)}`,
100
+ '',
101
+ '',
102
+ 'ja',
103
+ ''
104
+ ]);
105
+ return '\uFEFF' + rows.map((r) => r.map(cell).join(';')).join('\r\n') + '\r\n';
106
+ }