@le-space/eigenbeleg 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,8 +4,8 @@ The Eigenbeleg and the Kontoauszug of Le Space's tools – [Belege](https://gith
4
4
 
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
- - **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)`.
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.
9
9
  - **The Eigenbeleg of one booking** (Belege's, `@le-space/eigenbeleg/booking`, `/booking-pdf`): `bookingPdf(doc)` for a `BookingEigenbeleg` – a bank booking or a crypto payment, with an own wallet's transaction in full (whole hash, both addresses, every movement with the gas, the explorer link as a QR code). The booking's context is the caller's to gather. `nextSelfNumber(receipts, year)` – the range EB-YYYY-NNN.
10
10
  - **A statement Eigenbeleg** (Belege's Aleph, Akash and travel statements, `@le-space/eigenbeleg/statement-layout`): `statementLayout({ title, created, continuation })` → `head`, `field`, `rule`, `heading`, `table` (the header repeats on a new page), `signature`, `save`.
11
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/eigenbeleg",
3
- "version": "0.1.0",
3
+ "version": "0.2.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",
@@ -35,14 +35,14 @@
35
35
  "pdf-lib": "1.17.1",
36
36
  "uqr": "0.1.3",
37
37
  "@le-space/ledger": "^0.3.0",
38
- "@le-space/pdf": "^0.1.0"
38
+ "@le-space/pdf": "^0.1.1"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@noble/hashes": "2.4.0",
42
42
  "prettier": "3.6.2",
43
43
  "unpdf": "1.8.1",
44
- "@le-space/chains": "^0.3.0",
45
- "@le-space/browser-test": "0.1.0"
44
+ "@le-space/browser-test": "0.1.0",
45
+ "@le-space/chains": "^0.5.0"
46
46
  },
47
47
  "scripts": {
48
48
  "test": "node --test --test-reporter=spec \"test/*.test.js\"",
package/src/csv.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // where anyone can write anything.
9
9
 
10
10
  import { round } from '@le-space/ledger';
11
- import { KIND_TEXT } from './document.js';
11
+ import { kindText } from './document.js';
12
12
 
13
13
  const HEADER = [
14
14
  'Belegnummer',
@@ -63,7 +63,7 @@ export function eigenbelegCsv(doc) {
63
63
  e.chain,
64
64
  e.network,
65
65
  e.account,
66
- KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
66
+ kindText(e),
67
67
  DIRECTION[e.type],
68
68
  e.counterpartyLabel ? `${e.counterpartyLabel} (${e.counterparty})` : e.counterparty,
69
69
  e.asset,
package/src/document.js CHANGED
@@ -10,7 +10,9 @@
10
10
  // storage deposit to a protocol contract is the same. A transfer to another
11
11
  // account may well be to a company that does invoice; it goes on the
12
12
  // Eigenbeleg only when the payer says so (`includeKinds`), and is always in
13
- // the CSV.
13
+ // the CSV. Buying Aleph Cloud credits with a token is a payment of its own
14
+ // (kind `swap` on chain `aleph`, issue #23): its Eigenbeleg says *Kauf von
15
+ // Guthaben*; the credits it brought appear on it as the incoming movement.
14
16
  //
15
17
  // Two layouts, the same content:
16
18
  // collective one Eigenbeleg for the period (Sammel-Eigenbeleg), one
@@ -30,6 +32,31 @@ export const NOTE =
30
32
  'Eigenbeleg. Für diese Zahlung gibt es keinen Fremdbeleg: Empfänger ist ein Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation. ' +
31
33
  'Ausgestellt vom Zahlenden auf Grundlage der öffentlichen Transaktion; jede Position ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
32
34
 
35
+ /** Aleph Cloud is an organisation, but the purchase of credits is a token payment on chain that gets no invoice (#23). */
36
+ export const ALEPH_NOTE =
37
+ 'Eigenbeleg. Für diese Zahlung gibt es keinen Fremdbeleg: Aleph-Cloud-Guthaben (Credits) wird per Token-Zahlung an das Aleph-Netzwerk gekauft; Aleph stellt dafür keine Rechnung aus. ' +
38
+ 'Ausgestellt vom Zahlenden auf Grundlage der öffentlichen Transaktion; jede Position ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
39
+
40
+ /**
41
+ * Why there is no invoice for a payment on this chain: the recipient line and the reason, as the Eigenbeleg prints them.
42
+ *
43
+ * @param {string} chain
44
+ * @param {string} chainName
45
+ */
46
+ export function noInvoice(chain, chainName) {
47
+ if (chain === 'aleph')
48
+ return {
49
+ recipient: `${chainName}: Kauf von Guthaben per Token-Zahlung an das Netzwerk, ohne Rechnung`,
50
+ why: 'Aleph-Cloud-Guthaben (Credits) wird per Token-Zahlung an das Aleph-Netzwerk gekauft; Aleph stellt dafür keine Rechnung aus.',
51
+ note: ALEPH_NOTE
52
+ };
53
+ return {
54
+ recipient: `${chainName}: Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation`,
55
+ why: 'Der Empfänger ist ein Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation; es stellt keine Rechnung aus.',
56
+ note: NOTE
57
+ };
58
+ }
59
+
33
60
  export const NOT_AN_INVOICE =
34
61
  'Dies ist keine Rechnung und kein Beleg eines Dritten. Le Space stellt keine Rechnungen für andere aus.';
35
62
 
@@ -49,19 +76,41 @@ export const KIND_TEXT = {
49
76
  usage: 'Verbrauch (aus Guthaben abgerechnet)'
50
77
  };
51
78
 
79
+ /**
80
+ * What an entry's kind is called on the documents. An Aleph credit purchase is a swap
81
+ * of a token for credits in the ledger; for the books it is the purchase of a balance.
82
+ *
83
+ * @param {{ chain: string, kind: string }} e
84
+ */
85
+ export const kindText = (e) =>
86
+ e.chain === 'aleph' && e.kind === 'swap'
87
+ ? 'Kauf von Guthaben (Credits)'
88
+ : (KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind);
89
+
90
+ /** The chains Eigenbeleg makes documents for, by id (as @le-space/chains names them). */
52
91
  export const CHAIN_NAMES = {
53
92
  near: 'NEAR Protocol',
54
93
  akash: 'Akash',
55
94
  filecoin: 'Filecoin',
56
- aleph: 'Aleph Cloud (Credits)'
95
+ aleph: 'Aleph Cloud (Credits)',
96
+ 'filecoin-pay': 'Filecoin Pay',
97
+ ethereum: 'Ethereum',
98
+ base: 'Base'
57
99
  };
58
100
 
59
- /** Where a chain's data comes from, named in the footer of its documents. */
101
+ /**
102
+ * Where a chain's data comes from, named in the footer of its documents.
103
+ * Ethereum and Base: Eigenbeleg reads them through Alchemy (@le-space/chains'
104
+ * EVM reader, with the server's key).
105
+ */
60
106
  export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
61
107
  near: 'NearBlocks.io APIs, NEAR-Archiv-RPC',
62
108
  filecoin: 'Filfox',
63
109
  akash: 'Akash-RPC, Akash Console',
64
- aleph: 'Aleph-API (api2.aleph.im)'
110
+ aleph: 'Aleph-API (api2.aleph.im)',
111
+ 'filecoin-pay': 'Index von Filecoin Pay (Goldsky), Blockscout, Filfox',
112
+ ethereum: 'Alchemy APIs (Ethereum Mainnet)',
113
+ base: 'Alchemy APIs (Base Mainnet)'
65
114
  });
66
115
 
67
116
  /**
@@ -156,11 +205,12 @@ export function buildDocument({
156
205
  positions.push({
157
206
  pos: 0,
158
207
  entry: e,
159
- what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
208
+ what: kindText(e),
160
209
  recipient: e.counterpartyLabel || e.counterparty
161
210
  });
162
211
  }
163
212
  const first = number || `EB-${period.to.slice(0, 4)}-001`;
213
+ const chainName = CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain;
164
214
  /** @type {Transaction[]} */
165
215
  const transactions = [];
166
216
  for (const p of positions) {
@@ -181,7 +231,7 @@ export function buildDocument({
181
231
  const x = excluded.find((y) => y.entry === e);
182
232
  return {
183
233
  entry: e,
184
- what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
234
+ what: kindText(e),
185
235
  onIt: !x,
186
236
  why: x?.why ?? ''
187
237
  };
@@ -222,7 +272,7 @@ export function buildDocument({
222
272
  addresses: [...payer.addresses]
223
273
  },
224
274
  chain,
225
- chainName: CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
275
+ chainName,
226
276
  network,
227
277
  testnet: network !== 'mainnet',
228
278
  period,
@@ -234,14 +284,17 @@ export function buildDocument({
234
284
  eur: round(eurExact.replace(/^-/, ''), 2),
235
285
  eurExact: eurExact.replace(/^-/, '')
236
286
  },
287
+ // The rate's name without its day (`… vom 2026-08-10`): the day is each position's.
237
288
  sources: [
238
289
  ...new Set(
239
290
  positions.map((p) =>
240
- /** @type {any} */ (p.entry.eur).source.replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
291
+ /** @type {any} */ (p.entry.eur).source
292
+ .replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
293
+ .replace(/ vom$/, '')
241
294
  )
242
295
  )
243
296
  ],
244
- note: NOTE,
297
+ note: noInvoice(chain, chainName).note,
245
298
  notInvoice: NOT_AN_INVOICE
246
299
  };
247
300
  }
package/src/index.js CHANGED
@@ -9,6 +9,9 @@ export {
9
9
  NOT_AN_INVOICE,
10
10
  DEFAULT_KINDS,
11
11
  KIND_TEXT,
12
+ kindText,
13
+ ALEPH_NOTE,
14
+ noInvoice,
12
15
  CHAIN_NAMES,
13
16
  DATA_SOURCES,
14
17
  deNumber,
@@ -17,7 +20,17 @@ export {
17
20
  } from './document.js';
18
21
  export { eigenbelegCsv } from './csv.js';
19
22
  export { eigenbelegPdf, CREATOR, PRODUCER } from './pdf.js';
20
- export { buildStatement, STATEMENT_NOTE, USAGE_NOTE } from './statement.js';
23
+ export {
24
+ buildStatement,
25
+ isDust,
26
+ monthly,
27
+ reconciled,
28
+ STATEMENT_NOTE,
29
+ USAGE_NOTE,
30
+ USAGE_NOTES,
31
+ FILECOIN_PAY_USAGE_NOTE
32
+ } from './statement.js';
33
+ /** @typedef {import('./statement.js').MonthlyLine} MonthlyLine */
21
34
  export { statementPdf } from './statement-pdf.js';
22
35
  export { valueEntries, fixedRates } from './value.js';
23
36
  export { nextSelfNumber, bookingNote, bookingNotInvoice } from './booking.js';
package/src/layout.js CHANGED
@@ -110,6 +110,26 @@ export function pageLayout(pdf, fonts, { margin = 48, bottom = 14, leavePage, en
110
110
  face.draw(l.page, pdfText(t), { x, y: l.y - size, size, color });
111
111
  },
112
112
 
113
+ /**
114
+ * A one-line title and, when given, an image beside it, a little higher
115
+ * than the letters: the chain's mark (`logo`).
116
+ *
117
+ * @param {string} t
118
+ * @param {{ face: Face, size: number }} o
119
+ * @param {import('pdf-lib').PDFImage | null} [image]
120
+ */
121
+ title(t, { face, size }, image = null) {
122
+ l.text(t, { face, size });
123
+ if (!image) return;
124
+ const top = l.y + size * 1.35;
125
+ l.page.drawImage(image, {
126
+ x: margin + face.width(t, size) + 10,
127
+ y: top - size - 2,
128
+ width: size + 2,
129
+ height: size + 2
130
+ });
131
+ },
132
+
113
133
  /** @param {number} [thickness] @param {Color} [color] */
114
134
  rule(thickness = 0.6, color = RULE) {
115
135
  l.page.drawLine({
package/src/pdf.js CHANGED
@@ -6,10 +6,10 @@
6
6
  //
7
7
  // The text is German: the document is for German bookkeeping.
8
8
 
9
- import { createPdfA, savePdfA } from '@le-space/pdf';
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 } from './document.js';
12
+ import { DATA_SOURCES, deDate, deEuro, deNumber, noInvoice } from './document.js';
13
13
  import { A4, BLACK, GREY, WARN, pageLayout } from './layout.js';
14
14
 
15
15
  /** What made the file, unless the caller says otherwise. */
@@ -18,15 +18,23 @@ export const PRODUCER = 'eigenbeleg (Le Space UG), pdf-lib';
18
18
 
19
19
  /**
20
20
  * @param {import('./document.js').EigenbelegDocument} doc
21
- * @param {{ creator?: string, producer?: string }} [o]
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)
22
23
  * @returns {Promise<Uint8Array>}
23
24
  */
24
- export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCER } = {}) {
25
+ export async function eigenbelegPdf(
26
+ doc,
27
+ { creator = CREATOR, producer = PRODUCER, logo = false } = {}
28
+ ) {
25
29
  const created = new Date(doc.issuedAt);
26
30
  const title = `Eigenbeleg ${doc.number}`;
27
31
  const subject = `${doc.layout === 'single' ? 'Eigenbelege' : 'Sammel-Eigenbeleg'} ${doc.chainName}, ${deDate(doc.period.from)} – ${deDate(doc.period.to)}`;
28
32
  const { pdf, fonts } = await createPdfA();
29
33
  const { regular, bold, mono } = fonts;
34
+ const mark =
35
+ logo && Object.hasOwn(LOGOS, doc.chain)
36
+ ? await pdf.embedPng(await asset(LOGOS[doc.chain]))
37
+ : null;
30
38
  const M = 48;
31
39
  let pageNo = 1;
32
40
  let current = doc.number;
@@ -49,7 +57,7 @@ export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCE
49
57
  pageNo++;
50
58
  }
51
59
  });
52
- const { text, gap, field } = l;
60
+ const { text, gap, field, title: heading } = l;
53
61
  const width = l.width;
54
62
 
55
63
  /** @param {string} number @param {string} subtitle */
@@ -62,7 +70,7 @@ export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCE
62
70
  );
63
71
  gap(4);
64
72
  }
65
- text('Eigenbeleg', { face: bold, size: 20 });
73
+ heading('Eigenbeleg', { face: bold, size: 20 }, mark);
66
74
  text(`Nr. ${number}`, { face: bold, size: 12 });
67
75
  gap(2);
68
76
  text(subtitle, { size: 10 });
@@ -79,7 +87,7 @@ export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCE
79
87
  text(`${deDate(doc.issuedAt)}, ${doc.issuedAt.slice(11, 16)} UTC`, { x: rx });
80
88
  gap(3);
81
89
  text('Empfänger', { x: rx, face: bold, size: 8.5, color: GREY });
82
- text(`${doc.chainName}: Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation`, { x: rx });
90
+ text(noInvoice(doc.chain, doc.chainName).recipient, { x: rx });
83
91
  l.y = Math.min(l.y, leftEnd);
84
92
  gap(8);
85
93
  text(doc.payer.addresses.length > 1 ? 'Eigene Zahlungsadressen' : 'Eigene Zahlungsadresse', {
@@ -190,7 +198,11 @@ export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCE
190
198
  ts.flatMap((t) =>
191
199
  t.movements
192
200
  .filter((m) => m.onIt)
193
- .map((m) => /** @type {any} */ (m.entry.eur).source.replace(/ \d{4}-\d{2}-\d{2}.*$/, ''))
201
+ .map((m) =>
202
+ /** @type {any} */ (m.entry.eur).source
203
+ .replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
204
+ .replace(/ vom$/, '')
205
+ )
194
206
  )
195
207
  )
196
208
  ];
@@ -224,10 +236,7 @@ export async function eigenbelegPdf(doc, { creator = CREATOR, producer = PRODUCE
224
236
  text(`Ungerundet ${deEuro(t.eurExact, 8)} (unter einem Cent).`, { size: 8, color: GREY });
225
237
  gap(4);
226
238
  field('Was wurde bezahlt', `${what} an ${t.to.label || t.to.address}`);
227
- field(
228
- 'Warum kein Fremdbeleg',
229
- 'Der Empfänger ist ein Peer-to-Peer-Netzwerk ohne rechnungsstellende Organisation; es stellt keine Rechnung aus.'
230
- );
239
+ field('Warum kein Fremdbeleg', noInvoice(doc.chain, doc.chainName).why);
231
240
  sourcesAndSignature([], sourcesOf([t]));
232
241
  });
233
242
  } else {
@@ -8,11 +8,12 @@
8
8
  // the same layout titled »Verbrauchsauszug« (`st.title`).
9
9
 
10
10
  import { rgb } from 'pdf-lib';
11
- import { createPdfA, savePdfA, wrapText } from '@le-space/pdf';
11
+ import { asset, createPdfA, LOGOS, savePdfA, wrapText } from '@le-space/pdf';
12
12
  import { round } from '@le-space/ledger';
13
13
 
14
14
  import { DATA_SOURCES, deDate, deEuro, deNumber } from './document.js';
15
15
  import { CREATOR, PRODUCER } from './pdf.js';
16
+ import { isDust, reconciled } from './statement.js';
16
17
  import { A4, BAND, BLACK, GREY, OK, RULE, WARN, pageLayout } from './layout.js';
17
18
 
18
19
  const M = 44;
@@ -32,17 +33,27 @@ const qty = (q) => (q ? deNumber(round(q, 12)) : '');
32
33
 
33
34
  /**
34
35
  * @param {import('./statement.js').Statement} st
35
- * @param {{ creator?: string, producer?: string }} [o]
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)
36
38
  * @returns {Promise<Uint8Array>}
37
39
  */
38
- export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER } = {}) {
40
+ export async function statementPdf(
41
+ st,
42
+ { creator = CREATOR, producer = PRODUCER, logo = false } = {}
43
+ ) {
39
44
  const created = new Date(st.issuedAt);
40
45
  // Aleph credits: a Verbrauchsauszug in the same layout, valued by its own rule.
41
46
  const aleph = st.chain === 'aleph';
47
+ // Filecoin Pay: the same, in USDFC and by rail.
48
+ const pay = st.chain === 'filecoin-pay';
42
49
  const title = `${st.title} ${st.number}`;
43
50
  const subject = `${st.title} ${st.chainName} ${st.account}, ${deDate(st.period.from)} – ${deDate(st.period.to)}`;
44
51
  const { pdf, fonts } = await createPdfA();
45
52
  const { regular, bold, mono } = fonts;
53
+ const mark =
54
+ logo && Object.hasOwn(LOGOS, st.chain)
55
+ ? await pdf.embedPng(await asset(LOGOS[st.chain]))
56
+ : null;
46
57
  const l = pageLayout(pdf, fonts, {
47
58
  margin: M,
48
59
  bottom: 16,
@@ -86,7 +97,7 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
86
97
  l.y -= 12;
87
98
  }
88
99
  l.y = Math.min(l.y, leftEnd) - 14;
89
- text(st.title, { face: bold, size: 18 });
100
+ l.title(st.title, { face: bold, size: 18 }, mark);
90
101
  text('Konto', { face: bold, size: 7.5, color: GREY });
91
102
  text(st.account, { face: mono, size: 9 });
92
103
  l.y -= 6;
@@ -99,6 +110,35 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
99
110
  l.page.drawRectangle({ x: M, y: l.y - 18, width, height: 18, color: BAND });
100
111
  bold.draw(l.page, `${s.asset} · ${st.account}`, { x: M + 6, y: l.y - 12.5, size: 9.5 });
101
112
  l.y -= 24;
113
+ // The month in sums, first (#24): what the books take as one booking each; the rows below are the proof.
114
+ if (aleph || pay) {
115
+ const m = s.monthly;
116
+ const lines = [m.usage, m.usageTotal, m.purchases, m.transfersIn, m.transfersOut]
117
+ .flat()
118
+ .filter((x) => x !== null);
119
+ if (lines.length) {
120
+ l.ensure(14 + lines.length * 11 + 8);
121
+ l.at('Monatsübersicht', M, 8, bold, GREY);
122
+ 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);
124
+ l.y -= 12;
125
+ for (const ml of lines) {
126
+ const total = ml === m.usageTotal;
127
+ const f = total ? bold : regular;
128
+ l.at(ml.label, M + (total ? 0 : 8), 8, f);
129
+ 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
+ );
137
+ l.y -= 11;
138
+ }
139
+ l.y -= 8;
140
+ }
141
+ }
102
142
  const head = () => {
103
143
  let x = M;
104
144
  for (const c of COLS) {
@@ -175,27 +215,32 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
175
215
  l.y -= 15;
176
216
  // the check
177
217
  if (st.method === 'archive' && s.reported !== null) {
178
- const ok = s.difference !== null && /^-?0(\.0+)?$/.test(s.difference);
218
+ const ok = reconciled(s.difference) === true;
219
+ const difference = /** @type {string} */ (s.difference);
179
220
  const when = st.at
180
221
  ? ` (Block ${st.at.closing.height}, ${st.at.closing.time.slice(0, 19).replace('T', ' ')} UTC)`
181
222
  : '';
182
223
  text(
183
- ok
184
- ? `Abgestimmt: Der Kontostand laut Chain nach dem Zeitraum${when} ist ${qty(s.reported)} ${s.asset} und stimmt mit Anfangsstand plus Buchungen überein.`
185
- : `Nicht abgestimmt: Der Kontostand laut Chain${when} ist ${qty(s.reported)} ${s.asset}; Differenz ${deNumber(/** @type {string} */ (s.difference))} ${s.asset} (Bewegungen, die der Leser nicht sieht, etwa Auszahlungen eines Staking-Pools).`,
224
+ ok && isDust(difference)
225
+ ? `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).`
226
+ : ok
227
+ ? `Abgestimmt: Der Kontostand laut Chain nach dem Zeitraum${when} ist ${qty(s.reported)} ${s.asset} und stimmt mit Anfangsstand plus Buchungen überein.`
228
+ : `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).`,
186
229
  { size: 7.5, color: ok ? OK : WARN }
187
230
  );
188
231
  } else {
189
232
  text(
190
- `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'}).`,
233
+ `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' : pay ? 'der Zahlungsvertrag nennt nur den heutigen Stand' : 'die Chain hält keine alten Kontostände vor'}).`,
191
234
  { size: 7.5, color: GREY }
