-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathledger-converter-tui.ts
More file actions
416 lines (349 loc) · 12 KB
/
ledger-converter-tui.ts
File metadata and controls
416 lines (349 loc) · 12 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env bun
/**
* ledger-converter-tui.ts - Interactive TUI for Ledger Conversion
*
* Zero-dependency interactive terminal interface for converting QIF/CSV files
* to Ledger format. Uses only built-in Bun/Node APIs.
*
* Features:
* - Arrow key navigation for option selection
* - Sample files as default input (examples/sample.qif, examples/sample.csv)
* - Transaction preview before final output
* - Back navigation (press 'b' or Escape)
* - Output to stdout or save to file
*
* Usage:
* bun ledger-converter-tui.ts
*
* Build:
* bun build --compile --outfile=ledger-converter-tui ledger-converter-tui.ts
*/
import {
colors,
colorize,
printHeader,
printInfo,
printSuccess,
printError,
printWarning,
printBox,
promptText,
promptSelect,
promptConfirm,
isBack,
createSpinner,
} from "./cli/tui";
import { parseQIF } from "./utils/qif_parser";
import { parseCSV } from "./utils/csv_parser";
import {
qif2ledger,
csv2ledger,
formatLedgerTransaction,
type LedgerTransaction,
} from "./utils/ledger_converter";
// ============================================================================
// Types
// ============================================================================
type InputFormat = "qif" | "csv";
type OutputDestination = "stdout" | "file";
interface ConversionState {
format?: InputFormat;
inputFile?: string;
assetAccount?: string;
outputDestination?: OutputDestination;
outputFile?: string;
}
// ============================================================================
// File Utilities
// ============================================================================
async function fileExists(path: string): Promise<boolean> {
try {
await Bun.file(path).text();
return true;
} catch {
return false;
}
}
async function readFile(path: string): Promise<string> {
return await Bun.file(path).text();
}
async function writeFile(path: string, content: string): Promise<void> {
await Bun.write(path, content);
}
// ============================================================================
// Conversion Functions
// ============================================================================
function parseTransactions(
content: string,
format: InputFormat,
assetAccount: string
): LedgerTransaction[] {
const transactions: LedgerTransaction[] = [];
if (format === "qif") {
for (const qifTx of parseQIF(content)) {
transactions.push(qif2ledger(qifTx, assetAccount));
}
} else {
for (const csvTx of parseCSV(content)) {
transactions.push(csv2ledger(csvTx, assetAccount));
}
}
return transactions;
}
function formatAllTransactions(transactions: LedgerTransaction[]): string {
return transactions.map(formatLedgerTransaction).join("\n");
}
// ============================================================================
// Preview Functions
// ============================================================================
function previewTransactions(
transactions: LedgerTransaction[],
count: number = 3
): void {
const previewCount = Math.min(count, transactions.length);
console.log();
printInfo(`Preview of first ${previewCount} transaction(s):`);
console.log();
for (let i = 0; i < previewCount; i++) {
const formatted = formatLedgerTransaction(transactions[i]);
const lines = formatted.split("\n").filter((l) => l.trim());
for (const line of lines) {
if (line.match(/^\d{4}\/\d{2}\/\d{2}/)) {
// Date line - highlight
console.log(colorize(line, colors.cyan, colors.bold));
} else if (line.startsWith(" ;")) {
// Memo line
console.log(colorize(line, colors.dim));
} else if (line.includes("$")) {
// Amount line - highlight the amount
const [account, ...rest] = line.split("$");
console.log(account + colorize("$" + rest.join("$"), colors.green));
} else {
console.log(line);
}
}
console.log();
}
if (transactions.length > previewCount) {
printInfo(`... and ${transactions.length - previewCount} more transaction(s)`);
console.log();
}
}
// ============================================================================
// Interactive Flow
// ============================================================================
async function selectFormat(): Promise<InputFormat | "back"> {
const result = await promptSelect<InputFormat>("Select input format:", [
{ label: "QIF (Quicken Interchange Format)", value: "qif" },
{ label: "CSV (Comma-Separated Values)", value: "csv" },
]);
if (isBack(result)) return "back";
return result.value;
}
async function getInputFile(format: InputFormat): Promise<string | "back"> {
const extension = format === "qif" ? ".qif" : ".csv";
const defaultFile = format === "qif" ? "examples/sample.qif" : "examples/sample.csv";
while (true) {
const result = await promptText(`Enter path to ${format.toUpperCase()} file:`, defaultFile);
if (isBack(result)) return "back";
const path = result.value;
if (!path) {
printError("File path cannot be empty");
continue;
}
// Expand home directory
const expandedPath = path.startsWith("~")
? path.replace("~", process.env.HOME || "")
: path;
if (!(await fileExists(expandedPath))) {
printError(`File not found: ${expandedPath}`);
continue;
}
// Warn if extension doesn't match
if (!expandedPath.toLowerCase().endsWith(extension)) {
printWarning(`File doesn't have ${extension} extension, but will try to parse anyway`);
}
return expandedPath;
}
}
async function getAssetAccount(): Promise<string | "back"> {
while (true) {
const result = await promptText(
"Enter asset account name:",
"Assets:Checking"
);
if (isBack(result)) return "back";
const account = result.value;
if (!account) {
printError("Account name cannot be empty");
continue;
}
return account;
}
}
async function selectOutputDestination(): Promise<OutputDestination | "back"> {
const result = await promptSelect<OutputDestination>("Output to:", [
{ label: "Terminal (stdout)", value: "stdout" },
{ label: "File", value: "file" },
]);
if (isBack(result)) return "back";
return result.value;
}
async function getOutputFile(): Promise<string | "back"> {
while (true) {
const result = await promptText("Enter output file path:");
if (isBack(result)) return "back";
const path = result.value;
if (!path) {
printError("File path cannot be empty");
continue;
}
// Expand home directory
const expandedPath = path.startsWith("~")
? path.replace("~", process.env.HOME || "")
: path;
// Check if file exists and confirm overwrite
if (await fileExists(expandedPath)) {
const confirmResult = await promptConfirm(
`File ${expandedPath} already exists. Overwrite?`,
false
);
if (isBack(confirmResult)) return "back";
if (!confirmResult.value) continue;
}
return expandedPath;
}
}
// ============================================================================
// Main Flow (with back navigation)
// ============================================================================
async function main(): Promise<void> {
console.log();
printHeader("Ledger Converter");
console.log();
printInfo("Convert QIF or CSV files to Ledger-CLI format");
printInfo("Press 'b' or Escape at any prompt to go back");
console.log();
const state: ConversionState = {};
// Step 1: Select format
step1: while (true) {
const format = await selectFormat();
if (format === "back") {
printInfo("Already at the beginning. Press Ctrl+C to exit.");
continue;
}
state.format = format;
// Step 2: Get input file
step2: while (true) {
const inputFile = await getInputFile(state.format!);
if (inputFile === "back") {
continue step1; // Go back to format selection
}
state.inputFile = inputFile;
// Step 3: Get asset account
step3: while (true) {
const assetAccount = await getAssetAccount();
if (assetAccount === "back") {
continue step2; // Go back to file selection
}
state.assetAccount = assetAccount;
// Parse and preview
console.log();
const spinner = createSpinner("Parsing transactions...");
let content: string;
let transactions: LedgerTransaction[];
try {
content = await readFile(state.inputFile!);
transactions = parseTransactions(
content,
state.format!,
state.assetAccount!
);
spinner.stop(`Parsed ${transactions.length} transaction(s)`);
} catch (error) {
spinner.stop();
printError(`Failed to parse file: ${error instanceof Error ? error.message : error}`);
continue step2; // Go back to file selection
}
if (transactions.length === 0) {
printWarning("No transactions found in file");
continue step2;
}
// Preview transactions
previewTransactions(transactions, 3);
// Step 4: Confirm and select output
step4: while (true) {
const confirmResult = await promptConfirm("Proceed with conversion?", true);
if (isBack(confirmResult)) {
continue step3; // Go back to asset account
}
if (!confirmResult.value) {
printInfo("Conversion cancelled");
process.exit(0);
}
// Step 5: Select output destination
step5: while (true) {
const outputDest = await selectOutputDestination();
if (outputDest === "back") {
continue step4; // Go back to confirmation
}
state.outputDestination = outputDest;
if (state.outputDestination === "file") {
// Step 6: Get output file
step6: while (true) {
const outputFile = await getOutputFile();
if (outputFile === "back") {
continue step5; // Go back to output destination
}
state.outputFile = outputFile;
// Write to file
console.log();
const writeSpinner = createSpinner("Writing output file...");
try {
const output = formatAllTransactions(transactions);
await writeFile(state.outputFile!, output);
writeSpinner.stop(`Saved to ${state.outputFile}`);
} catch (error) {
writeSpinner.stop();
printError(
`Failed to write file: ${error instanceof Error ? error.message : error}`
);
continue step6;
}
// Done!
console.log();
printSuccess("Conversion complete!");
console.log();
printBox([
`Input: ${state.inputFile}`,
`Format: ${state.format?.toUpperCase()}`,
`Output: ${state.outputFile}`,
`Transactions: ${transactions.length}`,
], "Summary");
console.log();
return;
}
} else {
// Output to stdout
console.log();
console.log(colorize("─".repeat(60), colors.dim));
console.log(formatAllTransactions(transactions));
console.log(colorize("─".repeat(60), colors.dim));
console.log();
printSuccess("Conversion complete!");
console.log();
return;
}
}
}
}
}
}
}
// ============================================================================
// Entry Point
// ============================================================================
main().catch((error) => {
printError(`Fatal error: ${error instanceof Error ? error.message : error}`);
process.exit(1);
});