-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract-statement.js
More file actions
68 lines (62 loc) · 2.28 KB
/
Copy pathextract-statement.js
File metadata and controls
68 lines (62 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { spawn } from 'child_process';
import { resolve } from 'path';
import { fileURLToPath } from 'url';
import { parseTransactions, extractPhone, extractSender } from './lib/statement.js';
const jarPath = fileURLToPath(new URL('./node_modules/tabula-js/lib/tabula-java.jar', import.meta.url));
export async function runTabula({
pdfPath = './statement.pdf',
format = 'TSV',
pages = 'all',
guess = false,
} = {}) {
const resolvedPdf = resolve(pdfPath);
const args = ['-jar', jarPath, '--format', format, '--pages', pages];
if (guess) args.push('--guess');
args.push(resolvedPdf);
return new Promise((resolvePromise, reject) => {
const proc = spawn('java', args, { cwd: process.cwd() });
let stdout = '';
let stderr = '';
proc.stdout.setEncoding('utf8');
proc.stdout.on('data', chunk => (stdout += chunk));
proc.stderr.setEncoding('utf8');
proc.stderr.on('data', chunk => (stderr += chunk));
proc.on('error', reject);
proc.on('close', (code, signal) => {
if (code !== 0 || signal) {
const reason = signal ? `signal ${signal}` : `exit ${code}`;
reject(new Error(`tabula exited (${reason}): ${stderr.trim()}`));
return;
}
resolvePromise(stdout);
});
});
}
async function main() {
try {
const pdfPath = process.argv[2] ?? './statement.pdf';
const tsv = await runTabula({ pdfPath });
console.log('Raw extracted TSV (tabula output):');
console.log(tsv.trim() || '(empty)');
const rows = parseTransactions(tsv);
const filtered = rows.filter(row => {
const detail = (row.details ?? '').toLowerCase();
return /mobi\s*522522/i.test(detail);
});
console.log(`Extracted ${rows.length} rows from ${pdfPath}`);
const enriched = filtered.map(row => ({
...row,
phone: extractPhone(row.details),
sender: extractSender(row.details),
}));
console.log(`Kept ${filtered.length} rows that mention 522522 in their details`);
console.log(JSON.stringify(enriched, null, 2));
} catch (error) {
console.error('Unable to extract rows:', error.message);
process.exit(1);
}
}
const entryScript = fileURLToPath(process.argv[1] ? new URL(process.argv[1], 'file://') : '');
if (process.argv[1] && entryScript === fileURLToPath(import.meta.url)) {
await main();
}