192
235
  );
193
236
  }
194
237
  l.y -= 4;
195
238
  text(
196
- aleph
197
- ? `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.`
198
- : `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).`,
239
+ 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).`
241
+ : 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).`,
199
244
  { size: 7.5, color: GREY }
200
245
  );
201
246
  l.y -= 12;
package/src/statement.js CHANGED
@@ -13,9 +13,27 @@
13
13
  // node). A difference is shown, not hidden. Where a chain keeps no old
14
14
  // balances (Akash, Filecoin), the balances are derived from today's balance
15
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.
16
21
 
17
22
  import { normalize, sum } from '@le-space/ledger';
18
- import { CHAIN_NAMES, KIND_TEXT } from './document.js';
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);
19
37
 
20
38
  /** Aleph Cloud credits: the same layout, as a monthly Verbrauchsauszug. */
21
39
  export const USAGE_NOTE =
@@ -23,6 +41,19 @@ export const USAGE_NOTE =
23
41
  'Kein Dokument eines Kreditinstituts und keine Rechnung von Aleph. Verbrauch je Tag und Ressource; Euro-Wert: USD-Preis je Credit ' +
24
42
  '(letzter Kauf am oder vor dem Tag, sonst Alephs Listenpreis von 1 USD je 1.000.000 Credits) zum EZB-Referenzkurs des Tages.';
