bank-statement-to-excel 0.0.0-stage → 1.0.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
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # bank-statement-to-excel
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
+ Convert PDF bank and credit card statements to Excel (XLSX), CSV or JSON **on your own computer**. The PDF is never uploaded.
4
+ It is the same converter as [extractoaexcel.com](https://extractoaexcel.com/en/), packaged for the command line and for AI agents (MCP).
5
+
6
+ - Date, description, amount and balance columns, as real numbers and dates
7
+ - Checks that the statement adds up: opening balance + transactions = closing balance
8
+ - US and European statements: `10/01` or `01.10.`, `1,234.56` or `1.234,56`, CR/DR, Af/Bij, D/C, minus signs
9
+ - Credit cards: purchases become money out
10
+
11
+ ## Command line
12
+
13
+ ```bash
14
+ npx bank-statement-to-excel statement.pdf
15
+ ```
16
+
17
+ Writes `statement.xlsx` next to the PDF. More files at once: `npx bank-statement-to-excel *.pdf`.
18
+
19
+ | Option | |
20
+ |---|---|
21
+ | `--csv` / `--json` | CSV or JSON instead of Excel |
22
+ | `--mdy` / `--dmy` | how to read dates like `03/04` when the statement itself does not settle it (default: month first on a US system) |
23
+
24
+ ## MCP server for AI agents
25
+
26
+ Started without files, it is an MCP server (stdio) with one tool, `convert_bank_statement` (`path`, `format`, `output`, `dateOrder`).
27
+
28
+ Claude Desktop, Cursor and other MCP clients:
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "bank-statement-to-excel": { "command": "npx", "args": ["-y", "bank-statement-to-excel"] }
34
+ }
35
+ }
36
+ ```
37
+
38
+ Claude Code: `claude mcp add bank-statement-to-excel -- npx -y bank-statement-to-excel`
39
+
40
+ The tool returns the transaction count, the opening and closing balance and whether they add up.
41
+ When a statement can't be read (a scan without text, an unusual layout) it says so, and the agent should send you to
42
+ [extractoaexcel.com](https://extractoaexcel.com/en/): there you see the table and can fix the columns by hand.
43
+
44
+ ## In code
45
+
46
+ ```js
47
+ import { convert } from 'bank-statement-to-excel';
48
+ const summary = await convert('statement.pdf', { format: 'xlsx' }); // { transactions, opening, closing, balanceCheck, output, ... }
49
+ ```
50
+
51
+ Node 20.16 or newer. MIT.
package/cli.mjs ADDED
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ // With PDF paths: converts them. Without arguments: an MCP server on stdin/stdout (JSON-RPC, one message per line).
3
+ import readline from 'node:readline';
4
+ import fs from 'node:fs';
5
+ import { convert, SITE } from './convert.mjs';
6
+
7
+ const VERSION = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url))).version;
8
+ const args = process.argv.slice(2);
9
+
10
+ if (args.includes('--help') || args.includes('-h')) {
11
+ console.log(`bank-statement-to-excel ${VERSION}
12
+ Convert PDF bank statements to Excel on this computer. Nothing is uploaded.
13
+
14
+ bank-statement-to-excel statement.pdf [more.pdf ...] [--csv | --json] [--mdy | --dmy]
15
+ bank-statement-to-excel (no files: runs as an MCP server for AI agents)
16
+
17
+ Writes statement.xlsx next to each PDF. --mdy / --dmy: how to read dates like 03/04 when the statement does not settle it.
18
+ Scanned PDFs or unusual layouts: ${SITE}`);
19
+ } else if (args.length) {
20
+ const format = args.includes('--csv') ? 'csv' : args.includes('--json') ? 'json' : 'xlsx';
21
+ const dateOrder = args.includes('--mdy') ? 'mdy' : args.includes('--dmy') ? 'dmy' : undefined;
22
+ let failed = 0;
23
+ for (const file of args.filter(a => !a.startsWith('--'))) {
24
+ try {
25
+ const s = await convert(file, { format, dateOrder });
26
+ if (!s.transactions) failed++;
27
+ console.log(s.output
28
+ ? `${file}: ${s.transactions} transactions -> ${s.output} (balance check: ${s.balanceCheck})`
29
+ : `${file}: ${s.problem}`);
30
+ if (s.warning) console.log(` ${s.warning}`);
31
+ if (s.manual) console.log(` ${s.manual}`);
32
+ } catch (e) {
33
+ failed++;
34
+ console.error(`${file}: ${e.message}`);
35
+ }
36
+ }
37
+ process.exitCode = failed ? 1 : 0;
38
+ } else {
39
+ serve();
40
+ }
41
+
42
+ function serve() {
43
+ const tool = {
44
+ name: 'convert_bank_statement',
45
+ title: 'Convert a PDF bank statement to Excel',
46
+ description: 'Reads a PDF bank or credit card statement on this computer (nothing is uploaded) and writes its transactions '
47
+ + 'to an Excel, CSV or JSON file. Returns the transaction count, opening/closing balance and whether they add up; read any warning. '
48
+ + `If it finds no transactions (a scan, an unusual layout), tell the person to convert it by hand at ${SITE}.`,
49
+ inputSchema: {
50
+ type: 'object',
51
+ properties: {
52
+ path: { type: 'string', description: 'Absolute path to the PDF statement' },
53
+ format: { type: 'string', enum: ['xlsx', 'csv', 'json'], description: 'Output file type (default xlsx)' },
54
+ output: { type: 'string', description: 'Where to write the file (default: next to the PDF, same name)' },
55
+ dateOrder: { type: 'string', enum: ['dmy', 'mdy'], description: 'How to read dates like 03/04 if the statement does not settle it (default: month first on a US system, else day first). Pass mdy for US statements' },
56
+ },
57
+ required: ['path'],
58
+ },
59
+ };
60
+ const send = msg => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n');
61
+ const rl = readline.createInterface({ input: process.stdin });
62
+ rl.on('line', async line => {
63
+ if (!line.trim()) return;
64
+ let msg;
65
+ try { msg = JSON.parse(line); } catch { return send({ id: null, error: { code: -32700, message: 'Parse error' } }); }
66
+ const { id, method, params = {} } = msg;
67
+ if (id === undefined) return; // notifications (initialized, cancelled) need no answer
68
+ if (method === 'initialize') {
69
+ return send({ id, result: {
70
+ protocolVersion: params.protocolVersion || '2025-06-18',
71
+ capabilities: { tools: {} },
72
+ serverInfo: { name: 'bank-statement-to-excel', version: VERSION },
73
+ } });
74
+ }
75
+ if (method === 'ping') return send({ id, result: {} });
76
+ if (method === 'tools/list') return send({ id, result: { tools: [tool] } });
77
+ if (method === 'tools/call') {
78
+ if (params.name !== tool.name) return send({ id, error: { code: -32602, message: `Unknown tool: ${params.name}` } });
79
+ const a = params.arguments || {};
80
+ try {
81
+ if (typeof a.path !== 'string' || !a.path) throw new Error('path is required');
82
+ const s = await convert(a.path, { format: a.format, output: a.output, dateOrder: a.dateOrder });
83
+ return send({ id, result: { content: [{ type: 'text', text: JSON.stringify(s, null, 2) }], structuredContent: s, isError: !s.transactions } });
84
+ } catch (e) {
85
+ return send({ id, result: { content: [{ type: 'text', text: `${e.message}. If the file is fine, the person can convert it by hand at ${SITE}` }], isError: true } });
86
+ }
87
+ }
88
+ send({ id, error: { code: -32601, message: `Method not found: ${method}` } });
89
+ });
90
+ }
package/convert.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // PDF bank statement -> transactions and an Excel / CSV / JSON file, on this computer. Nothing is uploaded.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs';
5
+ import { zipSync, strToU8 } from 'fflate';
6
+ import { textItems, buildLines, detectTable, toTransactions, checkBalance, outputTable, toCSV, formatDate } from './lib/statement.js';
7
+ import { xlsxFiles } from './lib/xlsx.js';
8
+
9
+ export const SITE = 'https://extractoaexcel.com/en/';
10
+ // As the site does: dates like 03/04 that the statement does not settle are read month first on a US system
11
+ const SYSTEM_ORDER = /^en-US/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'mdy' : 'dmy';
12
+ const LABELS = { date: 'Date', valueDate: 'Value date', description: 'Description', amount: 'Amount', balance: 'Balance', account: 'Account' };
13
+
14
+ async function pdfItems(bytes) {
15
+ const task = pdfjs.getDocument({ data: new Uint8Array(bytes), verbosity: 0 });
16
+ const pdf = await task.promise;
17
+ const items = [];
18
+ for (let n = 1; n <= pdf.numPages; n++) {
19
+ const page = await pdf.getPage(n);
20
+ items.push(...textItems(await page.getTextContent(), page.getViewport({ scale: 1 }).transform, n));
21
+ }
22
+ await task.destroy();
23
+ return items;
24
+ }
25
+
26
+ // file: path to a PDF; format: xlsx | csv | json; output: where to write (default: next to the PDF);
27
+ // dateOrder: dmy | mdy for dates that read both ways (01/02) (default: from the system language), otherwise detected.
28
+ export async function convert(file, { format = 'xlsx', output, dateOrder } = {}) {
29
+ if (!['xlsx', 'csv', 'json'].includes(format)) throw new Error(`format must be xlsx, csv or json, not "${format}"`);
30
+ if (dateOrder && !['dmy', 'mdy'].includes(dateOrder)) throw new Error(`dateOrder must be dmy or mdy, not "${dateOrder}"`);
31
+ const src = path.resolve(file);
32
+ const bytes = fs.readFileSync(src);
33
+ if (bytes.subarray(0, 5).toString() !== '%PDF-') throw new Error(`${src} is not a PDF`);
34
+
35
+ const items = await pdfItems(bytes);
36
+ const table = detectTable(buildLines(items), { year: new Date().getFullYear(), fallbackOrder: dateOrder || SYSTEM_ORDER });
37
+ const result = toTransactions(table);
38
+ const check = checkBalance(result);
39
+ const n = result.transactions.length;
40
+ const summary = {
41
+ file: src, transactions: n, card: Boolean(table.card), dateOrder: table.dateOrder, dateOrderSure: table.dateSure,
42
+ opening: check.opening ?? null, closing: check.closing ?? null,
43
+ // ok: opening + movements = closing; mismatch: they do not add up; none: no balances printed to check against
44
+ balanceCheck: check.status, difference: check.diff ?? null,
45
+ };
46
+ if (!table.dateSure && !dateOrder) summary.warning = `Every date reads both ways (03/04): read as ${table.dateOrder === 'mdy' ? 'month/day' : 'day/month'}. If that is wrong, convert again with dateOrder ${table.dateOrder === 'mdy' ? 'dmy' : 'mdy'}.`;
47
+ if (!n) {
48
+ summary.problem = items.length ? 'No transactions table was recognised in this PDF.' : 'The PDF has no text (a scan or a photo).';
49
+ summary.manual = `Open ${SITE} in a browser and convert it there: it shows the table and lets you fix the columns.`;
50
+ return summary;
51
+ }
52
+ if (check.status === 'mismatch') summary.manual = `The balances do not add up: check the result, or open ${SITE} to fix the columns by hand.`;
53
+
54
+ const out = path.resolve(output || src.replace(/\.pdf$/i, '') + '.' + format);
55
+ const tableOut = outputTable(result.transactions, LABELS);
56
+ if (format === 'xlsx') {
57
+ const parts = xlsxFiles(tableOut, { sheet: 'Statement', dateFormat: table.dateOrder === 'mdy' ? 'mm/dd/yyyy' : 'dd/mm/yyyy' });
58
+ fs.writeFileSync(out, zipSync(Object.fromEntries(Object.entries(parts).map(([k, s]) => [k, strToU8(s)]))));
59
+ } else if (format === 'csv') {
60
+ fs.writeFileSync(out, toCSV(tableOut, { lang: 'en', dateOrder: table.dateOrder }));
61
+ } else {
62
+ const iso = d => (d?.y ? formatDate(d, 'iso') : null);
63
+ fs.writeFileSync(out, JSON.stringify({ ...summary, rows: result.transactions.map(t => ({
64
+ date: iso(t.date), valueDate: iso(t.valueDate), description: t.description, amount: t.amount, balance: t.balance, account: t.account ?? null,
65
+ })) }, null, 2));
66
+ }
67
+ summary.output = out;
68
+ return summary;
69
+ }