-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (87 loc) · 2.38 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const log4js = require('log4js');
log4js.configure({
appenders: {
file: { type: 'fileSync', filename: 'debug.log' },
},
categories: {
default: { appenders: ['file'], level: 'debug' }
},
});
const logger = log4js.getLogger('file');
logger.level = 'debug';
const fs = require('fs');
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
const parse = require('./parse');
const exportDB = require('./export');
const bank = require('./bank');
const db = new bank.BankDB();
const {formatCurrency} = require('./utility');
const commands = [
{regex: /^List All$/, action: (_) => listAll(db)},
{regex: /^List (.+)$/, action: (groups) => listPerson(db, groups[1])},
{regex: /^Import File (.+)\.(.+)$/, action: (groups) => parse.parseFile(groups[1], groups[2], db)},
{regex: /^Export File (.+)\.(.+)$/, action: (groups) => exportFile(groups[1], groups[2])},
{regex: /.?/, action: (_) => console.error('unrecognised command')},
];
function listAll(db) {
db.people.forEach((v, k, _)=>{
console.log('%s: %s', k, formatCurrency(v.balance));
});
}
function listPerson(db, name) {
const person = db.getPerson(name);
if(person === undefined) {
console.error('Person does not exist');
return;
};
for(let i = 0; i < person.transactions.length; i++) {
let trans = person.transactions[i];
// "to x" / "from x" (we don't need to show that it's from/to the given user)
toText = (trans.from === name)
// outgoing
? `${formatCurrency(-trans.amount)} to ${trans.to}`
: `${formatCurrency(trans.amount)} from ${trans.from}`;
console.log('%s: %s for "%s"',
trans.date.format('DD/MM/Y'),
toText,
trans.narrative
);
}
}
function exportFile(name, extension) {
const list = db.getAllTransactions();
switch(extension) {
case 'csv':
exportDB.exportCSV(`${name}.${extension}`, db);
break;
case 'json':
exportDB.exportJSON(`${name}.${extension}`, db);
break;
case 'xml':
exportDB.exportXML(`${name}.${extension}`, db);
break;
default:
console.error('unrecognised file type');
break;
}
}
function startPrompt() {
rl.setPrompt('SupportBank>');
rl.prompt();
rl.on('line', (answer) => {
for(let i = 0; i < commands.length; i++) {
let command = commands[i];
let match = answer.match(command.regex);
if(match === null) {
continue;
}
command.action(match);
break;
}
rl.prompt();
});
}
startPrompt();