25
43
 
44
+ /** Filecoin Pay: a payer's balance in the payment contract, as a monthly Verbrauchsauszug. */
45
+ export const FILECOIN_PAY_USAGE_NOTE =
46
+ 'Verbrauchsauszug eines Guthabens im Zahlungsvertrag Filecoin Pay (Filecoin Onchain Cloud), erstellt vom Zahler aus öffentlichen Chain-Daten. ' +
47
+ 'Kein Dokument eines Kreditinstituts und keine Rechnung eines Speicheranbieters. Verbrauch ist jede Abrechnung einer Rail an ihren Anbieter; ' +
48
+ 'sie bezahlt bis zu dem Zeitpunkt, den sie nennt, und deckt darum nicht genau den Monat. Gelesen wird nur USDFC; was der Zahler selbst über Rails einnimmt, fehlt. ' +
49
+ 'Euro-Wert: USDFC ist an den US-Dollar gebunden und wird zum Tageskurs von USDC bewertet.';
50
+
51
+ /** The chains whose statement is a Verbrauchsauszug (consumption from a prepaid balance), with its note. */
52
+ export const USAGE_NOTES = /** @type {Record<string, string>} */ ({
53
+ aleph: USAGE_NOTE,
54
+ 'filecoin-pay': FILECOIN_PAY_USAGE_NOTE
55
+ });
56
+
26
57
  export const STATEMENT_NOTE =
