openvibers/openvibe.finance servercsv.js

csv.js

main 8.1 KB · 152 lines · javascript

1'use strict';
2/**
3 * A bank's CSV export → transactions (plan §L.2: "manual entry, CSV … always free").
4 *
5 * readCsv(text) → { rows: [{ posted_on, amount_cents, payee, memo, category }], columns, skipped: [{ line, why }] }
6 *
7 * What banks send differs, so this reads the file rather than a fixed layout:
8 * - the delimiter: comma, semicolon or tab, whichever splits the header into the most columns;
9 * - quoted fields with commas, doubled quotes and line breaks inside;
10 * - the columns by their header: a date, then either one signed amount or a debit and a credit, a payee or
11 * description, a memo, a category;
12 * - dates as 2026-11-18, 11/18/2026, 18/11/2026 (day first when a day over 12 says so, or when the file is
13 * day-first throughout), 18.11.2026, 2026/11/18, and "Nov 18, 2026";
14 * - amounts as -12.34, (12.34), $1,234.56, 1.234,56 (comma decimals), 12.34 CR / DR.
15 * A row that cannot be read is skipped and said, never guessed.
16 */
17
18const MAX_ROWS = 20000;
19
20function splitRows(text, delim) {
21 const rows = [];
22 let row = [], cell = '', quoted = false;
23 for (let i = 0; i < text.length; i++) {
24 const c = text[i];
25 if (quoted) {
26 if (c === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else quoted = false; }
27 else cell += c;
28 } else if (c === '"' && cell === '') quoted = true;
29 else if (c === delim) { row.push(cell); cell = ''; }
30 else if (c === '\n' || c === '\r') {
31 if (c === '\r' && text[i + 1] === '\n') i++;
32 row.push(cell); cell = '';
33 if (row.length > 1 || row[0].trim() !== '') rows.push(row);
34 row = [];
35 if (rows.length > MAX_ROWS + 1) break;
36 } else cell += c;
37 }
38 if (cell !== '' || row.length) { row.push(cell); if (row.length > 1 || row[0].trim() !== '') rows.push(row); }
39 return rows;
40}
41
42const norm = (h) => String(h || '').toLowerCase().replace(/[^a-z]/g, '');
43const HEADERS = {
44 date: ['date', 'transactiondate', 'posteddate', 'postingdate', 'bookingdate', 'valuedate', 'transdate', 'datum'],
45 amount: ['amount', 'transactionamount', 'amountusd', 'value', 'betrag', 'montant', 'sum'],
46 debit: ['debit', 'debitamount', 'withdrawal', 'withdrawals', 'moneyout', 'paidout', 'outflow', 'charge'],
47 credit: ['credit', 'creditamount', 'deposit', 'deposits', 'moneyin', 'paidin', 'inflow', 'payment'],
48 payee: ['payee', 'description', 'name', 'merchant', 'merchantname', 'details', 'transactiondescription', 'narrative', 'counterparty', 'originaldescription'],
49 memo: ['memo', 'notes', 'note', 'reference', 'comment', 'extendeddescription'],
50 category: ['category', 'categoryname'],
51};
52
53function columnsOf(header) {
54 const n = header.map(norm);
55 const pick = (names) => { for (const name of names) { const i = n.indexOf(name); if (i >= 0) return i; } return -1; };
56 const cols = {};
57 for (const [k, names] of Object.entries(HEADERS)) cols[k] = pick(names);
58 // "Description" as the payee when there is no payee column; otherwise the description is the memo.
59 if (cols.payee >= 0 && cols.memo < 0) {
60 const desc = n.indexOf('description');
61 if (desc >= 0 && desc !== cols.payee) cols.memo = desc;
62 }
63 return cols;
64}
65
66const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, sept: 9, oct: 10, nov: 11, dec: 12 };
67const pad = (n) => String(n).padStart(2, '0');
68const valid = (y, m, d) => {
69 if (!(y >= 1900 && y <= 2200 && m >= 1 && m <= 12 && d >= 1 && d <= 31)) return null;
70 const t = new Date(Date.UTC(y, m - 1, d));
71 return t.getUTCMonth() === m - 1 ? `${y}-${pad(m)}-${pad(d)}` : null;
72};
73/** One date → 'YYYY-MM-DD' or null. `dayFirst`: read 01/02/2026 as the 1st of February. */
74function readDate(s, dayFirst = false) {
75 const t = String(s || '').trim();
76 let m = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})/.exec(t);
77 if (m) return valid(+m[1], +m[2], +m[3]);
78 m = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{2,4})$/.exec(t);
79 if (m) {
80 let y = +m[3]; if (y < 100) y += 2000;
81 const a = +m[1], b = +m[2];
82 const sep = t.includes('.') ? '.' : null;
83 const df = dayFirst || sep === '.' || a > 12;
84 return df ? valid(y, b, a) : valid(y, a, b);
85 }
86 m = /^([A-Za-z]{3,4})[a-z]*\.? (\d{1,2}),? (\d{4})$/.exec(t);
87 if (m && MONTHS[m[1].toLowerCase()]) return valid(+m[3], MONTHS[m[1].toLowerCase()], +m[2]);
88 m = /^(\d{1,2}) ([A-Za-z]{3,4})[a-z]*\.? (\d{4})$/.exec(t);
89 if (m && MONTHS[m[2].toLowerCase()]) return valid(+m[3], MONTHS[m[2].toLowerCase()], +m[1]);
90 return null;
91}
92
93/** One amount → integer cents (signed) or null. */
94function readAmount(s) {
95 let t = String(s == null ? '' : s).trim();
96 if (!t) return null;
97 let sign = 1;
98 if (/^\(.*\)$/.test(t)) { sign = -1; t = t.slice(1, -1); }
99 if (/\bDR$/i.test(t)) { sign = -1; t = t.replace(/\s*DR$/i, ''); }
100 t = t.replace(/\s*CR$/i, '');
101 t = t.replace(/[^\d.,\-+]/g, '');
102 if (t.startsWith('-')) { sign = -sign; t = t.slice(1); } else if (t.startsWith('+')) t = t.slice(1);
103 if (t.endsWith('-')) { sign = -sign; t = t.slice(0, -1); }
104 if (!/\d/.test(t)) return null;
105 // 1.234,56 or 12,34: a comma decimal when the last separator is a comma followed by 1-2 digits.
106 const lastComma = t.lastIndexOf(','), lastDot = t.lastIndexOf('.');
107 if (lastComma > lastDot && /,\d{1,2}$/.test(t)) t = t.replace(/\./g, '').replace(',', '.');
108 else t = t.replace(/,/g, '');
109 if (!/^\d+(\.\d+)?$/.test(t)) return null;
110 const [whole, frac = ''] = t.split('.');
111 const cents = Number(whole) * 100 + Number((frac + '00').slice(0, 2)) + (Number(frac[2] || 0) >= 5 ? 1 : 0);
112 return Number.isSafeInteger(cents) ? sign * cents : null;
113}
114
115function readCsv(text) {
116 const src = String(text || '').replace(/^/, '');
117 const firstLine = src.split(/\r?\n/, 1)[0] || '';
118 const delim = [',', ';', '\t'].map((d) => [d, firstLine.split(d).length]).sort((a, b) => b[1] - a[1])[0][0];
119 const all = splitRows(src, delim);
120 if (all.length < 2) return { rows: [], columns: null, skipped: [], problem: 'The file has no rows under its header.' };
121 const header = all[0];
122 const cols = columnsOf(header);
123 if (cols.date < 0) return { rows: [], columns: cols, skipped: [], problem: 'No date column: the header needs a column named Date (or Posted Date, Transaction Date).' };
124 if (cols.amount < 0 && cols.debit < 0 && cols.credit < 0) return { rows: [], columns: cols, skipped: [], problem: 'No amount column: the header needs Amount, or Debit and Credit.' };
125 const body = all.slice(1, MAX_ROWS + 1);
126 // Day first when any date's first number is over 12 (and none's second is): the file is one layout throughout.
127 let dayFirst = false;
128 for (const r of body) {
129 const m = /^(\d{1,2})[/-](\d{1,2})[/-]\d{2,4}$/.exec(String(r[cols.date] || '').trim());
130 if (m && +m[1] > 12) { dayFirst = true; break; }
131 }
132 const rows = [], skipped = [];
133 body.forEach((r, i) => {
134 const line = i + 2;
135 const posted_on = readDate(r[cols.date], dayFirst);
136 if (!posted_on) { skipped.push({ line, why: `the date "${String(r[cols.date] || '').slice(0, 30)}" is not one this reads` }); return; }
137 let amount = null;
138 if (cols.amount >= 0) amount = readAmount(r[cols.amount]);
139 if (amount == null && (cols.debit >= 0 || cols.credit >= 0)) {
140 const out = cols.debit >= 0 ? readAmount(r[cols.debit]) : null;
141 const inn = cols.credit >= 0 ? readAmount(r[cols.credit]) : null;
142 if (out != null || inn != null) amount = (inn != null ? Math.abs(inn) : 0) - (out != null ? Math.abs(out) : 0);
143 }
144 if (amount == null) { skipped.push({ line, why: 'no amount' }); return; }
145 const text = (k) => (cols[k] >= 0 ? String(r[cols[k]] || '').replace(/\s+/g, ' ').trim().slice(0, 300) : '');
146 rows.push({ posted_on, amount_cents: amount, payee: text('payee'), memo: text('memo'), category: text('category').slice(0, 60) });
147 });
148 return { rows, columns: cols, skipped, problem: rows.length ? null : 'No row could be read.' };
149}
150
151module.exports = { readCsv, readDate, readAmount, splitRows, columnsOf };
152