@le-space/eigenbeleg 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,276 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ //
3
+ // The Kontoauszug as an A4 PDF/A-2b, laid out like a bank statement:
4
+ // holder and account in the head, per asset the opening balance, a table of
5
+ // bookings (date, text, debit, credit, running balance, EUR value), the
6
+ // closing balance with its check against the chain, and the sums a
7
+ // bookkeeper needs. German, for German bookkeeping. Aleph Cloud credits get
8
+ // the same layout titled »Verbrauchsauszug« (`st.title`).
9
+
10
+ import { rgb } from 'pdf-lib';
11
+ import { asset, createPdfA, LOGOS, savePdfA, wrapText } from '@le-space/pdf';
12
+ import { round } from '@le-space/ledger';
13
+
14
+ import { DATA_SOURCES, deDate, deEuro, deNumber } from './document.js';
15
+ import { CREATOR, PRODUCER } from './pdf.js';
16
+ import { isDust, reconciled } from './statement.js';
17
+ import { A4, BAND, BLACK, GREY, OK, RULE, WARN, pageLayout } from './layout.js';
18
+
19
+ const M = 44;
20
+ const DARK = { thickness: 0.8, color: rgb(0.2, 0.2, 0.2) };
21
+
22
+ const COLS = [
23
+ { title: 'Buchungstag', width: 52 },
24
+ { title: 'Vorgang', width: 175 },
25
+ { title: 'Soll', width: 72, right: true },
26
+ { title: 'Haben', width: 72, right: true },
27
+ { title: 'Saldo', width: 80, right: true },
28
+ { title: 'Wert EUR', width: 56, right: true }
29
+ ];
30
+
31
+ /** Quantities in the table: at most 12 decimals, the CSV keeps them all. @param {string} q */
32
+ const qty = (q) => (q ? deNumber(round(q, 12)) : '');
33
+
34
+ /**
35
+ * @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)
38
+ * @returns {Promise<Uint8Array>}
39
+ */
40
+ export async function statementPdf(
41
+ st,
42
+ { creator = CREATOR, producer = PRODUCER, logo = false } = {}
43
+ ) {
44
+ const created = new Date(st.issuedAt);
45
+ // Aleph credits: a Verbrauchsauszug in the same layout, valued by its own rule.
46
+ const aleph = st.chain === 'aleph';
47
+ const title = `${st.title} ${st.number}`;
48
+ const subject = `${st.title} ${st.chainName} ${st.account}, ${deDate(st.period.from)} – ${deDate(st.period.to)}`;
49
+ const { pdf, fonts } = await createPdfA();
50
+ const { regular, bold, mono } = fonts;
51
+ const mark =
52
+ logo && Object.hasOwn(LOGOS, st.chain)
53
+ ? await pdf.embedPng(await asset(LOGOS[st.chain]))
54
+ : null;
55
+ const l = pageLayout(pdf, fonts, {
56
+ margin: M,
57
+ bottom: 16,
58
+ enterPage: (p) => {
59
+ p.at(`${st.title} ${st.number} · ${st.account}`, M, 8, regular, GREY);
60
+ p.y -= 18;
61
+ }
62
+ });
63
+ const { text } = l;
64
+ const width = l.width;
65
+ /** @param {number} y @param {{ thickness: number, color: import('pdf-lib').Color }} [o] */
66
+ const line = (y, o = DARK) =>
67
+ l.page.drawLine({ start: { x: M, y }, end: { x: A4[0] - M, y }, ...o });
68
+
69
+ // ---- head: like a bank's, with the holder's address window on the left
70
+ if (st.testnet) {
71
+ text('TESTNET – keine echten Werte. Kurse des Mainnet-Assets nur zur Veranschaulichung.', {
72
+ face: bold,
73
+ size: 8.5,
74
+ color: WARN
75
+ });
76
+ l.y -= 4;
77
+ }
78
+ const top = l.y;
79
+ text('Kontoinhaber', { face: bold, size: 7.5, color: GREY, max: 250 });
80
+ text(st.holder.name, { face: bold, size: 10, max: 250 });
81
+ text(st.holder.address, { size: 9.5, max: 250 });
82
+ const leftEnd = l.y;
83
+ l.y = top;
84
+ const rx = M + 300;
85
+ const facts = [
86
+ // The label column is 72 pt wide: »Verbrauchsauszug« does not fit.
87
+ [st.title === 'Kontoauszug' ? 'Kontoauszug' : 'Auszug-Nr.', st.number],
88
+ ['Zeitraum', `${deDate(st.period.from)} – ${deDate(st.period.to)}`],
89
+ ['Chain', `${st.chainName} (${st.network})`],
90
+ ['Erstellt am', `${deDate(st.issuedAt)}, ${st.issuedAt.slice(11, 16)} UTC`]
91
+ ];
92
+ for (const [k, v] of facts) {
93
+ bold.draw(l.page, k, { x: rx, y: l.y - 8.5, size: 8, color: GREY });
94
+ regular.draw(l.page, v, { x: rx + 72, y: l.y - 8.5, size: 8.5 });
95
+ l.y -= 12;
96
+ }
97
+ l.y = Math.min(l.y, leftEnd) - 14;
98
+ l.title(st.title, { face: bold, size: 18 }, mark);
99
+ text('Konto', { face: bold, size: 7.5, color: GREY });
100
+ text(st.account, { face: mono, size: 9 });
101
+ l.y -= 6;
102
+ text(st.note, { size: 8, color: GREY });
103
+ l.y -= 10;
104
+
105
+ // ---- one section per asset
106
+ for (const s of st.sections) {
107
+ l.ensure(90);
108
+ l.page.drawRectangle({ x: M, y: l.y - 18, width, height: 18, color: BAND });
109
+ bold.draw(l.page, `${s.asset} · ${st.account}`, { x: M + 6, y: l.y - 12.5, size: 9.5 });
110
+ l.y -= 24;
111
+ // The month in sums, first (#24): what the books take as one booking each; the rows below are the proof.
112
+ if (aleph) {
113
+ const m = s.monthly;
114
+ const lines = [m.usage, m.usageTotal, m.purchases, m.transfersIn, m.transfersOut]
115
+ .flat()
116
+ .filter((x) => x !== null);
117
+ if (lines.length) {
118
+ l.ensure(14 + lines.length * 11 + 8);
119
+ l.at('Monatsübersicht', M, 8, bold, GREY);
120
+ l.right('Credits', M + 371 - 4, 7.5, bold, GREY);
121
+ l.right('Wert EUR', M + 507 - 4, 7.5, bold, GREY);
122
+ l.y -= 12;
123
+ for (const ml of lines) {
124
+ const total = ml === m.usageTotal;
125
+ const f = total ? bold : regular;
126
+ l.at(ml.label, M + (total ? 0 : 8), 8, f);
127
+ l.right(qty(ml.amount), M + 371 - 4, 8, f);
128
+ l.right(
129
+ ml.eur ? deEuro(ml.eur, 4).replace(' €', '') : '—',
130
+ M + 507 - 4,
131
+ 8,
132
+ f,
133
+ ml.eur ? BLACK : GREY
134
+ );
135
+ l.y -= 11;
136
+ }
137
+ l.y -= 8;
138
+ }
139
+ }
140
+ const head = () => {
141
+ let x = M;
142
+ for (const c of COLS) {
143
+ if (c.right) l.right(c.title, x + c.width - 4, 7.5, bold, GREY);
144
+ else l.at(c.title, x, 7.5, bold, GREY);
145
+ x += c.width;
146
+ }
147
+ l.y -= 11;
148
+ line(l.y);
149
+ l.y -= 3;
150
+ };
151
+ head();
152
+ // opening balance
153
+ l.at(`Kontostand am ${deDate(st.period.from)} (Beginn)`, M + COLS[0].width, 8, bold);
154
+ l.right(qty(s.opening), M + 451 - 4, 8, bold);
155
+ l.y -= 13;
156
+ for (const r of s.rows) {
157
+ const detail = [
158
+ r.counterparty && `${r.debit ? 'an' : 'von'} ${r.counterparty}`,
159
+ r.hash && `${r.hashLabel} ${r.hash.slice(0, 10)}…${r.hash.slice(-6)}`,
160
+ r.beleg && `Eigenbeleg ${r.beleg}`
161
+ ]
162
+ .filter(Boolean)
163
+ .join(' · ');
164
+ const lines = wrapText(r.text, regular, 8, COLS[1].width - 6);
165
+ const sub = wrapText(detail, regular, 6.5, COLS[1].width - 6);
166
+ const h = lines.length * 10 + sub.length * 8.5 + 4;
167
+ if (l.ensure(h)) head();
168
+ const y = l.y;
169
+ regular.draw(l.page, deDate(r.date), { x: M, y: y - 8, size: 8 });
170
+ regular.draw(l.page, r.time, { x: M, y: y - 16.5, size: 6.5, color: GREY });
171
+ lines.forEach((t, i) =>
172
+ regular.draw(l.page, t, { x: M + COLS[0].width, y: y - 8 - i * 10, size: 8 })
173
+ );
174
+ sub.forEach((t, i) =>
175
+ regular.draw(l.page, t, {
176
+ x: M + COLS[0].width,
177
+ y: y - 8 - lines.length * 10 - i * 8.5 + 1.5,
178
+ size: 6.5,
179
+ color: GREY
180
+ })
181
+ );
182
+ let x = M + COLS[0].width + COLS[1].width;
183
+ l.right(qty(r.debit), x + COLS[2].width - 4, 8, regular);
184
+ x += COLS[2].width;
185
+ l.right(qty(r.credit), x + COLS[3].width - 4, 8, regular);
186
+ x += COLS[3].width;
187
+ l.right(qty(r.balance), x + COLS[4].width - 4, 8, regular);
188
+ x += COLS[4].width;
189
+ l.right(
190
+ r.eur ? deEuro(r.eur, 4).replace(' €', '') : '—',
191
+ x + COLS[5].width - 4,
192
+ 8,
193
+ regular,
194
+ r.eur ? BLACK : GREY
195
+ );
196
+ l.y -= h;
197
+ line(l.y + 1, { thickness: 0.25, color: RULE });
198
+ }
199
+ if (s.rows.length === 0) {
200
+ l.at('Keine Buchungen in diesem Zeitraum.', M + COLS[0].width, 8, regular, GREY);
201
+ l.y -= 13;
202
+ }
203
+ // sums and closing balance
204
+ l.ensure(60);
205
+ line(l.y);
206
+ l.y -= 3;
207
+ l.at('Summe', M + COLS[0].width, 8, bold);
208
+ l.right(qty(s.debit), M + 299 - 4, 8, bold);
209
+ l.right(qty(s.credit), M + 371 - 4, 8, bold);
210
+ l.y -= 13;
211
+ l.at(`Kontostand am ${deDate(st.period.to)} (Ende)`, M + COLS[0].width, 9, bold);
212
+ l.right(`${qty(s.closing)} ${s.asset}`, M + 451 - 4, 9, bold);
213
+ l.y -= 15;
214
+ // the check
215
+ if (st.method === 'archive' && s.reported !== null) {
216
+ const ok = reconciled(s.difference) === true;
217
+ const difference = /** @type {string} */ (s.difference);
218
+ const when = st.at
219
+ ? ` (Block ${st.at.closing.height}, ${st.at.closing.time.slice(0, 19).replace('T', ' ')} UTC)`
220
+ : '';
221
+ text(
222
+ ok && isDust(difference)
223
+ ? `Abgestimmt: Der Kontostand laut Chain nach dem Zeitraum${when} ist ${qty(s.reported)} ${s.asset}; die Differenz von ${deNumber(difference)} ${s.asset} liegt unter der dargestellten Genauigkeit (das 1 yoctoNEAR, das ein Token-Transfer als Sicherheit mitgibt, zählt nicht als Zahlung).`
224
+ : ok
225
+ ? `Abgestimmt: Der Kontostand laut Chain nach dem Zeitraum${when} ist ${qty(s.reported)} ${s.asset} und stimmt mit Anfangsstand plus Buchungen überein.`
226
+ : `Nicht abgestimmt: Der Kontostand laut Chain${when} ist ${qty(s.reported)} ${s.asset}; Differenz ${deNumber(difference)} ${s.asset} (Bewegungen, die der Leser nicht sieht, etwa Auszahlungen eines Staking-Pools).`,
227
+ { size: 7.5, color: ok ? OK : WARN }
228
+ );
229
+ } else {
230
+ text(
231
+ `Anfangs- und Endstand abgeleitet aus dem heutigen Kontostand abzüglich aller Bewegungen seither (${aleph ? 'die Aleph-API nennt den heutigen Stand und die Summen seither' : 'die Chain hält keine alten Kontostände vor'}).`,
232
+ { size: 7.5, color: GREY }
233
+ );
234
+ }
235
+ l.y -= 4;
236
+ text(
237
+ aleph
238
+ ? `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.`
239
+ : `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).`,
240
+ { size: 7.5, color: GREY }
241
+ );
242
+ l.y -= 12;
243
+ }
244
+ if (st.unlisted)
245
+ text(
246
+ `${st.unlisted} Bewegung(en) in Token ohne verlässlichen Kurs (oft Spam) sind nur in der CSV-Datei aufgeführt.`,
247
+ { size: 7.5, color: GREY }
248
+ );
249
+
250
+ // page numbers and footer on every page
251
+ const data = `Daten: ${DATA_SOURCES[st.chain] ?? st.chainName} · kein Dokument eines Kreditinstituts`;
252
+ l.pages.forEach((p, i) => {
253
+ regular.draw(p, `${st.number} · Seite ${i + 1} von ${l.pages.length}`, {
254
+ x: M,
255
+ y: M / 2,
256
+ size: 7,
257
+ color: GREY
258
+ });
259
+ regular.draw(p, data, {
260
+ x: A4[0] - M - regular.width(data, 7),
261
+ y: M / 2,
262
+ size: 7,
263
+ color: GREY
264
+ });
265
+ });
266
+
267
+ return savePdfA(pdf, {
268
+ title,
269
+ author: st.holder.name,
270
+ subject,
271
+ creator,
272
+ producer,
273
+ created,
274
+ seed: `${st.number}|${st.issuedAt}|${st.account}`
275
+ });
276
+ }
@@ -0,0 +1,232 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ //
3
+ // The Kontoauszug: every booking of one own blockchain account in a period,
4
+ // laid out the way a bank lays out an account statement – opening balance,
5
+ // each booking with debit (Soll) or credit (Haben) and the running balance,
6
+ // closing balance, sums. One section per asset the account holds.
7
+ //
8
+ // It is built from public chain data by the account holder. It is no
9
+ // document of a bank or of anyone else, and says so.
10
+ //
11
+ // The closing balance is checked: opening balance plus bookings must give
12
+ // the balance the chain reports after the period (NEAR, from the archival
13
+ // node). A difference is shown, not hidden. Where a chain keeps no old
14
+ // balances (Akash, Filecoin), the balances are derived from today's balance
15
+ // less the movements since, and the statement says that instead.
16
+ //
17
+ // A difference below what the documents print (twelve decimals) still
18
+ // counts as reconciled, and is still shown: the NEAR reader leaves out the
19
+ // 1 yoctoNEAR a token transfer attaches as its security deposit (no payment,
20
+ // 10⁻²⁴ NEAR), so an account that moved tokens is off by a few yocto.
21
+
22
+ import { normalize, sum } from '@le-space/ledger';
23
+ import { CHAIN_NAMES, kindText } from './document.js';
24
+
25
+ /** Smaller than the twelve decimals the documents print (and not zero). @param {string} difference */
26
+ export const isDust = (difference) => /^-?0\.0{12}\d*$/.test(difference);
27
+
28
+ /**
29
+ * Whether opening balance plus bookings meet the chain's balance: exactly,
30
+ * or but for dust (isDust). null: the chain names no balance.
31
+ *
32
+ * @param {string | null} difference
33
+ * @returns {boolean | null}
34
+ */
35
+ export const reconciled = (difference) =>
36
+ difference === null ? null : /^-?0(\.0+)?$/.test(difference) || isDust(difference);
37
+
38
+ /** Aleph Cloud credits: the same layout, as a monthly Verbrauchsauszug. */
39
+ export const USAGE_NOTE =
40
+ 'Verbrauchsauszug eines Aleph-Cloud-Kontos (Credits), erstellt vom Kontoinhaber aus der öffentlichen Aleph-API. ' +
41
+ 'Kein Dokument eines Kreditinstituts und keine Rechnung von Aleph. Verbrauch je Tag und Ressource; Euro-Wert: USD-Preis je Credit ' +
42
+ '(letzter Kauf am oder vor dem Tag, sonst Alephs Listenpreis von 1 USD je 1.000.000 Credits) zum EZB-Referenzkurs des Tages.';
43
+
44
+ export const STATEMENT_NOTE =
45
+ 'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
46
+ 'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
47
+
48
+ /**
49
+ * @typedef {object} StatementRow
50
+ * @property {string} date YYYY-MM-DD
51
+ * @property {string} time HH:MM:SS UTC
52
+ * @property {string} text what happened
53
+ * @property {string} counterparty
54
+ * @property {string} hash
55
+ * @property {string} explorerUrl
56
+ * @property {string} debit amount out, positive, or ''
57
+ * @property {string} credit amount in, positive, or ''
58
+ * @property {string} balance running balance after it
59
+ * @property {string} eur signed EUR value at the day's rate, or ''
60
+ * @property {string} beleg the Eigenbeleg's number, when the booking has one
61
+ * @property {boolean} fee
62
+ * @property {boolean} usage consumption billed from the balance (Aleph credits)
63
+ * @property {boolean} purchase credits bought from Aleph (the payment is on another chain, with its own Eigenbeleg)
64
+ * @property {string} label the counterparty's label alone (the resource's name, for usage)
65
+ * @property {string} hashLabel what the hash is: `Tx`, or `Ressource` for usage
66
+ */
67
+
68
+ /**
69
+ * @typedef {object} MonthlyLine one line of the month's summary
70
+ * @property {string} label
71
+ * @property {string} amount in the asset, positive
72
+ * @property {string} eur positive, '' when a row had no rate
73
+ * @property {number} rows how many bookings it sums
74
+ */
75
+
76
+ /**
77
+ * The month in sums, as the books take it (issue #24): consumption per resource and in all,
78
+ * credits bought, transfers in and out, fees. One booking each instead of the day's rows below.
79
+ *
80
+ * @param {StatementRow[]} rows
81
+ */
82
+ export function monthly(rows) {
83
+ /** @param {StatementRow[]} rs @param {string} label @param {'debit' | 'credit'} side @returns {MonthlyLine} */
84
+ const line = (rs, label, side) => ({
85
+ label,
86
+ amount: sum(rs.map((r) => r[side] || '0')),
87
+ eur: rs.some((r) => !r.eur) ? '' : sum(rs.map((r) => r.eur.replace(/^-/, ''))),
88
+ rows: rs.length
89
+ });
90
+ /** Usage rows by resource, in the order they first appear. */
91
+ const byResource = [...new Set(rows.filter((r) => r.usage).map((r) => r.label))].map((label) =>
92
+ line(
93
+ rows.filter((r) => r.usage && r.label === label),
94
+ `Verbrauch ${label.replace(/^Aleph Cloud \((.*)\)$/, '$1').replace(/^storage$/, 'Speicher (storage)')}`,
95
+ 'debit'
96
+ )
97
+ );
98
+ const usage = rows.filter((r) => r.usage);
99
+ const purchases = rows.filter((r) => r.purchase);
100
+ const transfersIn = rows.filter((r) => r.credit && !r.purchase);
101
+ const transfersOut = rows.filter((r) => r.debit && !r.usage && !r.fee);
102
+ const fees = rows.filter((r) => r.fee);
103
+ return {
104
+ usage: byResource,
105
+ usageTotal: usage.length ? line(usage, 'Verbrauch gesamt (Aufwand)', 'debit') : null,
106
+ purchases: purchases.length
107
+ ? line(purchases, 'Käufe von Guthaben (Vorauszahlung; Eigenbeleg je Kauf)', 'credit')
108
+ : null,
109
+ transfersIn: transfersIn.length
110
+ ? line(transfersIn, 'Eingänge von anderen Konten', 'credit')
111
+ : null,
112
+ transfersOut: transfersOut.length
113
+ ? line(transfersOut, 'Ausgänge an andere Konten', 'debit')
114
+ : null,
115
+ fees: fees.length ? line(fees, 'Netzwerkgebühren (Aufwand)', 'debit') : null
116
+ };
117
+ }
118
+
119
+ /**
120
+ * @param {object} p
121
+ * @param {{ name: string, address: string }} p.payer the account holder
122
+ * @param {string} p.account the own address
123
+ * @param {string} p.chain
124
+ * @param {string} p.network
125
+ * @param {{ from: string, to: string }} p.period
126
+ * @param {import('./value.js').ValuedEntry[]} p.entries this account's entries in the period
127
+ * @param {Record<string, string>} p.opening asset → balance before the period
128
+ * @param {Record<string, string>} p.closing asset → balance after it, as the chain or the derivation says
129
+ * @param {'archive' | 'derived'} p.method
130
+ * @param {{ opening: { height: number, time: string }, closing: { height: number, time: string } } | null} [p.at]
131
+ * @param {Map<string, string>} [p.belege] hash → Eigenbeleg number
132
+ * @param {string} [p.number]
133
+ * @param {string} [p.issuedAt]
134
+ */
135
+ export function buildStatement({
136
+ payer,
137
+ account,
138
+ chain,
139
+ network,
140
+ period,
141
+ entries,
142
+ opening,
143
+ closing,
144
+ method,
145
+ at = null,
146
+ belege = new Map(),
147
+ number,
148
+ issuedAt
149
+ }) {
150
+ // An Aleph credit purchase (kind `swap`) is the payment on another chain; the
151
+ // credits it bought are the incoming row. Only that row belongs on the statement.
152
+ const mine = entries.filter(
153
+ (e) => e.account === account && !(e.chain === 'aleph' && e.kind === 'swap')
154
+ );
155
+ const own = mine.filter((e) => e.success !== false);
156
+ const assets = [
157
+ ...new Set([...Object.keys(opening), ...own.filter((e) => e.priceAs).map((e) => e.asset)])
158
+ ];
159
+ const sections = assets.map((asset) => {
160
+ let balance = normalize(opening[asset] ?? '0');
161
+ /** @type {StatementRow[]} */
162
+ const rows = [];
163
+ for (const e of own.filter((x) => x.asset === asset)) {
164
+ balance = sum([balance, e.amount]);
165
+ const out = e.amount.startsWith('-');
166
+ rows.push({
167
+ date: e.date,
168
+ time: e.time.slice(11, 19),
169
+ text: `${kindText(e)}${e.type === 'received' ? ' (Eingang)' : ''}`,
170
+ counterparty: e.counterpartyLabel
171
+ ? `${e.counterpartyLabel} · ${e.counterparty}`
172
+ : e.counterparty,
173
+ hash: e.hash,
174
+ explorerUrl: e.explorerUrl,
175
+ debit: out ? e.amount.slice(1) : '',
176
+ credit: out ? '' : e.amount,
177
+ balance,
178
+ eur: e.eur?.value ?? '',
179
+ beleg: belege.get(e.hash) ?? '',
180
+ fee: e.type === 'fee',
181
+ usage: e.kind === 'usage',
182
+ purchase: e.type === 'received' && e.counterparty === 'aleph',
183
+ label: e.counterpartyLabel,
184
+ hashLabel: e.kind === 'usage' ? 'Ressource' : 'Tx'
185
+ });
186
+ }
187
+ const debit = sum(rows.map((r) => r.debit || '0'));
188
+ const credit = sum(rows.map((r) => r.credit || '0'));
189
+ const reported = closing[asset];
190
+ return {
191
+ asset,
192
+ opening: normalize(opening[asset] ?? '0'),
193
+ closing: balance,
194
+ reported: reported === undefined ? null : normalize(reported),
195
+ difference:
196
+ reported === undefined
197
+ ? null
198
+ : sum([reported, balance.startsWith('-') ? balance.slice(1) : `-${balance}`]),
199
+ debit,
200
+ credit,
201
+ rows,
202
+ monthly: monthly(rows),
203
+ eurOut: sum(rows.filter((r) => r.debit && r.eur).map((r) => r.eur.replace(/^-/, ''))),
204
+ eurIn: sum(rows.filter((r) => r.credit && r.eur).map((r) => r.eur)),
205
+ eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
206
+ eurUsage: sum(rows.filter((r) => r.usage && r.eur).map((r) => r.eur.replace(/^-/, ''))),
207
+ unvalued: rows.filter((r) => !r.eur).length
208
+ };
209
+ });
210
+ // Aleph credits: a monthly usage statement, laid out as the Kontoauszug.
211
+ const usage = chain === 'aleph';
212
+ return {
213
+ kind: 'kontoauszug',
214
+ title: usage ? 'Verbrauchsauszug' : 'Kontoauszug',
215
+ number: number || `KA-${period.from}`,
216
+ issuedAt: issuedAt ?? new Date().toISOString(),
217
+ holder: { name: payer.name.trim(), address: payer.address.trim() },
218
+ account,
219
+ chain,
220
+ chainName: CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
221
+ network,
222
+ testnet: network !== 'mainnet',
223
+ period,
224
+ method,
225
+ at,
226
+ sections,
227
+ unlisted: mine.filter((e) => !e.priceAs && !assets.includes(e.asset)).length,
228
+ note: usage ? USAGE_NOTE : STATEMENT_NOTE
229
+ };
230
+ }
231
+
232
+ /** @typedef {ReturnType<typeof buildStatement>} Statement */
package/src/value.js ADDED
@@ -0,0 +1,74 @@
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
3
+ // comes from is the caller's (the pipeline asks @le-space/rates); this file
4
+ // only applies it, and names a fixed rate for tests and offline demos.
5
+ //
6
+ // Aleph Cloud credits have no rate of the day: they are valued at the USD
7
+ // price per credit the reader hands with each entry (`unitPrice`: the last
8
+ // purchase on or before the day, else Aleph's list price) at that day's ECB
9
+ // rate for USD (@le-space/rates/aleph-credits).
10
+
11
+ import { multiply } from '@le-space/ledger';
12
+
13
+ /**
14
+ * @typedef {object} Rate
15
+ * @property {string} rate EUR per unit, decimal string
16
+ * @property {string} source human-readable: where and which moment, printed on the document
17
+ * @property {string} date YYYY-MM-DD the rate is for
18
+ */
19
+
20
+ /** @typedef {{ rateFor: (asset: string, date: string) => Promise<Rate | null> }} Rates */
21
+
22
+ /**
23
+ * @typedef {import('@le-space/ledger').LedgerEntry & { eur: { value: string, rate: string, source: string } | null }} ValuedEntry
24
+ */
25
+
26
+ /**
27
+ * Every entry with its euro value (8 decimals; printed with 4, the total rounded to cents
28
+ * where it is printed). An entry without a price gets `eur: null`. One with a
29
+ * `unitPrice` in USD (Aleph credits) is valued at that price and the day's rate for USD.
30
+ *
31
+ * @param {import('@le-space/ledger').LedgerEntry[]} entries
32
+ * @param {Rates} rates
33
+ * @returns {Promise<ValuedEntry[]>}
34
+ */
35
+ export async function valueEntries(entries, rates) {
36
+ const out = [];
37
+ for (const e of entries) {
38
+ const unit =
39
+ /** @type {{ currency?: string, amount?: string, source?: string } | undefined} */ (
40
+ /** @type {any} */ (e).unitPrice
41
+ );
42
+ if (!e.priceAs && e.success && unit?.currency === 'USD' && unit.amount) {
43
+ const usd = await rates.rateFor('USD', e.date);
44
+ const how = unit.source === 'purchase' ? 'Kaufpreis' : 'Listenpreis';
45
+ out.push({
46
+ ...e,
47
+ eur: usd
48
+ ? {
49
+ value: multiply(multiply(e.amount, unit.amount, 12), usd.rate, 8),
50
+ rate: multiply(unit.amount, usd.rate, 14),
51
+ source: `Aleph ${how} ${unit.amount} USD je Credit × ${usd.source}`
52
+ }
53
+ : null
54
+ });
55
+ continue;
56
+ }
57
+ const r = e.priceAs && e.success ? await rates.rateFor(e.priceAs, e.date) : null;
58
+ out.push({
59
+ ...e,
60
+ eur: r ? { value: multiply(e.amount, r.rate, 8), rate: r.rate, source: r.source } : null
61
+ });
62
+ }
63
+ return out;
64
+ }
65
+
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) {
68
+ return {
69
+ async rateFor(asset, date) {
70
+ const rate = table[`${asset}:${date}`] ?? table[asset];
71
+ return rate ? { rate, source: `fester Testkurs (${asset})`, date } : null;
72
+ }
73
+ };
74
+ }