@le-space/eigenbeleg 0.1.0 → 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.
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 as a monthly **Verbrauchsauszug**. `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.1.1",
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.3.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,39 @@ 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
+ ethereum: 'Ethereum',
97
+ base: 'Base'
57
98
  };
58
99
 
59
- /** Where a chain's data comes from, named in the footer of its documents. */
100
+ /**
101
+ * Where a chain's data comes from, named in the footer of its documents.
102
+ * Ethereum and Base: Eigenbeleg reads them through Alchemy (@le-space/chains'
103
+ * EVM reader, with the server's key).
104
+ */
60
105
  export const DATA_SOURCES = /** @type {Record<string, string>} */ ({
61
106
  near: 'NearBlocks.io APIs, NEAR-Archiv-RPC',
62
107
  filecoin: 'Filfox',
63
108
  akash: 'Akash-RPC, Akash Console',
64
- aleph: 'Aleph-API (api2.aleph.im)'
109
+ aleph: 'Aleph-API (api2.aleph.im)',
110
+ ethereum: 'Alchemy APIs (Ethereum Mainnet)',
111
+ base: 'Alchemy APIs (Base Mainnet)'
65
112
  });
66
113
 
67
114
  /**
@@ -156,11 +203,12 @@ export function buildDocument({
156
203
  positions.push({
157
204
  pos: 0,
158
205
  entry: e,
159
- what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
206
+ what: kindText(e),
160
207
  recipient: e.counterpartyLabel || e.counterparty
161
208
  });
162
209
  }
163
210
  const first = number || `EB-${period.to.slice(0, 4)}-001`;
211
+ const chainName = CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain;
164
212
  /** @type {Transaction[]} */
165
213
  const transactions = [];
166
214
  for (const p of positions) {
@@ -181,7 +229,7 @@ export function buildDocument({
181
229
  const x = excluded.find((y) => y.entry === e);
182
230
  return {
183
231
  entry: e,
184
- what: KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind,
232
+ what: kindText(e),
185
233
  onIt: !x,
186
234
  why: x?.why ?? ''
187
235
  };
@@ -222,7 +270,7 @@ export function buildDocument({
222
270
  addresses: [...payer.addresses]
223
271
  },
224
272
  chain,
225
- chainName: CHAIN_NAMES[/** @type {keyof typeof CHAIN_NAMES} */ (chain)] ?? chain,
273
+ chainName,
226
274
  network,
227
275
  testnet: network !== 'mainnet',
228
276
  period,
@@ -234,14 +282,17 @@ export function buildDocument({
234
282
  eur: round(eurExact.replace(/^-/, ''), 2),
235
283
  eurExact: eurExact.replace(/^-/, '')
236
284
  },
285
+ // The rate's name without its day (`… vom 2026-08-10`): the day is each position's.
237
286
  sources: [
238
287
  ...new Set(
239
288
  positions.map((p) =>
240
- /** @type {any} */ (p.entry.eur).source.replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
289
+ /** @type {any} */ (p.entry.eur).source
290
+ .replace(/ \d{4}-\d{2}-\d{2}.*$/, '')
291
+ .replace(/ vom$/, '')
241
292
  )
242
293
  )
243
294
  ],
244
- note: NOTE,
295
+ note: noInvoice(chain, chainName).note,
245
296
  notInvoice: NOT_AN_INVOICE
246
297
  };
247
298
  }
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,15 @@ 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
+ } from './statement.js';
31
+ /** @typedef {import('./statement.js').MonthlyLine} MonthlyLine */
21
32
  export { statementPdf } from './statement-pdf.js';
22
33
  export { valueEntries, fixedRates } from './value.js';
23
34
  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,10 +33,14 @@ 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';
@@ -43,6 +48,10 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
43
48
  const subject = `${st.title} ${st.chainName} ${st.account}, ${deDate(st.period.from)} – ${deDate(st.period.to)}`;
44
49
  const { pdf, fonts } = await createPdfA();
45
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;
46
55
  const l = pageLayout(pdf, fonts, {
47
56
  margin: M,
48
57
  bottom: 16,
@@ -86,7 +95,7 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
86
95
  l.y -= 12;
87
96
  }
88
97
  l.y = Math.min(l.y, leftEnd) - 14;
89
- text(st.title, { face: bold, size: 18 });
98
+ l.title(st.title, { face: bold, size: 18 }, mark);
90
99
  text('Konto', { face: bold, size: 7.5, color: GREY });
91
100
  text(st.account, { face: mono, size: 9 });
92
101
  l.y -= 6;
@@ -99,6 +108,35 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
99
108
  l.page.drawRectangle({ x: M, y: l.y - 18, width, height: 18, color: BAND });
100
109
  bold.draw(l.page, `${s.asset} · ${st.account}`, { x: M + 6, y: l.y - 12.5, size: 9.5 });
101
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
+ }
102
140
  const head = () => {
103
141
  let x = M;
104
142
  for (const c of COLS) {
@@ -175,14 +213,17 @@ export async function statementPdf(st, { creator = CREATOR, producer = PRODUCER
175
213
  l.y -= 15;
176
214
  // the check
177
215
  if (st.method === 'archive' && s.reported !== null) {
178
- const ok = s.difference !== null && /^-?0(\.0+)?$/.test(s.difference);
216
+ const ok = reconciled(s.difference) === true;
217
+ const difference = /** @type {string} */ (s.difference);
179
218
  const when = st.at
180
219
  ? ` (Block ${st.at.closing.height}, ${st.at.closing.time.slice(0, 19).replace('T', ' ')} UTC)`
181
220
  : '';
182
221
  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).`,
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).`,
186
227
  { size: 7.5, color: ok ? OK : WARN }
187
228
  );
188
229
  } else {
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 =
@@ -42,9 +60,62 @@ export const STATEMENT_NOTE =
42
60
  * @property {string} beleg the Eigenbeleg's number, when the booking has one
43
61
  * @property {boolean} fee
44
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)
45
65
  * @property {string} hashLabel what the hash is: `Tx`, or `Ressource` for usage
46
66
  */
47
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
+
48
119
  /**
49
120
  * @param {object} p
50
121
  * @param {{ name: string, address: string }} p.payer the account holder
@@ -76,7 +147,12 @@ export function buildStatement({
76
147
  number,
77
148
  issuedAt
78
149
  }) {
79
- const own = entries.filter((e) => e.account === account && e.success !== false);
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);
80
156
  const assets = [
81
157
  ...new Set([...Object.keys(opening), ...own.filter((e) => e.priceAs).map((e) => e.asset)])
82
158
  ];
@@ -90,7 +166,7 @@ export function buildStatement({
90
166
  rows.push({
91
167
  date: e.date,
92
168
  time: e.time.slice(11, 19),
93
- text: `${KIND_TEXT[/** @type {keyof typeof KIND_TEXT} */ (e.kind)] ?? e.kind}${e.type === 'received' ? ' (Eingang)' : ''}`,
169
+ text: `${kindText(e)}${e.type === 'received' ? ' (Eingang)' : ''}`,
94
170
  counterparty: e.counterpartyLabel
95
171
  ? `${e.counterpartyLabel} · ${e.counterparty}`
96
172
  : e.counterparty,
@@ -103,6 +179,8 @@ export function buildStatement({
103
179
  beleg: belege.get(e.hash) ?? '',
104
180
  fee: e.type === 'fee',
105
181
  usage: e.kind === 'usage',
182
+ purchase: e.type === 'received' && e.counterparty === 'aleph',
183
+ label: e.counterpartyLabel,
106
184
  hashLabel: e.kind === 'usage' ? 'Ressource' : 'Tx'
107
185
  });
108
186
  }
@@ -121,6 +199,7 @@ export function buildStatement({
121
199
  debit,
122
200
  credit,
123
201
  rows,
202
+ monthly: monthly(rows),
124
203
  eurOut: sum(rows.filter((r) => r.debit && r.eur).map((r) => r.eur.replace(/^-/, ''))),
125
204
  eurIn: sum(rows.filter((r) => r.credit && r.eur).map((r) => r.eur)),
126
205
  eurFees: sum(rows.filter((r) => r.fee && r.eur).map((r) => r.eur.replace(/^-/, ''))),
@@ -145,9 +224,7 @@ export function buildStatement({
145
224
  method,
146
225
  at,
147
226
  sections,
148
- unlisted: entries.filter(
149
- (e) => e.account === account && !e.priceAs && !assets.includes(e.asset)
150
- ).length,
227
+ unlisted: mine.filter((e) => !e.priceAs && !assets.includes(e.asset)).length,
151
228
  note: usage ? USAGE_NOTE : STATEMENT_NOTE
152
229
  };
153
230
  }