27
58
  'Kontoauszug eines Blockchain-Kontos, erstellt vom Kontoinhaber aus öffentlichen Chain-Daten. ' +
28
59
  'Kein Dokument eines Kreditinstituts. Jede Buchung ist über ihren Transaktions-Hash in einem öffentlichen Block-Explorer nachprüfbar.';
@@ -41,10 +72,63 @@ export const STATEMENT_NOTE =
41
72
  * @property {string} eur signed EUR value at the day's rate, or ''
42
73
  * @property {string} beleg the Eigenbeleg's number, when the booking has one
43
74
  * @property {boolean} fee
44
- * @property {boolean} usage consumption billed from the balance (Aleph credits)
45
- * @property {string} hashLabel what the hash is: `Tx`, or `Ressource` for usage
75
+ * @property {boolean} usage consumption billed from the balance (Aleph credits, a Filecoin Pay settlement)
76
+ * @property {boolean} purchase credits bought from Aleph (the payment is on another chain, with its own Eigenbeleg)
77
+ * @property {string} label the counterparty's label alone (the resource's name, for usage)
78
+ * @property {string} hashLabel what the hash is: `Tx`, or `Ressource` for Aleph's usage
46
79
  */
47
80
 
81
+ /**
82
+ * @typedef {object} MonthlyLine one line of the month's summary
83
+ * @property {string} label
84
+ * @property {string} amount in the asset, positive
85
+ * @property {string} eur positive, '' when a row had no rate
86
+ * @property {number} rows how many bookings it sums
87
+ */
88
+
89
+ /**
90
+ * The month in sums, as the books take it (issue #24): consumption per resource and in all,
91
+ * credits bought, transfers in and out, fees. One booking each instead of the day's rows below.
92
+ *
93
+ * @param {StatementRow[]} rows
94
+ */
95
+ export function monthly(rows) {
96
+ /** @param {StatementRow[]} rs @param {string} label @param {'debit' | 'credit'} side @returns {MonthlyLine} */
97
+ const line = (rs, label, side) => ({
98
+ label,
99
+ amount: sum(rs.map((r) => r[side] || '0')),
100
+ eur: rs.some((r) => !r.eur) ? '' : sum(rs.map((r) => r.eur.replace(/^-/, ''))),
101
+ rows: rs.length
102
+ });
103
+ /** Usage rows by resource, in the order they first appear. */
104
+ const byResource = [...new Set(rows.filter((r) => r.usage).map((r) => r.label))].map((label) =>
105
+ line(
106
+ rows.filter((r) => r.usage && r.label === label),
107
+ `Verbrauch ${label.replace(/^Aleph Cloud \((.*)\)$/, '$1').replace(/^storage$/, 'Speicher (storage)')}`,
108
+ 'debit'
109
+ )
110
+ );
111
+ const usage = rows.filter((r) => r.usage);
112
+ const purchases = rows.filter((r) => r.purchase);
113
+ const transfersIn = rows.filter((r) => r.credit && !r.purchase);
114
+ const transfersOut = rows.filter((r) => r.debit && !r.usage && !r.fee);
115
+ const fees = rows.filter((r) => r.fee);
116
+ return {
117
+ usage: byResource,
118
+ usageTotal: usage.length ? line(usage, 'Verbrauch gesamt (Aufwand)', 'debit') : null,
119
+ purchases: purchases.length
120
+ ? line(purchases, 'Käufe von Guthaben (Vorauszahlung; Eigenbeleg je Kauf)', 'credit')
121
+ : null,
122
+ transfersIn: transfersIn.length
123
+ ? line(transfersIn, 'Eingänge von anderen Konten', 'credit')
124
+ : null,
125
+ transfersOut: transfersOut.length
126
+ ? line(transfersOut, 'Ausgänge an andere Konten', 'debit')
127
+ : null,
128
+ fees: fees.length ? line(fees, 'Netzwerkgebühren (Aufwand)', 'debit') : null
129
+ };
130
+ }
131
+
48
132
  /**
49
133
  * @param {object} p
50
134
  * @param {{ name: string, address: string }} p.payer the account holder
@@ -76,7 +160,12 @@ export function buildStatement({
76
160
  number,
77
161
  issuedAt
78
162
  }) {
79
- const own = entries.filter((e) => e.account === account && e.success !== false);
163
+ // An Aleph credit purchase (kind `swap`) is the payment on another chain; the
164
+ // credits it bought are the incoming row. Only that row belongs on the statement.
165
+ const mine = entries.filter(
166
+ (e) => e.account === account && !(e.chain === 'aleph' && e.kind === 'swap')
167
+ );
168
+ const own = mine.filter((e) => e.success !== false);
80
169
  const assets = [
81
170
  ...new Set([...Object.keys(opening), ...own.filter((e) => e.priceAs).map((e) => e.asset)])
82
171
  ];
@@ -90,7 +179,8 @@ export function buildStatement({
90
179
  rows.push({
91
180
  date: e.date,
92
181
  time: e.time.slice(11, 19),
93
- text: `${KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind}${e.type === 'received' ? ' (Eingang)' : ''}`,
182
+ // Filecoin Pay: up to when a settlement paid its rail (the entry's memo).
183
+ text: `${kindText(e)}${e.type === 'received' ? ' (Eingang)' : ''}${e.chain === 'filecoin-pay' && e.kind === 'usage' && e.memo ? `, ${e.memo}` : ''}`,
94
184
  counterparty: e.counterpartyLabel
95
185
  ? `${e.counterpartyLabel} · ${e.counterparty}`
96
186
  : e.counterparty,
@@ -103,7 +193,10 @@ export function buildStatement({
103
193
  beleg: belege.get(e.hash) ?? '',
104
194
  fee: e.type === 'fee',
105
195
  usage: e.kind === 'usage',
106
- hashLabel: e.kind === 'usage' ? 'Ressource' : 'Tx'
196
+ purchase: e.type === 'received' && e.counterparty === 'aleph',
197
+ label: e.counterpartyLabel,
198
+ // Aleph's usage names a resource; a Filecoin Pay settlement is a transaction.
199
+ hashLabel: e.kind === 'usage' && e.chain === 'aleph' ? 'Ressource' : 'Tx'
107
200
  });
108
201
  }
109
202
  const debit = sum(rows.map((r) => r.debit || '0'));
@@ -121,6 +214,7 @@ export function buildStatement({
121
214
  debit,
122
215
  credit,
123
216
  rows,
217
+ monthly: monthly(rows),
124
218
  eurOut: sum(rows.filter((r) => r.debit && r.eur).map((r) => r.eur.replace(/^-/, ''))),
125
219
  eurIn: sum(rows.filter((r) => r.credit && r.eur).map((r) => r.eur)),
126
220
  eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
@@ -128,8 +222,8 @@ export function buildStatement({
128
222
  unvalued: rows.filter((r) => !r.eur).length
129
223
  };
130
224
  });
131
- // Aleph credits: a monthly usage statement, laid out as the Kontoauszug.
132
- const usage = chain === 'aleph';
225
+ // Aleph credits, Filecoin Pay: a monthly usage statement, laid out as the Kontoauszug.
226
+ const usage = Object.hasOwn(USAGE_NOTES, chain);
133
227
  return {
134
228
  kind: 'kontoauszug',
135
229
  title: usage ? 'Verbrauchsauszug' : 'Kontoauszug',
@@ -145,10 +239,8 @@ export function buildStatement({
145
239
  method,
146
240
  at,
147
241
  sections,
148
- unlisted: entries.filter(
149
- (e) => e.account === account && !e.priceAs && !assets.includes(e.asset)
150
- ).length,
151
- note: usage ? USAGE_NOTE : STATEMENT_NOTE
242
+ unlisted: mine.filter((e) => !e.priceAs && !assets.includes(e.asset)).length,
243
+ note: usage ? USAGE_NOTES[chain] : STATEMENT_NOTE
152
244
  };
153
245
  }
154
246