@hisaabo/cli 0.1.0

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.
Files changed (48) hide show
  1. package/.turbo/turbo-build.log +13 -0
  2. package/.turbo/turbo-typecheck.log +4 -0
  3. package/CLI-UX-ARCHITECTURE.md +1269 -0
  4. package/dist/bin/hisaabo.js +3516 -0
  5. package/package.json +34 -0
  6. package/src/auth.ts +212 -0
  7. package/src/bin/hisaabo.ts +950 -0
  8. package/src/client.ts +1229 -0
  9. package/src/commands/bank/index.ts +244 -0
  10. package/src/commands/dashboard.ts +105 -0
  11. package/src/commands/expense/create.ts +51 -0
  12. package/src/commands/expense/delete.ts +45 -0
  13. package/src/commands/expense/list.ts +65 -0
  14. package/src/commands/gst/index.ts +116 -0
  15. package/src/commands/import/index.ts +100 -0
  16. package/src/commands/invoice/create.ts +262 -0
  17. package/src/commands/invoice/delete.ts +44 -0
  18. package/src/commands/invoice/get.ts +105 -0
  19. package/src/commands/invoice/list.ts +126 -0
  20. package/src/commands/invoice/pdf.ts +75 -0
  21. package/src/commands/invoice/status.ts +41 -0
  22. package/src/commands/item/create.ts +98 -0
  23. package/src/commands/item/delete.ts +44 -0
  24. package/src/commands/item/list.ts +81 -0
  25. package/src/commands/item/stock.ts +46 -0
  26. package/src/commands/party/create.ts +88 -0
  27. package/src/commands/party/delete.ts +44 -0
  28. package/src/commands/party/get.ts +42 -0
  29. package/src/commands/party/ledger.ts +63 -0
  30. package/src/commands/party/list.ts +69 -0
  31. package/src/commands/payment/create.ts +133 -0
  32. package/src/commands/payment/delete.ts +46 -0
  33. package/src/commands/payment/list.ts +66 -0
  34. package/src/commands/report/index.ts +218 -0
  35. package/src/commands/shipment/index.ts +170 -0
  36. package/src/commands/store/index.ts +77 -0
  37. package/src/commands/target/index.ts +118 -0
  38. package/src/components/ErrorDisplay.tsx +16 -0
  39. package/src/components/Header.tsx +26 -0
  40. package/src/components/MoneyCell.tsx +16 -0
  41. package/src/components/Spinner.tsx +12 -0
  42. package/src/components/StatusBadge.tsx +39 -0
  43. package/src/components/Table.tsx +63 -0
  44. package/src/config.ts +47 -0
  45. package/src/format.ts +180 -0
  46. package/src/output.ts +227 -0
  47. package/tsconfig.json +22 -0
  48. package/tsup.config.ts +13 -0
@@ -0,0 +1,3516 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/bin/hisaabo.ts
4
+ import { Command } from "commander";
5
+ import * as readline11 from "readline";
6
+
7
+ // src/client.ts
8
+ import superjson from "superjson";
9
+ var HisaaboApiError = class extends Error {
10
+ constructor(hisaaboError) {
11
+ super(formatHisaaboError(hisaaboError));
12
+ this.hisaaboError = hisaaboError;
13
+ this.name = "HisaaboApiError";
14
+ }
15
+ };
16
+ function formatHisaaboError(err) {
17
+ switch (err.code) {
18
+ case "unauthorized":
19
+ return `Authentication required: ${err.message}`;
20
+ case "forbidden":
21
+ return `Permission denied: ${err.message}`;
22
+ case "not_found":
23
+ return `Not found: ${err.resource}`;
24
+ case "validation_failed":
25
+ return `Validation failed:
26
+ ` + Object.entries(err.fields).map(([field, msgs]) => ` ${field}: ${msgs.join(", ")}`).join("\n");
27
+ case "network_error":
28
+ return `Network error: ${err.message}`;
29
+ case "api_error":
30
+ return `API error: ${err.message}`;
31
+ }
32
+ }
33
+ function normalizeTrpcError(raw) {
34
+ if (!raw || typeof raw !== "object") {
35
+ return { code: "api_error", message: "Unknown error from API" };
36
+ }
37
+ const err = raw;
38
+ const code = err["code"];
39
+ const message = err["message"] ?? "Unknown error";
40
+ if (code === "UNAUTHORIZED") return { code: "unauthorized", message };
41
+ if (code === "FORBIDDEN") return { code: "forbidden", message };
42
+ if (code === "NOT_FOUND") return { code: "not_found", resource: message };
43
+ if (code === "BAD_REQUEST") {
44
+ const data = err["data"];
45
+ const zodError = data?.["zodError"];
46
+ if (zodError?.fieldErrors) {
47
+ return { code: "validation_failed", fields: zodError.fieldErrors };
48
+ }
49
+ return { code: "validation_failed", fields: { _: [message] } };
50
+ }
51
+ return { code: "api_error", message };
52
+ }
53
+ var HisaaboClient = class {
54
+ constructor(config) {
55
+ this.config = config;
56
+ this.apiUrl = config.apiUrl;
57
+ }
58
+ apiUrl;
59
+ buildHeaders() {
60
+ return {
61
+ "Authorization": `Bearer ${this.config.token}`,
62
+ "x-business-id": this.config.businessId,
63
+ "x-tenant-id": this.config.tenantId,
64
+ "x-client-type": "cli"
65
+ };
66
+ }
67
+ async unwrap(res) {
68
+ const body = await res.json();
69
+ if (typeof body !== "object" || body === null) {
70
+ throw new HisaaboApiError({ code: "api_error", message: "Unexpected response format from API" });
71
+ }
72
+ const envelope = body;
73
+ if (!res.ok || "error" in envelope) {
74
+ throw new HisaaboApiError(normalizeTrpcError(envelope["error"] ?? { code: "api_error", message: `HTTP ${res.status}` }));
75
+ }
76
+ const result = envelope["result"];
77
+ if (!result) {
78
+ throw new HisaaboApiError({ code: "api_error", message: "Missing result in API response" });
79
+ }
80
+ const data = result["data"];
81
+ return superjson.deserialize(data);
82
+ }
83
+ async query(path3, input) {
84
+ const url = new URL(`${this.config.apiUrl}/api/trpc/${path3}`);
85
+ if (input !== void 0) {
86
+ url.searchParams.set("input", JSON.stringify(superjson.serialize(input)));
87
+ }
88
+ try {
89
+ const res = await fetch(url.toString(), { headers: this.buildHeaders() });
90
+ return this.unwrap(res);
91
+ } catch (e) {
92
+ if (e instanceof HisaaboApiError) throw e;
93
+ throw new HisaaboApiError({ code: "network_error", message: String(e instanceof Error ? e.message : e) });
94
+ }
95
+ }
96
+ async mutate(path3, input) {
97
+ try {
98
+ const res = await fetch(`${this.config.apiUrl}/api/trpc/${path3}`, {
99
+ method: "POST",
100
+ headers: { ...this.buildHeaders(), "Content-Type": "application/json" },
101
+ body: JSON.stringify(superjson.serialize(input))
102
+ });
103
+ return this.unwrap(res);
104
+ } catch (e) {
105
+ if (e instanceof HisaaboApiError) throw e;
106
+ throw new HisaaboApiError({ code: "network_error", message: String(e instanceof Error ? e.message : e) });
107
+ }
108
+ }
109
+ // ── Auth ──────────────────────────────────────────────────────
110
+ get auth() {
111
+ const c = this;
112
+ return {
113
+ login(input) {
114
+ return c.mutate("auth.login", input);
115
+ },
116
+ logout() {
117
+ return c.mutate("auth.logout", {});
118
+ },
119
+ me() {
120
+ return c.query("auth.me");
121
+ }
122
+ };
123
+ }
124
+ // ── Business ──────────────────────────────────────────────────
125
+ get business() {
126
+ const c = this;
127
+ return {
128
+ list() {
129
+ return c.query("business.list");
130
+ },
131
+ get() {
132
+ return c.query("business.get");
133
+ }
134
+ };
135
+ }
136
+ // ── Invoice ───────────────────────────────────────────────────
137
+ get invoice() {
138
+ const c = this;
139
+ return {
140
+ list(input) {
141
+ return c.query("invoice.list", input);
142
+ },
143
+ get(id) {
144
+ return c.query("invoice.get", { id });
145
+ },
146
+ create(input) {
147
+ return c.mutate("invoice.create", input);
148
+ },
149
+ updateStatus(id, status) {
150
+ return c.mutate("invoice.updateStatus", { id, status });
151
+ },
152
+ delete(id) {
153
+ return c.mutate("invoice.delete", { id });
154
+ }
155
+ };
156
+ }
157
+ // ── Party ─────────────────────────────────────────────────────
158
+ get party() {
159
+ const c = this;
160
+ return {
161
+ list(input) {
162
+ return c.query("party.list", input);
163
+ },
164
+ get(id) {
165
+ return c.query("party.get", { id });
166
+ },
167
+ create(input) {
168
+ return c.mutate("party.create", input);
169
+ },
170
+ update(id, data) {
171
+ return c.mutate("party.update", { id, data });
172
+ },
173
+ delete(id) {
174
+ return c.mutate("party.delete", { id });
175
+ },
176
+ ledger(partyId, input) {
177
+ return c.query("party.ledger", { partyId, ...input });
178
+ }
179
+ };
180
+ }
181
+ // ── Item ──────────────────────────────────────────────────────
182
+ get item() {
183
+ const c = this;
184
+ return {
185
+ list(input) {
186
+ return c.query("item.list", input);
187
+ },
188
+ get(id) {
189
+ return c.query("item.get", { id });
190
+ },
191
+ create(input) {
192
+ return c.mutate("item.create", input);
193
+ },
194
+ update(id, data) {
195
+ return c.mutate("item.update", { id, data });
196
+ },
197
+ delete(id) {
198
+ return c.mutate("item.delete", { id });
199
+ },
200
+ adjustStock(input) {
201
+ return c.mutate("item.adjustStock", input);
202
+ },
203
+ categories() {
204
+ return c.query("item.categories");
205
+ }
206
+ };
207
+ }
208
+ // ── Payment ───────────────────────────────────────────────────
209
+ get payment() {
210
+ const c = this;
211
+ return {
212
+ list(input) {
213
+ return c.query("payment.list", input);
214
+ },
215
+ getById(id) {
216
+ return c.query("payment.getById", { id });
217
+ },
218
+ create(input) {
219
+ return c.mutate("payment.create", input);
220
+ },
221
+ update(input) {
222
+ return c.mutate("payment.update", input);
223
+ },
224
+ delete(id) {
225
+ return c.mutate("payment.delete", { id });
226
+ }
227
+ };
228
+ }
229
+ // ── Expense ───────────────────────────────────────────────────
230
+ get expense() {
231
+ const c = this;
232
+ return {
233
+ list(input) {
234
+ return c.query("expense.list", input);
235
+ },
236
+ create(input) {
237
+ return c.mutate("expense.create", input);
238
+ },
239
+ update(id, data) {
240
+ return c.mutate("expense.update", { id, data });
241
+ },
242
+ delete(id) {
243
+ return c.mutate("expense.delete", { id });
244
+ },
245
+ categories() {
246
+ return c.query("expense.categories");
247
+ }
248
+ };
249
+ }
250
+ // ── Dashboard ─────────────────────────────────────────────────
251
+ get dashboard() {
252
+ const c = this;
253
+ return {
254
+ summary(input) {
255
+ return c.query("dashboard.summary", input);
256
+ }
257
+ };
258
+ }
259
+ // ── GST ───────────────────────────────────────────────────────
260
+ get gst() {
261
+ const c = this;
262
+ return {
263
+ gstr1(input) {
264
+ return c.query("gst.gstr1", input);
265
+ },
266
+ gstr3b(input) {
267
+ return c.query("gst.gstr3b", input);
268
+ },
269
+ gstr1CSV(input) {
270
+ return c.query("gst.gstr1CSV", input);
271
+ }
272
+ };
273
+ }
274
+ // ── Shipment ──────────────────────────────────────────────────
275
+ get shipment() {
276
+ const c = this;
277
+ return {
278
+ list(input) {
279
+ return c.query("shipment.list", input);
280
+ },
281
+ get(id) {
282
+ return c.query("shipment.getById", { id });
283
+ },
284
+ create(input) {
285
+ return c.mutate("shipment.create", input);
286
+ },
287
+ update(input) {
288
+ return c.mutate("shipment.update", input);
289
+ },
290
+ delete(id) {
291
+ return c.mutate("shipment.delete", { id });
292
+ }
293
+ };
294
+ }
295
+ // ── Bank Account ──────────────────────────────────────────────
296
+ get bankAccount() {
297
+ const c = this;
298
+ return {
299
+ list() {
300
+ return c.query("bankAccount.list");
301
+ },
302
+ get(id) {
303
+ return c.query("bankAccount.getById", { id });
304
+ },
305
+ create(input) {
306
+ return c.mutate("bankAccount.create", input);
307
+ },
308
+ update(id, data) {
309
+ return c.mutate("bankAccount.update", { id, data });
310
+ },
311
+ delete(id) {
312
+ return c.mutate("bankAccount.delete", { id });
313
+ },
314
+ transfer(input) {
315
+ return c.mutate("bankAccount.transfer", input);
316
+ },
317
+ listTransactions(input) {
318
+ return c.query("bankAccount.listTransactions", input);
319
+ },
320
+ summary() {
321
+ return c.query("bankAccount.summary");
322
+ }
323
+ };
324
+ }
325
+ // ── Reports ───────────────────────────────────────────────────
326
+ get reports() {
327
+ const c = this;
328
+ return {
329
+ daybook(input) {
330
+ return c.query("reports.daybook", input);
331
+ },
332
+ outstanding(input) {
333
+ return c.query("reports.outstanding", input);
334
+ },
335
+ taxSummary(input) {
336
+ return c.query("reports.taxSummary", input);
337
+ },
338
+ itemSales(input) {
339
+ return c.query("reports.itemSales", input);
340
+ },
341
+ stockSummary(input) {
342
+ return c.query("reports.stockSummary", input);
343
+ },
344
+ partyStatement(input) {
345
+ return c.query("reports.partyStatement", input);
346
+ },
347
+ paymentSummary(input) {
348
+ return c.query("reports.paymentSummary", input);
349
+ }
350
+ };
351
+ }
352
+ // ── Store ─────────────────────────────────────────────────────
353
+ get store() {
354
+ const c = this;
355
+ return {
356
+ getSettings() {
357
+ return c.query("store.getSettings");
358
+ },
359
+ updateSettings(input) {
360
+ return c.mutate("store.updateSettings", input);
361
+ },
362
+ listOrders(input) {
363
+ return c.query("store.listOrders", input);
364
+ },
365
+ getOrder(id) {
366
+ return c.query("store.getOrder", { id });
367
+ },
368
+ updateOrder(input) {
369
+ return c.mutate("store.updateOrderStatus", input);
370
+ }
371
+ };
372
+ }
373
+ // ── Target ────────────────────────────────────────────────────
374
+ get target() {
375
+ const c = this;
376
+ return {
377
+ list(input) {
378
+ return c.query("target.list", input);
379
+ },
380
+ create(input) {
381
+ return c.mutate("target.create", input);
382
+ },
383
+ getProgress(id) {
384
+ return c.query("target.getProgress", { id });
385
+ },
386
+ update(input) {
387
+ return c.mutate("target.update", input);
388
+ },
389
+ delete(id) {
390
+ return c.mutate("target.delete", { id });
391
+ },
392
+ myTargets() {
393
+ return c.query("target.myTargets");
394
+ }
395
+ };
396
+ }
397
+ // ── Import ────────────────────────────────────────────────────
398
+ get import() {
399
+ const c = this;
400
+ return {
401
+ importParties(input) {
402
+ return c.mutate("import.importParties", input);
403
+ },
404
+ importItems(input) {
405
+ return c.mutate("import.importItems", input);
406
+ },
407
+ importInvoices(input) {
408
+ return c.mutate("import.importInvoices", input);
409
+ },
410
+ importPayments(input) {
411
+ return c.mutate("import.importPayments", input);
412
+ }
413
+ };
414
+ }
415
+ };
416
+
417
+ // src/config.ts
418
+ import Conf from "conf";
419
+
420
+ // src/output.ts
421
+ import chalk from "chalk";
422
+ function isInteractive() {
423
+ return process.stdout.isTTY === true;
424
+ }
425
+ function hasColor() {
426
+ if (process.env["NO_COLOR"] !== void 0) return false;
427
+ if (process.env["FORCE_COLOR"] === "0") return false;
428
+ return process.stdout.hasColors?.() ?? isInteractive();
429
+ }
430
+ function stripAnsi(str) {
431
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
432
+ }
433
+ function getWidthTier() {
434
+ const w = process.stdout.columns ?? 80;
435
+ if (w < 80) return "narrow";
436
+ if (w <= 120) return "standard";
437
+ return "wide";
438
+ }
439
+ function termWidth() {
440
+ return process.stdout.columns ?? 80;
441
+ }
442
+ var EXIT = {
443
+ SUCCESS: 0,
444
+ GENERAL: 1,
445
+ USAGE: 2,
446
+ AUTH: 3,
447
+ FORBIDDEN: 4,
448
+ NOT_FOUND: 5,
449
+ VALIDATION: 6,
450
+ NETWORK: 7,
451
+ CONFLICT: 8
452
+ };
453
+ function fatalError(message, code = 1) {
454
+ if (hasColor()) {
455
+ process.stderr.write(chalk.red("Error: ") + message + "\n");
456
+ } else {
457
+ process.stderr.write("Error: " + message + "\n");
458
+ }
459
+ process.exit(code);
460
+ }
461
+ function success(message) {
462
+ if (hasColor()) {
463
+ process.stdout.write(chalk.green("\u2713 ") + message + "\n");
464
+ } else {
465
+ process.stdout.write("OK: " + message + "\n");
466
+ }
467
+ }
468
+ function warn(message) {
469
+ if (hasColor()) {
470
+ process.stderr.write(chalk.yellow("Warning: ") + message + "\n");
471
+ } else {
472
+ process.stderr.write("Warning: " + message + "\n");
473
+ }
474
+ }
475
+ function outputJSON(data) {
476
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
477
+ }
478
+ function getNestedValue(obj, key) {
479
+ const parts = key.split(".");
480
+ let cur = obj;
481
+ for (const part of parts) {
482
+ if (cur == null || typeof cur !== "object") return void 0;
483
+ cur = cur[part];
484
+ }
485
+ return cur;
486
+ }
487
+ function padEnd(str, len) {
488
+ const visual = stripAnsi(str).length;
489
+ const pad = Math.max(0, len - visual);
490
+ return str + " ".repeat(pad);
491
+ }
492
+ function padStart(str, len) {
493
+ const visual = stripAnsi(str).length;
494
+ const pad = Math.max(0, len - visual);
495
+ return " ".repeat(pad) + str;
496
+ }
497
+ function outputTable(rows, columns) {
498
+ if (rows.length === 0) {
499
+ process.stdout.write(" (no results)\n");
500
+ return;
501
+ }
502
+ const widths = columns.map((col) => {
503
+ let max = stripAnsi(col.header).length;
504
+ for (const row of rows) {
505
+ const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
506
+ const vis = stripAnsi(val).length;
507
+ if (vis > max) max = vis;
508
+ }
509
+ if (col.width) max = Math.min(max, col.width);
510
+ return max;
511
+ });
512
+ const sep = "\u2500".repeat(widths.reduce((s, w) => s + w + 2, 1));
513
+ let header = " ";
514
+ for (let i = 0; i < columns.length; i++) {
515
+ const col = columns[i];
516
+ const h = col.align === "right" ? padStart(col.header, widths[i]) : padEnd(col.header, widths[i]);
517
+ header += (hasColor() ? chalk.dim(h) : h) + " ";
518
+ }
519
+ process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
520
+ process.stdout.write(header.trimEnd() + "\n");
521
+ process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
522
+ for (const row of rows) {
523
+ let line = " ";
524
+ for (let i = 0; i < columns.length; i++) {
525
+ const col = columns[i];
526
+ let val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
527
+ const vis = stripAnsi(val).length;
528
+ if (col.width && vis > col.width) {
529
+ val = val.slice(0, col.width - 1) + "\u2026";
530
+ }
531
+ const cell = col.align === "right" ? padStart(val, widths[i]) : padEnd(val, widths[i]);
532
+ line += cell + " ";
533
+ }
534
+ process.stdout.write(line.trimEnd() + "\n");
535
+ }
536
+ process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
537
+ }
538
+ function outputTSV(rows, columns) {
539
+ process.stdout.write(columns.map((c) => c.header).join(" ") + "\n");
540
+ for (const row of rows) {
541
+ const line = columns.map((col) => {
542
+ const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
543
+ return stripAnsi(val).replace(/\t/g, " ");
544
+ });
545
+ process.stdout.write(line.join(" ") + "\n");
546
+ }
547
+ }
548
+ function csvEscape(val) {
549
+ if (val.includes(",") || val.includes('"') || val.includes("\n")) {
550
+ return `"${val.replace(/"/g, '""')}"`;
551
+ }
552
+ return val;
553
+ }
554
+ function outputCSV(rows, columns) {
555
+ process.stdout.write(columns.map((c) => csvEscape(c.header)).join(",") + "\n");
556
+ for (const row of rows) {
557
+ const line = columns.map((col) => {
558
+ const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
559
+ return csvEscape(stripAnsi(val));
560
+ });
561
+ process.stdout.write(line.join(",") + "\n");
562
+ }
563
+ }
564
+ function outputIds(ids) {
565
+ for (const id of ids) {
566
+ process.stdout.write(id + "\n");
567
+ }
568
+ }
569
+ function paginationFooter(page, limit, total) {
570
+ const from = (page - 1) * limit + 1;
571
+ const to = Math.min(page * limit, total);
572
+ const msg = ` Showing ${from}-${to} of ${total}`;
573
+ process.stdout.write("\n" + (hasColor() ? chalk.dim(msg) : msg) + "\n");
574
+ }
575
+
576
+ // src/config.ts
577
+ var conf = new Conf({
578
+ projectName: "hisaabo",
579
+ projectSuffix: "",
580
+ configName: "config"
581
+ });
582
+ function getConfig() {
583
+ return conf.store;
584
+ }
585
+ function setConfig(values) {
586
+ for (const [k, v] of Object.entries(values)) {
587
+ conf.set(k, v);
588
+ }
589
+ }
590
+ function clearConfig() {
591
+ conf.clear();
592
+ }
593
+ function requireAuth() {
594
+ const cfg = getConfig();
595
+ if (!cfg.token || !cfg.apiUrl || !cfg.businessId || !cfg.tenantId) {
596
+ fatalError("Not authenticated. Run: hisaabo login", 3);
597
+ }
598
+ return cfg;
599
+ }
600
+ function getConfigPath() {
601
+ return conf.path;
602
+ }
603
+
604
+ // src/auth.ts
605
+ async function loginWithToken(apiUrl, token) {
606
+ const base = apiUrl.replace(/\/$/, "");
607
+ const client = new HisaaboClient({
608
+ apiUrl: base,
609
+ token,
610
+ tenantId: "",
611
+ businessId: ""
612
+ });
613
+ let user;
614
+ try {
615
+ user = await client.auth.me();
616
+ } catch (e) {
617
+ if (e instanceof HisaaboApiError) {
618
+ const err = e.hisaaboError;
619
+ if (err.code === "unauthorized") fatalError("Invalid or expired API key.", EXIT.AUTH);
620
+ if (err.code === "network_error") fatalError("Cannot reach server: " + err.message, EXIT.NETWORK);
621
+ }
622
+ fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
623
+ return;
624
+ }
625
+ setConfig({ apiUrl: base, token });
626
+ const authedClient = new HisaaboClient({
627
+ apiUrl: base,
628
+ token,
629
+ tenantId: "",
630
+ businessId: ""
631
+ });
632
+ let businesses;
633
+ try {
634
+ businesses = await authedClient.business.list();
635
+ } catch {
636
+ businesses = [];
637
+ }
638
+ if (businesses.length === 0) {
639
+ fatalError("No businesses found for this account.", EXIT.GENERAL);
640
+ }
641
+ console.log("\n You have access to " + businesses.length + " business" + (businesses.length > 1 ? "es" : "") + ":\n");
642
+ console.log(" # Business" + " ".repeat(22) + "GSTIN" + " ".repeat(15) + "Role");
643
+ console.log(" " + "\u2500".repeat(58));
644
+ businesses.forEach((b, i) => {
645
+ const name = b.name.padEnd(26);
646
+ const gstin = (b.gstin ?? "-").padEnd(19);
647
+ console.log(` ${i + 1} ${name} ${gstin} ${b.gstRegistrationType ?? "member"}`);
648
+ });
649
+ console.log();
650
+ let selected = businesses[0];
651
+ if (businesses.length > 1) {
652
+ const readline12 = await import("readline");
653
+ const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
654
+ const answer = await new Promise((resolve2) => {
655
+ rl.question(" Select business [1]: ", resolve2);
656
+ });
657
+ rl.close();
658
+ const idx = parseInt(answer.trim() || "1", 10) - 1;
659
+ selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
660
+ }
661
+ if (!selected) {
662
+ fatalError("No business selected.", EXIT.GENERAL);
663
+ }
664
+ setConfig({
665
+ businessId: selected.id,
666
+ businessName: selected.name,
667
+ tenantId: selected.id
668
+ });
669
+ success(`Authenticated as ${user.name ?? user.email} (${user.email}) via API key`);
670
+ console.log(" Active business: " + selected.name);
671
+ console.log(" Config saved to " + getConfigPath() + "\n");
672
+ }
673
+ async function login(apiUrl, email, password) {
674
+ const base = apiUrl.replace(/\/$/, "");
675
+ const client = new HisaaboClient({
676
+ apiUrl: base,
677
+ token: "",
678
+ tenantId: "",
679
+ businessId: ""
680
+ });
681
+ try {
682
+ const result = await client.auth.login({ email, password });
683
+ const authedClient = new HisaaboClient({
684
+ apiUrl: base,
685
+ token: result.sessionId,
686
+ tenantId: "",
687
+ businessId: ""
688
+ });
689
+ const businesses = await authedClient.business.list();
690
+ if (businesses.length === 0) {
691
+ fatalError("No businesses found for this account.", EXIT.GENERAL);
692
+ }
693
+ setConfig({
694
+ apiUrl: base,
695
+ token: result.sessionId
696
+ });
697
+ console.log("\n You have access to " + businesses.length + " business" + (businesses.length > 1 ? "es" : "") + ":\n");
698
+ console.log(" # Business" + " ".repeat(22) + "GSTIN" + " ".repeat(15) + "Role");
699
+ console.log(" " + "\u2500".repeat(58));
700
+ businesses.forEach((b, i) => {
701
+ const name = b.name.padEnd(26);
702
+ const gstin = (b.gstin ?? "-").padEnd(19);
703
+ console.log(` ${i + 1} ${name} ${gstin} ${b.gstRegistrationType ?? "member"}`);
704
+ });
705
+ console.log();
706
+ let selected = businesses[0];
707
+ if (businesses.length > 1) {
708
+ const readline12 = await import("readline");
709
+ const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
710
+ const answer = await new Promise((resolve2) => {
711
+ rl.question(" Select business [1]: ", resolve2);
712
+ });
713
+ rl.close();
714
+ const idx = parseInt(answer.trim() || "1", 10) - 1;
715
+ selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
716
+ }
717
+ if (!selected) {
718
+ fatalError("No business selected.", EXIT.GENERAL);
719
+ }
720
+ setConfig({
721
+ businessId: selected.id,
722
+ businessName: selected.name,
723
+ tenantId: selected.id
724
+ // fallback; real tenantId may differ
725
+ });
726
+ success(`Active business: ${selected.name}`);
727
+ console.log(" Config saved to " + getConfigPath());
728
+ console.log("\n You can switch businesses anytime with:");
729
+ console.log(" hisaabo business switch\n");
730
+ } catch (e) {
731
+ if (e instanceof HisaaboApiError) {
732
+ const err = e.hisaaboError;
733
+ if (err.code === "unauthorized") fatalError("Invalid email or password.", EXIT.AUTH);
734
+ if (err.code === "network_error") fatalError("Cannot reach server: " + err.message, EXIT.NETWORK);
735
+ }
736
+ fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
737
+ }
738
+ }
739
+ async function logout() {
740
+ if (!getConfig().token) {
741
+ console.log("Not logged in.");
742
+ return;
743
+ }
744
+ try {
745
+ const cfg = requireAuth();
746
+ const client = new HisaaboClient(cfg);
747
+ await client.auth.logout();
748
+ } catch {
749
+ }
750
+ clearConfig();
751
+ success("Logged out.");
752
+ }
753
+ async function whoami(jsonMode) {
754
+ const cfg = requireAuth();
755
+ const client = new HisaaboClient(cfg);
756
+ try {
757
+ const user = await client.auth.me();
758
+ if (jsonMode) {
759
+ outputJSON({ user, business: { id: cfg.businessId, name: cfg.businessName }, apiUrl: cfg.apiUrl });
760
+ return;
761
+ }
762
+ console.log(` User: ${user.name} <${user.email}>`);
763
+ console.log(` Role: ${user.role}`);
764
+ console.log(` Business: ${cfg.businessName} (${cfg.businessId})`);
765
+ console.log(` API: ${cfg.apiUrl}`);
766
+ } catch (e) {
767
+ if (e instanceof HisaaboApiError) {
768
+ const err = e.hisaaboError;
769
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
770
+ fatalError(e.message, EXIT.GENERAL);
771
+ }
772
+ fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
773
+ }
774
+ }
775
+
776
+ // src/format.ts
777
+ import chalk2 from "chalk";
778
+ function formatINR(amount) {
779
+ const num = typeof amount === "string" ? parseFloat(amount) : amount;
780
+ if (isNaN(num)) return "0.00";
781
+ const abs = Math.abs(num);
782
+ const formatted = new Intl.NumberFormat("en-IN", {
783
+ minimumFractionDigits: 2,
784
+ maximumFractionDigits: 2
785
+ }).format(abs);
786
+ return (num < 0 ? "-" : "") + "\u20B9" + formatted;
787
+ }
788
+ function formatAmount(amount) {
789
+ const num = typeof amount === "string" ? parseFloat(amount) : amount;
790
+ if (isNaN(num)) return "0.00";
791
+ const abs = Math.abs(num);
792
+ const formatted = new Intl.NumberFormat("en-IN", {
793
+ minimumFractionDigits: 2,
794
+ maximumFractionDigits: 2
795
+ }).format(abs);
796
+ return (num < 0 ? "-" : "") + formatted;
797
+ }
798
+ var MONTHS = [
799
+ "Jan",
800
+ "Feb",
801
+ "Mar",
802
+ "Apr",
803
+ "May",
804
+ "Jun",
805
+ "Jul",
806
+ "Aug",
807
+ "Sep",
808
+ "Oct",
809
+ "Nov",
810
+ "Dec"
811
+ ];
812
+ function formatDate(date) {
813
+ if (!date) return "-";
814
+ try {
815
+ const d = new Date(date);
816
+ if (isNaN(d.getTime())) return date;
817
+ const day = String(d.getDate()).padStart(2, "0");
818
+ const month = MONTHS[d.getMonth()];
819
+ const year = d.getFullYear();
820
+ return `${day} ${month} ${year}`;
821
+ } catch {
822
+ return date;
823
+ }
824
+ }
825
+ function formatRelativeDate(date) {
826
+ if (!date) return "-";
827
+ try {
828
+ const d = new Date(date);
829
+ const now = /* @__PURE__ */ new Date();
830
+ const diff = Math.floor((now.getTime() - d.getTime()) / (1e3 * 60 * 60 * 24));
831
+ if (diff === 0) return "Today";
832
+ if (diff === 1) return "Yesterday";
833
+ if (diff < 30) return `${diff}d ago`;
834
+ if (diff < 365) return `${Math.floor(diff / 30)}mo ago`;
835
+ return `${Math.floor(diff / 365)}y ago`;
836
+ } catch {
837
+ return date ?? "-";
838
+ }
839
+ }
840
+ var STATUS_CONFIG = {
841
+ paid: { label: "PAID", color: (s) => chalk2.green(s) },
842
+ sent: { label: "SENT", color: (s) => chalk2.blue(s) },
843
+ draft: { label: "DRAFT", color: (s) => chalk2.dim(s) },
844
+ partial: { label: "PARTIAL", color: (s) => chalk2.yellow(s) },
845
+ overdue: { label: "OVERDUE", color: (s) => chalk2.red(s) },
846
+ cancelled: { label: "CANCEL", color: (s) => chalk2.dim(chalk2.strikethrough(s)) },
847
+ unfulfilled: { label: "UNFUL", color: (s) => chalk2.blue(s) },
848
+ pending: { label: "PEND", color: (s) => chalk2.yellow(s) },
849
+ confirmed: { label: "CONF", color: (s) => chalk2.blue(s) },
850
+ delivered: { label: "DELIV", color: (s) => chalk2.green(s) },
851
+ shipped: { label: "SHIPPED", color: (s) => chalk2.blue(s) },
852
+ in_transit: { label: "TRANSIT", color: (s) => chalk2.cyan(s) },
853
+ returned: { label: "RETURN", color: (s) => chalk2.red(s) },
854
+ preparing: { label: "PREP", color: (s) => chalk2.yellow(s) },
855
+ ready: { label: "READY", color: (s) => chalk2.cyan(s) }
856
+ };
857
+ function formatStatus(status) {
858
+ const cfg = STATUS_CONFIG[status.toLowerCase()];
859
+ const label = cfg ? `[${cfg.label}]` : `[${status.toUpperCase()}]`;
860
+ if (!hasColor() || !cfg) return label;
861
+ return cfg.color(label);
862
+ }
863
+ function currentFY() {
864
+ const now = /* @__PURE__ */ new Date();
865
+ const year = now.getFullYear();
866
+ const month = now.getMonth() + 1;
867
+ if (month >= 4) {
868
+ return `${year}-${String(year + 1).slice(2)}`;
869
+ }
870
+ return `${year - 1}-${String(year).slice(2)}`;
871
+ }
872
+ function fyStart() {
873
+ const now = /* @__PURE__ */ new Date();
874
+ const year = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
875
+ return `${year}-04-01`;
876
+ }
877
+ function todayISO() {
878
+ return (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "";
879
+ }
880
+ function monthStart() {
881
+ const now = /* @__PURE__ */ new Date();
882
+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`;
883
+ }
884
+ function monthEnd() {
885
+ const now = /* @__PURE__ */ new Date();
886
+ const last = new Date(now.getFullYear(), now.getMonth() + 1, 0);
887
+ return `${last.getFullYear()}-${String(last.getMonth() + 1).padStart(2, "0")}-${String(last.getDate()).padStart(2, "0")}`;
888
+ }
889
+ function quarterRange(q) {
890
+ const now = /* @__PURE__ */ new Date();
891
+ const fyYear = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
892
+ const ranges = {
893
+ Q1: { from: `${fyYear}-04-01`, to: `${fyYear}-06-30`, month: 4, year: fyYear },
894
+ Q2: { from: `${fyYear}-07-01`, to: `${fyYear}-09-30`, month: 7, year: fyYear },
895
+ Q3: { from: `${fyYear}-10-01`, to: `${fyYear}-12-31`, month: 10, year: fyYear },
896
+ Q4: { from: `${fyYear + 1}-01-01`, to: `${fyYear + 1}-03-31`, month: 1, year: fyYear + 1 }
897
+ };
898
+ const upper = q.toUpperCase();
899
+ return ranges[upper] ?? ranges["Q1"];
900
+ }
901
+ function deliveryMethodLabel(method) {
902
+ const map = {
903
+ self_pickup: "Self Pickup",
904
+ hand_delivery: "Hand Delivery",
905
+ courier: "Courier",
906
+ bus: "Bus",
907
+ transport: "Transport",
908
+ post: "Post"
909
+ };
910
+ return map[method] ?? method;
911
+ }
912
+
913
+ // src/commands/dashboard.ts
914
+ import chalk3 from "chalk";
915
+ function box(title, lines, width) {
916
+ const innerW = width - 2;
917
+ const titleStr = `\u2500 ${title} `;
918
+ const border = "\u250C" + titleStr + "\u2500".repeat(Math.max(1, innerW - titleStr.length)) + "\u2510";
919
+ const bottom = "\u2514" + "\u2500".repeat(innerW) + "\u2518";
920
+ const padded = lines.map((l) => {
921
+ const vis = l.length;
922
+ const pad = Math.max(0, innerW - vis - 1);
923
+ return "\u2502 " + l + " ".repeat(pad) + "\u2502";
924
+ });
925
+ return [border, ...padded, bottom];
926
+ }
927
+ function colorMoney(amount, good = true) {
928
+ if (!hasColor()) return formatAmount(amount);
929
+ const num = parseFloat(amount);
930
+ if (isNaN(num) || num === 0) return chalk3.dim(formatAmount(amount));
931
+ if (good) return chalk3.green(formatAmount(amount));
932
+ return chalk3.red(formatAmount(amount));
933
+ }
934
+ async function dashboardCommand(opts) {
935
+ const cfg = requireAuth();
936
+ const client = new HisaaboClient(cfg);
937
+ const from = fyStart();
938
+ const to = todayISO();
939
+ try {
940
+ const summary = await client.dashboard.summary({ fromDate: from, toDate: to });
941
+ if (opts.json) {
942
+ outputJSON(summary);
943
+ return;
944
+ }
945
+ const width = Math.min(termWidth() - 2, 70);
946
+ const fy = currentFY();
947
+ console.log();
948
+ console.log(` Hisaabo Dashboard` + " ".repeat(Math.max(2, width - 30)) + (cfg.businessName ?? ""));
949
+ console.log(` FY ${fy} (01 Apr ${fy.split("-")[0]} - 31 Mar 20${fy.split("-")[1]})`);
950
+ console.log(` ${"\u2550".repeat(width)}`);
951
+ console.log();
952
+ const halfW = Math.floor((width - 3) / 2);
953
+ const revLines = [
954
+ `Sales ${formatAmount(summary.totalSales).padStart(12)}`,
955
+ `Cash In ${formatAmount(summary.cashInHand).padStart(12)}`
956
+ ];
957
+ const expLines = [
958
+ `Purchases ${formatAmount(summary.totalPurchases).padStart(11)}`,
959
+ `Expenses ${formatAmount(summary.totalExpenses).padStart(11)}`
960
+ ];
961
+ const revBox = box("Revenue", revLines, halfW);
962
+ const expBox = box("Expenses", expLines, halfW);
963
+ for (let i = 0; i < Math.max(revBox.length, expBox.length); i++) {
964
+ const l = (revBox[i] ?? "").padEnd(halfW);
965
+ const r = expBox[i] ?? "";
966
+ console.log(` ${l} ${r}`);
967
+ }
968
+ console.log();
969
+ const net = parseFloat(summary.receivable) - parseFloat(summary.payable);
970
+ const netLabel = net >= 0 ? "receivable" : "payable";
971
+ const outLines = [
972
+ `Receivable ${colorMoney(summary.receivable)}`,
973
+ `Payable ${colorMoney(summary.payable, false)}`,
974
+ `Net Position ${colorMoney(String(Math.abs(net)))} ${netLabel}`
975
+ ];
976
+ const outBox = box("Outstanding", outLines, width);
977
+ outBox.forEach((l) => console.log(` ${l}`));
978
+ console.log();
979
+ const recentLines = summary.recentInvoices.slice(0, 5).map((inv) => {
980
+ const num = inv.invoiceNumber.padEnd(10);
981
+ const party2 = inv.partyName.slice(0, 16).padEnd(18);
982
+ const amt = formatAmount(inv.totalAmount).padStart(12);
983
+ const status = formatStatus(inv.status).padEnd(10);
984
+ const rel = formatRelativeDate(inv.invoiceDate).padEnd(7);
985
+ return `${num} ${party2} ${amt} ${status} ${rel}`;
986
+ });
987
+ const recentBox = box("Recent Invoices", recentLines, width);
988
+ recentBox.forEach((l) => console.log(` ${l}`));
989
+ console.log();
990
+ } catch (e) {
991
+ if (e instanceof HisaaboApiError) {
992
+ const err = e.hisaaboError;
993
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
994
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
995
+ }
996
+ fatalError(String(e instanceof Error ? e.message : e));
997
+ }
998
+ }
999
+
1000
+ // src/commands/invoice/list.ts
1001
+ async function invoiceListCommand(opts) {
1002
+ const cfg = requireAuth();
1003
+ const client = new HisaaboClient(cfg);
1004
+ let from = opts.from;
1005
+ let to = opts.to;
1006
+ if (opts.thisFy) {
1007
+ from = fyStart();
1008
+ to = todayISO();
1009
+ } else if (opts.thisMonth) {
1010
+ from = monthStart();
1011
+ to = monthEnd();
1012
+ } else if (opts.thisQuarter) {
1013
+ const now = /* @__PURE__ */ new Date();
1014
+ const month = now.getMonth() + 1;
1015
+ const year = now.getFullYear();
1016
+ if (month >= 4 && month <= 6) {
1017
+ from = `${year}-04-01`;
1018
+ to = `${year}-06-30`;
1019
+ } else if (month >= 7 && month <= 9) {
1020
+ from = `${year}-07-01`;
1021
+ to = `${year}-09-30`;
1022
+ } else if (month >= 10 && month <= 12) {
1023
+ from = `${year}-10-01`;
1024
+ to = `${year}-12-31`;
1025
+ } else {
1026
+ from = `${year}-01-01`;
1027
+ to = `${year}-03-31`;
1028
+ }
1029
+ }
1030
+ const page = opts.page ?? 1;
1031
+ const limit = opts.limit ?? 20;
1032
+ try {
1033
+ const result = await client.invoice.list({
1034
+ type: opts.type ?? null,
1035
+ status: opts.status ?? null,
1036
+ partyId: opts.partyId ?? null,
1037
+ fromDate: from ?? null,
1038
+ toDate: to ?? null,
1039
+ search: opts.search ?? null,
1040
+ sortBy: opts.sortBy ?? null,
1041
+ sortDir: opts.sortDir ?? null,
1042
+ page,
1043
+ limit
1044
+ });
1045
+ if (opts.json) {
1046
+ outputJSON({
1047
+ data: result.data,
1048
+ pagination: { page: result.page, limit: result.limit, total: result.total, hasMore: result.page * result.limit < result.total }
1049
+ });
1050
+ return;
1051
+ }
1052
+ const tier = getWidthTier();
1053
+ const typeLabel = opts.type === "purchase" ? "Purchase Bills" : "Sale Invoices";
1054
+ console.log(`
1055
+ ${typeLabel}` + " ".repeat(40) + `FY ${currentFY()}`);
1056
+ console.log(` ${"\u2550".repeat(68)}
1057
+ `);
1058
+ const narrowCols = [
1059
+ { key: "invoiceNumber", header: "#", width: 10 },
1060
+ { key: "partyName", header: "Party", width: 18 },
1061
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
1062
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
1063
+ ];
1064
+ const standardCols = [
1065
+ { key: "invoiceNumber", header: "#", width: 10 },
1066
+ { key: "partyName", header: "Party", width: 18 },
1067
+ { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
1068
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1069
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
1070
+ ];
1071
+ const wideCols = [
1072
+ { key: "invoiceNumber", header: "#", width: 10 },
1073
+ { key: "partyName", header: "Party", width: 18 },
1074
+ { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
1075
+ { key: "dueDate", header: "Due", width: 12, format: (v) => formatDate(v ? String(v) : null) },
1076
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1077
+ { key: "amountPaid", header: "Paid (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
1078
+ { key: "balanceDue", header: "Balance (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
1079
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
1080
+ ];
1081
+ const cols = tier === "narrow" ? narrowCols : tier === "wide" ? wideCols : standardCols;
1082
+ if (opts.format === "tsv") {
1083
+ outputTSV(result.data, cols);
1084
+ } else if (opts.format === "csv") {
1085
+ outputCSV(result.data, cols);
1086
+ } else if (opts.format === "ids") {
1087
+ outputIds(result.data.map((r) => r.id));
1088
+ } else {
1089
+ outputTable(result.data, cols);
1090
+ paginationFooter(result.page, result.limit, result.total);
1091
+ }
1092
+ } catch (e) {
1093
+ if (e instanceof HisaaboApiError) {
1094
+ const err = e.hisaaboError;
1095
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1096
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1097
+ }
1098
+ fatalError(String(e instanceof Error ? e.message : e));
1099
+ }
1100
+ }
1101
+
1102
+ // src/commands/invoice/get.ts
1103
+ import chalk4 from "chalk";
1104
+ async function invoiceGetCommand(id, opts) {
1105
+ const cfg = requireAuth();
1106
+ const client = new HisaaboClient(cfg);
1107
+ try {
1108
+ let line2 = function(left, right) {
1109
+ if (right !== void 0) {
1110
+ const pad = Math.max(1, inner - left.length - right.length - 2);
1111
+ process.stdout.write(`\u2502 ${left}${" ".repeat(pad)}${right} \u2502
1112
+ `);
1113
+ } else {
1114
+ const vis = left.length;
1115
+ const pad = Math.max(0, inner - vis);
1116
+ process.stdout.write(`\u2502 ${left}${" ".repeat(pad)} \u2502
1117
+ `);
1118
+ }
1119
+ }, divider2 = function() {
1120
+ process.stdout.write(`\u251C${"\u2500".repeat(inner + 2)}\u2524
1121
+ `);
1122
+ };
1123
+ var line = line2, divider = divider2;
1124
+ const inv = await client.invoice.get(id);
1125
+ if (opts.json) {
1126
+ outputJSON(inv);
1127
+ return;
1128
+ }
1129
+ const w = Math.min(termWidth() - 2, 68);
1130
+ const inner = w - 2;
1131
+ const title = `SALE INVOICE ${inv.invoiceNumber}`;
1132
+ const statusBadge = formatStatus(inv.status);
1133
+ const topPad = Math.max(1, inner - title.length - statusBadge.replace(/\x1b\[[0-9;]*m/g, "").length);
1134
+ process.stdout.write(`
1135
+ \u250C${"\u2500".repeat(inner + 2)}\u2510
1136
+ `);
1137
+ process.stdout.write(`\u2502 ${hasColor() ? chalk4.bold(title) : title}${" ".repeat(topPad)}${statusBadge} \u2502
1138
+ `);
1139
+ divider2();
1140
+ line2(`Party: ${inv.partyName}`);
1141
+ line2(`Date: ${formatDate(inv.invoiceDate)}`);
1142
+ if (inv.dueDate) line2(`Due: ${formatDate(inv.dueDate)}`);
1143
+ if (inv.createdByName) line2(`Created: ${inv.createdByName}${inv.createdAt ? ` (${formatDate(inv.createdAt)})` : ""}`);
1144
+ if (inv.deliveryMethod) line2(`Delivery: ${deliveryMethodLabel(inv.deliveryMethod)}`);
1145
+ divider2();
1146
+ process.stdout.write(`\u2502 \u2502
1147
+ `);
1148
+ process.stdout.write(`\u2502 # ${"Item".padEnd(18)} ${"Qty".padStart(5)} ${"Rate (\u20B9)".padStart(10)} ${"Tax%".padStart(5)} ${"Amount (\u20B9)".padStart(12)} \u2502
1149
+ `);
1150
+ process.stdout.write(`\u2502 ${"\u2500\u2500".padEnd(2)} ${"\u2500".repeat(18)} ${"\u2500".repeat(5)} ${"\u2500".repeat(10)} ${"\u2500".repeat(5)} ${"\u2500".repeat(12)} \u2502
1151
+ `);
1152
+ inv.lineItems.forEach((item2, i) => {
1153
+ const idx = String(i + 1).padStart(2);
1154
+ const desc = item2.description.slice(0, 18).padEnd(18);
1155
+ const qty = item2.quantity.padStart(5);
1156
+ const rate = formatAmount(item2.unitPrice).padStart(10);
1157
+ const tax = `${item2.taxPercent}%`.padStart(5);
1158
+ const amt = formatAmount(item2.amount).padStart(12);
1159
+ process.stdout.write(`\u2502 ${idx} ${desc} ${qty} ${rate} ${tax} ${amt} \u2502
1160
+ `);
1161
+ });
1162
+ process.stdout.write(`\u2502 \u2502
1163
+ `);
1164
+ divider2();
1165
+ const subtotal = inv.lineItems.reduce((s, i) => s + parseFloat(i.amount), 0);
1166
+ const _tax = parseFloat(inv.totalAmount) - subtotal - parseFloat(inv.roundOff ?? "0") + parseFloat(inv.invoiceDiscount ?? "0");
1167
+ line2(`Subtotal:`, formatAmount(String(subtotal)).padStart(16));
1168
+ if (parseFloat(inv.invoiceDiscount ?? "0") !== 0)
1169
+ line2(`Discount:`, ("-" + formatAmount(inv.invoiceDiscount)).padStart(16));
1170
+ if (inv.charges && inv.charges.length > 0) {
1171
+ inv.charges.forEach((c) => line2(`${c.label}:`, formatAmount(c.amount).padStart(16)));
1172
+ }
1173
+ if (parseFloat(inv.roundOff ?? "0") !== 0)
1174
+ line2(`Round Off:`, formatAmount(inv.roundOff).padStart(16));
1175
+ process.stdout.write(`\u2502 ${"\u2500".repeat(inner - 2)} \u2502
1176
+ `);
1177
+ line2(`Total:`, (hasColor() ? chalk4.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
1178
+ line2(`Paid:`, formatAmount(inv.amountPaid).padStart(16));
1179
+ line2(`Balance:`, formatAmount(inv.balanceDue).padStart(16));
1180
+ if (inv.notes || inv.termsAndConditions) {
1181
+ divider2();
1182
+ if (inv.notes) line2(`Notes: ${inv.notes}`);
1183
+ if (inv.termsAndConditions) line2(`Terms: ${inv.termsAndConditions}`);
1184
+ }
1185
+ process.stdout.write(` \u2514${"\u2500".repeat(inner + 2)}\u2518
1186
+
1187
+ `);
1188
+ process.stdout.write(` Actions: [e] Edit [p] PDF [d] Delete [pay] Record Payment
1189
+
1190
+ `);
1191
+ } catch (e) {
1192
+ if (e instanceof HisaaboApiError) {
1193
+ const err = e.hisaaboError;
1194
+ if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
1195
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1196
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1197
+ }
1198
+ fatalError(String(e instanceof Error ? e.message : e));
1199
+ }
1200
+ }
1201
+
1202
+ // src/commands/invoice/create.ts
1203
+ import * as readline from "readline";
1204
+ async function prompt(rl, question) {
1205
+ return new Promise((resolve2) => rl.question(question, resolve2));
1206
+ }
1207
+ async function invoiceCreateCommand(opts) {
1208
+ const cfg = requireAuth();
1209
+ const client = new HisaaboClient(cfg);
1210
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
1211
+ try {
1212
+ let invoiceType = "sale";
1213
+ if (opts.type === "purchase") invoiceType = "purchase";
1214
+ let partyId = opts.partyId;
1215
+ let partyName = opts.party ?? "";
1216
+ if (!partyId) {
1217
+ if (!isNonInteractive) {
1218
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1219
+ console.log(`
1220
+ New ${invoiceType === "sale" ? "Sale Invoice" : "Purchase Bill"}`);
1221
+ console.log(" " + "\u2500".repeat(40) + "\n");
1222
+ const search = await prompt(rl, " Select Party:\n > Search: ");
1223
+ const parties = await client.party.list({ search: search.trim(), limit: 5 });
1224
+ if (parties.data.length === 0) {
1225
+ rl.close();
1226
+ fatalError("No parties found. Create one with: hisaabo party create", EXIT.NOT_FOUND);
1227
+ }
1228
+ parties.data.forEach((p, i) => {
1229
+ console.log(` ${i + 1} ${p.name.padEnd(20)} ${(p.phone ?? "").padEnd(14)} ${p.type}`);
1230
+ });
1231
+ const partyChoice = await prompt(rl, "\n Party [1]: ");
1232
+ const idx = parseInt(partyChoice.trim() || "1", 10) - 1;
1233
+ const selected = parties.data[Math.max(0, Math.min(idx, parties.data.length - 1))];
1234
+ if (!selected) {
1235
+ rl.close();
1236
+ fatalError("Invalid selection.", EXIT.USAGE);
1237
+ }
1238
+ partyId = selected.id;
1239
+ partyName = selected.name;
1240
+ console.log(` Party: ${partyName}
1241
+ `);
1242
+ rl.close();
1243
+ } else {
1244
+ if (!partyName) fatalError("--party or --party-id is required", EXIT.USAGE);
1245
+ const parties = await client.party.list({ search: partyName, limit: 5 });
1246
+ if (parties.data.length === 0) fatalError(`Party not found: ${partyName}`, EXIT.NOT_FOUND);
1247
+ partyId = parties.data[0].id;
1248
+ partyName = parties.data[0].name;
1249
+ }
1250
+ }
1251
+ const lineItems = [];
1252
+ if (opts.items && opts.items.length > 0) {
1253
+ for (let i = 0; i < opts.items.length; i++) {
1254
+ const itemName = opts.items[i];
1255
+ const qty = opts.qty?.[i] ?? "1";
1256
+ let unitPrice = opts.rate?.[i] ?? "";
1257
+ if (!unitPrice) {
1258
+ const items = await client.item.list({ search: itemName, limit: 3 });
1259
+ if (items.data.length > 0 && items.data[0]?.salePrice) {
1260
+ unitPrice = items.data[0].salePrice;
1261
+ lineItems.push({
1262
+ itemId: items.data[0].id,
1263
+ description: items.data[0].name,
1264
+ quantity: qty,
1265
+ unitPrice,
1266
+ taxPercent: items.data[0].taxPercent
1267
+ });
1268
+ } else {
1269
+ fatalError(`Item not found or has no price: ${itemName}. Use --rate to specify price.`, EXIT.NOT_FOUND);
1270
+ }
1271
+ } else {
1272
+ const items = await client.item.list({ search: itemName, limit: 3 });
1273
+ const matched = items.data.find((it) => it.name.toLowerCase().includes(itemName.toLowerCase()));
1274
+ if (matched) {
1275
+ lineItems.push({
1276
+ itemId: matched.id,
1277
+ description: matched.name,
1278
+ quantity: qty,
1279
+ unitPrice,
1280
+ taxPercent: matched.taxPercent
1281
+ });
1282
+ } else {
1283
+ lineItems.push({ description: itemName, quantity: qty, unitPrice });
1284
+ }
1285
+ }
1286
+ }
1287
+ } else if (!isNonInteractive) {
1288
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1289
+ console.log(" Add Line Items (empty description to finish):\n");
1290
+ let itemNum = 1;
1291
+ while (true) {
1292
+ console.log(` Item ${itemNum}:`);
1293
+ const search = await prompt(rl, " Search item (or description): ");
1294
+ if (!search.trim()) break;
1295
+ let description = search.trim();
1296
+ let itemId;
1297
+ let defaultPrice = "";
1298
+ let defaultTax = "0";
1299
+ const items = await client.item.list({ search: search.trim(), limit: 5 });
1300
+ if (items.data.length > 0) {
1301
+ items.data.forEach((it, i) => {
1302
+ const stock = it.itemType === "service" ? "-" : String(it.stockQuantity);
1303
+ const price = it.salePrice ? formatINR(it.salePrice) : "no price";
1304
+ console.log(` ${i + 1} ${it.name.padEnd(20)} ${price.padEnd(12)} Stock: ${stock}`);
1305
+ });
1306
+ const choice = await prompt(rl, " Item [1] (or 0 to use as description): ");
1307
+ const idx = parseInt(choice.trim() || "1", 10);
1308
+ if (idx > 0) {
1309
+ const selected = items.data[idx - 1];
1310
+ if (selected) {
1311
+ itemId = selected.id;
1312
+ description = selected.name;
1313
+ defaultPrice = selected.salePrice ?? "";
1314
+ defaultTax = selected.taxPercent;
1315
+ }
1316
+ }
1317
+ }
1318
+ const qtyStr = await prompt(rl, " Quantity [1]: ");
1319
+ const qty = qtyStr.trim() || "1";
1320
+ const rateStr = await prompt(rl, ` Unit Price [${defaultPrice || "0.00"}]: `);
1321
+ const unitPrice = rateStr.trim() || defaultPrice || "0.00";
1322
+ const taxStr = await prompt(rl, ` Tax % [${defaultTax}]: `);
1323
+ const taxPercent = taxStr.trim() || defaultTax;
1324
+ const discStr = await prompt(rl, " Discount % [0]: ");
1325
+ const discountPercent = discStr.trim() || "0";
1326
+ const amount = parseFloat(qty) * parseFloat(unitPrice) * (1 + parseFloat(taxPercent) / 100) * (1 - parseFloat(discountPercent) / 100);
1327
+ console.log(` > ${description} x${qty} @${formatAmount(unitPrice)} ${taxPercent}% tax = ${formatAmount(String(amount))}
1328
+ `);
1329
+ lineItems.push({ itemId, description, quantity: qty, unitPrice, taxPercent, discountPercent });
1330
+ itemNum++;
1331
+ }
1332
+ rl.close();
1333
+ if (lineItems.length === 0) {
1334
+ fatalError("No line items added.", EXIT.USAGE);
1335
+ }
1336
+ } else {
1337
+ fatalError("No items specified. Use --item flags.", EXIT.USAGE);
1338
+ }
1339
+ const subtotal = lineItems.reduce((s, item2) => {
1340
+ const amt = parseFloat(item2.quantity) * parseFloat(item2.unitPrice);
1341
+ return s + amt;
1342
+ }, 0);
1343
+ const taxTotal = lineItems.reduce((s, item2) => {
1344
+ const amt = parseFloat(item2.quantity) * parseFloat(item2.unitPrice);
1345
+ const tax = parseFloat(item2.taxPercent ?? "0") / 100;
1346
+ return s + amt * tax;
1347
+ }, 0);
1348
+ let invoiceDate = todayISO();
1349
+ let dueDate;
1350
+ let deliveryMethod = opts.delivery;
1351
+ let notes = opts.notes;
1352
+ let terms = opts.terms;
1353
+ if (!isNonInteractive) {
1354
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1355
+ console.log("\n \u2500\u2500\u2500 Invoice Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
1356
+ console.log(` Subtotal: ${formatAmount(String(subtotal))}`);
1357
+ console.log(` Tax: ${formatAmount(String(taxTotal))}`);
1358
+ console.log(` Total: ${formatAmount(String(subtotal + taxTotal))}`);
1359
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n");
1360
+ const dateStr = await prompt(rl, ` Invoice Date [${todayISO()}]: `);
1361
+ if (dateStr.trim()) invoiceDate = dateStr.trim();
1362
+ const dueStr = await prompt(rl, " Due Date [optional]: ");
1363
+ if (dueStr.trim()) dueDate = dueStr.trim();
1364
+ const delivStr = await prompt(rl, " Delivery Method [self_pickup]: ");
1365
+ deliveryMethod = delivStr.trim() || "self_pickup";
1366
+ const notesStr = await prompt(rl, " Notes: ");
1367
+ if (notesStr.trim()) notes = notesStr.trim();
1368
+ const termsStr = await prompt(rl, " Terms: ");
1369
+ if (termsStr.trim()) terms = termsStr.trim();
1370
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
1371
+ const confirm = await prompt(rl, "\n Create this invoice? (y/n) [y]: ");
1372
+ rl.close();
1373
+ if (confirm.trim().toLowerCase() === "n") {
1374
+ console.log(" Cancelled.");
1375
+ process.exit(EXIT.SUCCESS);
1376
+ }
1377
+ }
1378
+ const invoice2 = await client.invoice.create({
1379
+ partyId,
1380
+ type: invoiceType,
1381
+ invoiceDate,
1382
+ dueDate,
1383
+ deliveryMethod,
1384
+ notes,
1385
+ termsAndConditions: terms,
1386
+ lineItems
1387
+ });
1388
+ if (opts.json) {
1389
+ outputJSON(invoice2);
1390
+ return;
1391
+ }
1392
+ success(`Created: ${invoice2.invoiceNumber} for ${formatINR(invoice2.totalAmount)}`);
1393
+ console.log(` View: hisaabo invoice get ${invoice2.invoiceNumber}`);
1394
+ console.log(` PDF: hisaabo invoice pdf ${invoice2.invoiceNumber}
1395
+ `);
1396
+ } catch (e) {
1397
+ if (e instanceof HisaaboApiError) {
1398
+ const err = e.hisaaboError;
1399
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1400
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1401
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1402
+ }
1403
+ fatalError(String(e instanceof Error ? e.message : e));
1404
+ }
1405
+ }
1406
+
1407
+ // src/commands/invoice/status.ts
1408
+ var VALID_STATUSES = ["draft", "unfulfilled", "sent", "paid", "partial", "overdue", "cancelled"];
1409
+ async function invoiceStatusCommand(id, status, opts) {
1410
+ const cfg = requireAuth();
1411
+ const client = new HisaaboClient(cfg);
1412
+ if (!VALID_STATUSES.includes(status)) {
1413
+ fatalError(`Invalid status: ${status}. Valid: ${VALID_STATUSES.join(", ")}`, EXIT.USAGE);
1414
+ }
1415
+ try {
1416
+ const before = await client.invoice.get(id);
1417
+ const updated = await client.invoice.updateStatus(id, status);
1418
+ if (opts.json) {
1419
+ outputJSON(updated);
1420
+ return;
1421
+ }
1422
+ const fromBadge = formatStatus(before.status);
1423
+ const toBadge = formatStatus(status);
1424
+ console.log(` ${id} status updated: ${fromBadge} -> ${toBadge}`);
1425
+ } catch (e) {
1426
+ if (e instanceof HisaaboApiError) {
1427
+ const err = e.hisaaboError;
1428
+ if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
1429
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1430
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
1431
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1432
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1433
+ }
1434
+ fatalError(String(e instanceof Error ? e.message : e));
1435
+ }
1436
+ }
1437
+
1438
+ // src/commands/invoice/pdf.ts
1439
+ import * as fs from "fs";
1440
+ import * as path from "path";
1441
+ async function invoicePdfCommand(id, opts) {
1442
+ const cfg = requireAuth();
1443
+ const client = new HisaaboClient(cfg);
1444
+ let invoiceNumber = id;
1445
+ try {
1446
+ const inv = await client.invoice.get(id);
1447
+ invoiceNumber = inv.invoiceNumber;
1448
+ } catch {
1449
+ }
1450
+ const pdfUrl = `${cfg.apiUrl}/api/invoice/${id}/pdf`;
1451
+ try {
1452
+ const res = await fetch(pdfUrl, {
1453
+ headers: {
1454
+ "Authorization": `Bearer ${cfg.token}`,
1455
+ "x-business-id": cfg.businessId,
1456
+ "x-tenant-id": cfg.tenantId,
1457
+ "x-client-type": "cli"
1458
+ }
1459
+ });
1460
+ if (!res.ok) {
1461
+ fatalError(`Failed to download PDF: HTTP ${res.status}`, EXIT.GENERAL);
1462
+ }
1463
+ const buffer = await res.arrayBuffer();
1464
+ const bytes = Buffer.from(buffer);
1465
+ let outputPath;
1466
+ if (opts.output) {
1467
+ if (fs.existsSync(opts.output) && fs.statSync(opts.output).isDirectory()) {
1468
+ outputPath = path.join(opts.output, `${invoiceNumber}.pdf`);
1469
+ } else {
1470
+ outputPath = opts.output;
1471
+ }
1472
+ } else {
1473
+ outputPath = `${invoiceNumber}.pdf`;
1474
+ }
1475
+ fs.writeFileSync(outputPath, bytes);
1476
+ success(`Saved: ${outputPath} (${Math.round(bytes.length / 1024)} KB)`);
1477
+ if (opts.open) {
1478
+ const openPkg = await import("open");
1479
+ await openPkg.default(outputPath);
1480
+ }
1481
+ } catch (e) {
1482
+ if (e instanceof HisaaboApiError) {
1483
+ const err = e.hisaaboError;
1484
+ if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
1485
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1486
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1487
+ }
1488
+ fatalError(String(e instanceof Error ? e.message : e));
1489
+ }
1490
+ }
1491
+
1492
+ // src/commands/invoice/delete.ts
1493
+ import * as readline2 from "readline";
1494
+ async function invoiceDeleteCommand(id, opts) {
1495
+ const cfg = requireAuth();
1496
+ const client = new HisaaboClient(cfg);
1497
+ try {
1498
+ const inv = await client.invoice.get(id);
1499
+ if (!opts.yes && process.stdin.isTTY) {
1500
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1501
+ const answer = await new Promise((resolve2) => {
1502
+ rl.question(` Delete ${inv.invoiceNumber} (${inv.partyName}, ${inv.totalAmount})? (y/N): `, resolve2);
1503
+ });
1504
+ rl.close();
1505
+ if (answer.trim().toLowerCase() !== "y") {
1506
+ console.log(" Cancelled.");
1507
+ process.exit(0);
1508
+ }
1509
+ }
1510
+ const result = await client.invoice.delete(id);
1511
+ if (opts.json) {
1512
+ outputJSON(result);
1513
+ return;
1514
+ }
1515
+ success(`Deleted: ${inv.invoiceNumber}`);
1516
+ } catch (e) {
1517
+ if (e instanceof HisaaboApiError) {
1518
+ const err = e.hisaaboError;
1519
+ if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
1520
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1521
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
1522
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1523
+ }
1524
+ fatalError(String(e instanceof Error ? e.message : e));
1525
+ }
1526
+ }
1527
+
1528
+ // src/commands/party/list.ts
1529
+ async function partyListCommand(opts) {
1530
+ const cfg = requireAuth();
1531
+ const client = new HisaaboClient(cfg);
1532
+ const page = opts.page ?? 1;
1533
+ const limit = opts.limit ?? 20;
1534
+ try {
1535
+ const result = await client.party.list({
1536
+ type: opts.type ?? null,
1537
+ search: opts.search ?? null,
1538
+ category: opts.category ?? null,
1539
+ page,
1540
+ limit
1541
+ });
1542
+ if (opts.json) {
1543
+ outputJSON({
1544
+ data: result.data,
1545
+ pagination: { page: result.page, limit: result.limit, total: result.total }
1546
+ });
1547
+ return;
1548
+ }
1549
+ const typeLabel = opts.type === "supplier" ? "Suppliers" : opts.type === "customer" ? "Customers" : "Parties";
1550
+ console.log(`
1551
+ ${typeLabel}` + " ".repeat(40) + `${result.total} total
1552
+ `);
1553
+ const cols = [
1554
+ { key: "name", header: "Name", width: 22 },
1555
+ { key: "phone", header: "Phone", width: 16, format: (v) => String(v ?? "-") },
1556
+ { key: "balance", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1557
+ { key: "gstin", header: "GSTIN", width: 16, format: (v) => String(v ?? "-") },
1558
+ { key: "category", header: "Category", width: 14, format: (v) => String(v ?? "-") }
1559
+ ];
1560
+ if (opts.format === "tsv") outputTSV(result.data, cols);
1561
+ else if (opts.format === "csv") outputCSV(result.data, cols);
1562
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
1563
+ else {
1564
+ outputTable(result.data, cols);
1565
+ paginationFooter(result.page, result.limit, result.total);
1566
+ }
1567
+ } catch (e) {
1568
+ if (e instanceof HisaaboApiError) {
1569
+ const err = e.hisaaboError;
1570
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1571
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1572
+ }
1573
+ fatalError(String(e instanceof Error ? e.message : e));
1574
+ }
1575
+ }
1576
+
1577
+ // src/commands/party/get.ts
1578
+ async function partyGetCommand(id, opts) {
1579
+ const cfg = requireAuth();
1580
+ const client = new HisaaboClient(cfg);
1581
+ try {
1582
+ const party2 = await client.party.get(id);
1583
+ if (opts.json) {
1584
+ outputJSON(party2);
1585
+ return;
1586
+ }
1587
+ console.log(`
1588
+ ${party2.name} (${party2.type.toUpperCase()})`);
1589
+ console.log(" " + "\u2500".repeat(50));
1590
+ if (party2.phone) console.log(` Phone: ${party2.phone}`);
1591
+ if (party2.email) console.log(` Email: ${party2.email}`);
1592
+ if (party2.gstin) console.log(` GSTIN: ${party2.gstin}`);
1593
+ if (party2.pan) console.log(` PAN: ${party2.pan}`);
1594
+ if (party2.billingAddress) console.log(` Address: ${party2.billingAddress}`);
1595
+ if (party2.city) console.log(` City: ${party2.city}`);
1596
+ if (party2.state) console.log(` State: ${party2.state}`);
1597
+ if (party2.category) console.log(` Category: ${party2.category}`);
1598
+ if (party2.creditPeriodDays) console.log(` Credit Period: ${party2.creditPeriodDays} days`);
1599
+ if (party2.creditLimit && parseFloat(party2.creditLimit) > 0) console.log(` Credit Limit: ${formatINR(party2.creditLimit)}`);
1600
+ console.log(` Balance: ${formatINR(party2.balance)}`);
1601
+ console.log();
1602
+ } catch (e) {
1603
+ if (e instanceof HisaaboApiError) {
1604
+ const err = e.hisaaboError;
1605
+ if (err.code === "not_found") fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1606
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1607
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1608
+ }
1609
+ fatalError(String(e instanceof Error ? e.message : e));
1610
+ }
1611
+ }
1612
+
1613
+ // src/commands/party/create.ts
1614
+ import * as readline3 from "readline";
1615
+ async function prompt2(rl, q) {
1616
+ return new Promise((resolve2) => rl.question(q, resolve2));
1617
+ }
1618
+ async function partyCreateCommand(opts) {
1619
+ const cfg = requireAuth();
1620
+ const client = new HisaaboClient(cfg);
1621
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
1622
+ let type = opts.type;
1623
+ let name = opts.name;
1624
+ let phone = opts.phone;
1625
+ let email = opts.email;
1626
+ let gstin = opts.gstin;
1627
+ let city = opts.city;
1628
+ let category = opts.category;
1629
+ if (!isNonInteractive) {
1630
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1631
+ console.log("\n New Party\n " + "\u2500".repeat(30) + "\n");
1632
+ if (!type) {
1633
+ const t = await prompt2(rl, " Type (customer/supplier) [customer]: ");
1634
+ type = t.trim() || "customer";
1635
+ }
1636
+ if (!name) {
1637
+ name = (await prompt2(rl, " Name: ")).trim();
1638
+ }
1639
+ if (!phone) {
1640
+ const p = await prompt2(rl, " Phone: ");
1641
+ phone = p.trim() || void 0;
1642
+ }
1643
+ if (!email) {
1644
+ const e = await prompt2(rl, " Email: ");
1645
+ email = e.trim() || void 0;
1646
+ }
1647
+ if (!gstin) {
1648
+ const g = await prompt2(rl, " GSTIN: ");
1649
+ gstin = g.trim() || void 0;
1650
+ }
1651
+ if (!city) {
1652
+ const c = await prompt2(rl, " City: ");
1653
+ city = c.trim() || void 0;
1654
+ }
1655
+ rl.close();
1656
+ }
1657
+ if (!name) fatalError("--name is required", EXIT.USAGE);
1658
+ if (!type) type = "customer";
1659
+ try {
1660
+ const party2 = await client.party.create({ type, name, phone, email, gstin, city, category });
1661
+ if (opts.json) {
1662
+ outputJSON(party2);
1663
+ return;
1664
+ }
1665
+ success(`Created: ${party2.name} (${party2.type})`);
1666
+ console.log(` ID: ${party2.id}
1667
+ `);
1668
+ } catch (e) {
1669
+ if (e instanceof HisaaboApiError) {
1670
+ const err = e.hisaaboError;
1671
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1672
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1673
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1674
+ }
1675
+ fatalError(String(e instanceof Error ? e.message : e));
1676
+ }
1677
+ }
1678
+
1679
+ // src/commands/party/delete.ts
1680
+ import * as readline4 from "readline";
1681
+ async function partyDeleteCommand(id, opts) {
1682
+ const cfg = requireAuth();
1683
+ const client = new HisaaboClient(cfg);
1684
+ try {
1685
+ const party2 = await client.party.get(id);
1686
+ if (!opts.yes && process.stdin.isTTY) {
1687
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1688
+ const answer = await new Promise((resolve2) => {
1689
+ rl.question(` Delete ${party2.name}? (y/N): `, resolve2);
1690
+ });
1691
+ rl.close();
1692
+ if (answer.trim().toLowerCase() !== "y") {
1693
+ console.log(" Cancelled.");
1694
+ process.exit(0);
1695
+ }
1696
+ }
1697
+ const result = await client.party.delete(id);
1698
+ if (opts.json) {
1699
+ outputJSON(result);
1700
+ return;
1701
+ }
1702
+ success(`Deleted: ${party2.name}`);
1703
+ } catch (e) {
1704
+ if (e instanceof HisaaboApiError) {
1705
+ const err = e.hisaaboError;
1706
+ if (err.code === "not_found") fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1707
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1708
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
1709
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1710
+ }
1711
+ fatalError(String(e instanceof Error ? e.message : e));
1712
+ }
1713
+ }
1714
+
1715
+ // src/commands/party/ledger.ts
1716
+ async function partyLedgerCommand(partyId, opts) {
1717
+ const cfg = requireAuth();
1718
+ const client = new HisaaboClient(cfg);
1719
+ try {
1720
+ const result = await client.party.ledger(partyId, {
1721
+ fromDate: opts.from,
1722
+ toDate: opts.to,
1723
+ page: opts.page ?? 1,
1724
+ limit: opts.limit ?? 50
1725
+ });
1726
+ if (opts.json) {
1727
+ outputJSON(result);
1728
+ return;
1729
+ }
1730
+ console.log(`
1731
+ Ledger: ${result.partyName} (${result.partyType})`);
1732
+ console.log(" " + "\u2550".repeat(60));
1733
+ console.log(` Opening Balance: ${formatINR(result.openingBalance)}
1734
+ `);
1735
+ const cols = [
1736
+ { key: "date", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
1737
+ { key: "description", header: "Description", width: 25 },
1738
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1739
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1740
+ { key: "balance", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1741
+ { key: "referenceType", header: "Type", width: 10 }
1742
+ ];
1743
+ if (opts.format === "tsv") outputTSV(result.entries, cols);
1744
+ else if (opts.format === "csv") outputCSV(result.entries, cols);
1745
+ else outputTable(result.entries, cols);
1746
+ console.log(`
1747
+ Closing Balance: ${formatINR(result.closingBalance)}
1748
+ `);
1749
+ } catch (e) {
1750
+ if (e instanceof HisaaboApiError) {
1751
+ const err = e.hisaaboError;
1752
+ if (err.code === "not_found") fatalError(`Party not found: ${partyId}`, EXIT.NOT_FOUND);
1753
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1754
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1755
+ }
1756
+ fatalError(String(e instanceof Error ? e.message : e));
1757
+ }
1758
+ }
1759
+
1760
+ // src/commands/item/list.ts
1761
+ import chalk5 from "chalk";
1762
+ async function itemListCommand(opts) {
1763
+ const cfg = requireAuth();
1764
+ const client = new HisaaboClient(cfg);
1765
+ const page = opts.page ?? 1;
1766
+ const limit = opts.limit ?? 20;
1767
+ try {
1768
+ const result = await client.item.list({
1769
+ search: opts.search ?? null,
1770
+ category: opts.category ?? null,
1771
+ itemType: opts.type ?? null,
1772
+ lowStock: opts.lowStock ?? null,
1773
+ page,
1774
+ limit
1775
+ });
1776
+ if (opts.json) {
1777
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
1778
+ return;
1779
+ }
1780
+ console.log(`
1781
+ Items` + " ".repeat(45) + `${result.total} total
1782
+ `);
1783
+ const cols = [
1784
+ { key: "name", header: "Name", width: 22 },
1785
+ { key: "unit", header: "Unit", width: 6 },
1786
+ {
1787
+ key: "salePrice",
1788
+ header: "Sale (\u20B9)",
1789
+ align: "right",
1790
+ width: 12,
1791
+ format: (v) => v ? formatAmount(String(v)) : "-"
1792
+ },
1793
+ {
1794
+ key: "stockQuantity",
1795
+ header: "Stock",
1796
+ width: 8,
1797
+ format: (v, row) => {
1798
+ const qty = String(v ?? "0");
1799
+ const low = row.lowStockAlert;
1800
+ const isLow = low && parseFloat(qty) <= parseFloat(low);
1801
+ const str = row.itemType === "service" ? "-" : isLow ? `${qty} !` : qty;
1802
+ return isLow && hasColor() ? chalk5.red(str) : str;
1803
+ }
1804
+ },
1805
+ { key: "taxPercent", header: "Tax%", width: 6, format: (v) => `${v ?? 0}%` },
1806
+ { key: "category", header: "Category", width: 14, format: (v) => String(v ?? "-") }
1807
+ ];
1808
+ if (opts.format === "tsv") outputTSV(result.data, cols);
1809
+ else if (opts.format === "csv") outputCSV(result.data, cols);
1810
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
1811
+ else {
1812
+ outputTable(result.data, cols);
1813
+ paginationFooter(result.page, result.limit, result.total);
1814
+ if (result.data.some((i) => i.lowStockAlert && parseFloat(i.stockQuantity) <= parseFloat(i.lowStockAlert))) {
1815
+ console.log("\n ! = below low stock alert threshold\n");
1816
+ }
1817
+ }
1818
+ } catch (e) {
1819
+ if (e instanceof HisaaboApiError) {
1820
+ const err = e.hisaaboError;
1821
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1822
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1823
+ }
1824
+ fatalError(String(e instanceof Error ? e.message : e));
1825
+ }
1826
+ }
1827
+
1828
+ // src/commands/item/create.ts
1829
+ import * as readline5 from "readline";
1830
+ async function prompt3(rl, q) {
1831
+ return new Promise((resolve2) => rl.question(q, resolve2));
1832
+ }
1833
+ async function itemCreateCommand(opts) {
1834
+ const cfg = requireAuth();
1835
+ const client = new HisaaboClient(cfg);
1836
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
1837
+ let name = opts.name;
1838
+ let unit = opts.unit ?? "pcs";
1839
+ let salePrice = opts.salePrice;
1840
+ let purchasePrice = opts.purchasePrice;
1841
+ let taxPercent = opts.taxPercent ?? "0";
1842
+ let stockQuantity = opts.stock;
1843
+ let hsn = opts.hsn;
1844
+ let category = opts.category;
1845
+ let itemType = opts.type ?? "product";
1846
+ if (!isNonInteractive) {
1847
+ const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1848
+ console.log("\n New Item\n " + "\u2500".repeat(30) + "\n");
1849
+ if (!name) name = (await prompt3(rl, " Name: ")).trim();
1850
+ const typeStr = await prompt3(rl, " Type (product/service) [product]: ");
1851
+ itemType = typeStr.trim() || "product";
1852
+ const unitStr = await prompt3(rl, " Unit [pcs]: ");
1853
+ unit = unitStr.trim() || "pcs";
1854
+ const spStr = await prompt3(rl, " Sale Price: ");
1855
+ if (spStr.trim()) salePrice = spStr.trim();
1856
+ const ppStr = await prompt3(rl, " Purchase Price: ");
1857
+ if (ppStr.trim()) purchasePrice = ppStr.trim();
1858
+ const taxStr = await prompt3(rl, " Tax % [0]: ");
1859
+ taxPercent = taxStr.trim() || "0";
1860
+ if (itemType === "product") {
1861
+ const stockStr = await prompt3(rl, " Opening Stock [0]: ");
1862
+ stockQuantity = stockStr.trim() || "0";
1863
+ }
1864
+ const hsnStr = await prompt3(rl, " HSN Code: ");
1865
+ if (hsnStr.trim()) hsn = hsnStr.trim();
1866
+ const catStr = await prompt3(rl, " Category: ");
1867
+ if (catStr.trim()) category = catStr.trim();
1868
+ rl.close();
1869
+ }
1870
+ if (!name) fatalError("--name is required", EXIT.USAGE);
1871
+ try {
1872
+ const item2 = await client.item.create({
1873
+ name,
1874
+ unit,
1875
+ salePrice,
1876
+ purchasePrice,
1877
+ taxPercent,
1878
+ stockQuantity,
1879
+ hsn,
1880
+ category,
1881
+ itemType
1882
+ });
1883
+ if (opts.json) {
1884
+ outputJSON(item2);
1885
+ return;
1886
+ }
1887
+ success(`Created: ${item2.name} (${item2.itemType})`);
1888
+ console.log(` ID: ${item2.id}
1889
+ `);
1890
+ } catch (e) {
1891
+ if (e instanceof HisaaboApiError) {
1892
+ const err = e.hisaaboError;
1893
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1894
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1895
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1896
+ }
1897
+ fatalError(String(e instanceof Error ? e.message : e));
1898
+ }
1899
+ }
1900
+
1901
+ // src/commands/item/delete.ts
1902
+ import * as readline6 from "readline";
1903
+ async function itemDeleteCommand(id, opts) {
1904
+ const cfg = requireAuth();
1905
+ const client = new HisaaboClient(cfg);
1906
+ try {
1907
+ const item2 = await client.item.get(id);
1908
+ if (!opts.yes && process.stdin.isTTY) {
1909
+ const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1910
+ const answer = await new Promise((resolve2) => {
1911
+ rl.question(` Delete ${item2.name}? (y/N): `, resolve2);
1912
+ });
1913
+ rl.close();
1914
+ if (answer.trim().toLowerCase() !== "y") {
1915
+ console.log(" Cancelled.");
1916
+ process.exit(0);
1917
+ }
1918
+ }
1919
+ const result = await client.item.delete(id);
1920
+ if (opts.json) {
1921
+ outputJSON(result);
1922
+ return;
1923
+ }
1924
+ success(`Deleted: ${item2.name}`);
1925
+ } catch (e) {
1926
+ if (e instanceof HisaaboApiError) {
1927
+ const err = e.hisaaboError;
1928
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1929
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1930
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
1931
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1932
+ }
1933
+ fatalError(String(e instanceof Error ? e.message : e));
1934
+ }
1935
+ }
1936
+
1937
+ // src/commands/item/stock.ts
1938
+ async function itemStockCommand(id, adjustment, opts) {
1939
+ const cfg = requireAuth();
1940
+ const client = new HisaaboClient(cfg);
1941
+ if (!/^[+-]?\d+(\.\d+)?$/.test(adjustment)) {
1942
+ fatalError(`Invalid adjustment: ${adjustment}. Use a number like +10, -5, or 100`, EXIT.USAGE);
1943
+ }
1944
+ try {
1945
+ const updated = await client.item.adjustStock({
1946
+ itemId: id,
1947
+ adjustment,
1948
+ reason: opts.reason
1949
+ });
1950
+ if (opts.json) {
1951
+ outputJSON(updated);
1952
+ return;
1953
+ }
1954
+ const adj = parseFloat(adjustment);
1955
+ const dir = adj >= 0 ? "+" : "";
1956
+ success(`Stock adjusted: ${updated.name} ${dir}${formatAmount(adjustment)} \u2192 ${formatAmount(updated.stockQuantity)}`);
1957
+ } catch (e) {
1958
+ if (e instanceof HisaaboApiError) {
1959
+ const err = e.hisaaboError;
1960
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1961
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1962
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1963
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1964
+ }
1965
+ fatalError(String(e instanceof Error ? e.message : e));
1966
+ }
1967
+ }
1968
+
1969
+ // src/commands/payment/list.ts
1970
+ async function paymentListCommand(opts) {
1971
+ const cfg = requireAuth();
1972
+ const client = new HisaaboClient(cfg);
1973
+ const page = opts.page ?? 1;
1974
+ const limit = opts.limit ?? 20;
1975
+ try {
1976
+ const result = await client.payment.list({
1977
+ partyId: opts.partyId ?? null,
1978
+ fromDate: opts.from ?? null,
1979
+ toDate: opts.to ?? null,
1980
+ page,
1981
+ limit
1982
+ });
1983
+ if (opts.json) {
1984
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
1985
+ return;
1986
+ }
1987
+ console.log(`
1988
+ Payments ${result.total} total
1989
+ `);
1990
+ const cols = [
1991
+ { key: "paymentNumber", header: "#", width: 10 },
1992
+ { key: "partyName", header: "Party", width: 20 },
1993
+ { key: "paymentDate", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
1994
+ { key: "amount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1995
+ { key: "mode", header: "Mode", width: 8 },
1996
+ { key: "referenceNumber", header: "Ref#", width: 14, format: (v) => String(v ?? "-") }
1997
+ ];
1998
+ if (opts.format === "tsv") outputTSV(result.data, cols);
1999
+ else if (opts.format === "csv") outputCSV(result.data, cols);
2000
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
2001
+ else {
2002
+ outputTable(result.data, cols);
2003
+ paginationFooter(result.page, result.limit, result.total);
2004
+ }
2005
+ } catch (e) {
2006
+ if (e instanceof HisaaboApiError) {
2007
+ const err = e.hisaaboError;
2008
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2009
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2010
+ }
2011
+ fatalError(String(e instanceof Error ? e.message : e));
2012
+ }
2013
+ }
2014
+
2015
+ // src/commands/payment/create.ts
2016
+ import * as readline7 from "readline";
2017
+ async function prompt4(rl, q) {
2018
+ return new Promise((resolve2) => rl.question(q, resolve2));
2019
+ }
2020
+ async function paymentCreateCommand(opts) {
2021
+ const cfg = requireAuth();
2022
+ const client = new HisaaboClient(cfg);
2023
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
2024
+ let partyId = opts.partyId;
2025
+ let amount = opts.amount;
2026
+ let mode = opts.mode;
2027
+ let referenceNumber = opts.reference;
2028
+ let paymentDate = opts.date ?? todayISO();
2029
+ let notes = opts.notes;
2030
+ try {
2031
+ if (!isNonInteractive) {
2032
+ const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
2033
+ console.log("\n Record Payment\n " + "\u2500".repeat(30) + "\n");
2034
+ if (!partyId) {
2035
+ const search = await prompt4(rl, " Select Party:\n > Search: ");
2036
+ const parties = await client.party.list({ search: search.trim(), limit: 5 });
2037
+ if (parties.data.length === 0) {
2038
+ rl.close();
2039
+ fatalError("No parties found.", EXIT.NOT_FOUND);
2040
+ }
2041
+ parties.data.forEach((p, i) => {
2042
+ const bal = parseFloat(p.balance);
2043
+ const balStr = `Balance: ${formatINR(p.balance)} ${bal >= 0 ? "receivable" : "payable"}`;
2044
+ console.log(` ${i + 1} ${p.name.padEnd(20)} ${balStr}`);
2045
+ });
2046
+ const choice = await prompt4(rl, "\n Party [1]: ");
2047
+ const idx = parseInt(choice.trim() || "1", 10) - 1;
2048
+ const selected = parties.data[Math.max(0, Math.min(idx, parties.data.length - 1))];
2049
+ if (!selected) {
2050
+ rl.close();
2051
+ fatalError("Invalid selection.", EXIT.USAGE);
2052
+ }
2053
+ partyId = selected.id;
2054
+ console.log(`
2055
+ Party: ${selected.name}
2056
+ `);
2057
+ const invoices = await client.invoice.list({ partyId, status: "sent", limit: 10 });
2058
+ const partial = await client.invoice.list({ partyId, status: "partial", limit: 10 });
2059
+ const unpaid = [...invoices.data, ...partial.data];
2060
+ if (unpaid.length > 0) {
2061
+ console.log(" Unpaid Invoices:");
2062
+ console.log(" " + "\u2500".repeat(65));
2063
+ unpaid.forEach((inv, i) => {
2064
+ console.log(` ${i + 1} ${inv.invoiceNumber.padEnd(12)} ${inv.totalAmount.padStart(12)} due ${inv.status}`);
2065
+ });
2066
+ console.log();
2067
+ }
2068
+ if (!amount) {
2069
+ const amtStr = await prompt4(rl, " Amount: ");
2070
+ amount = amtStr.trim();
2071
+ }
2072
+ const modeStr = await prompt4(rl, " Mode (cash/bank/upi/cheque/other) [upi]: ");
2073
+ mode = modeStr.trim() || "upi";
2074
+ const refStr = await prompt4(rl, " Reference Number: ");
2075
+ if (refStr.trim()) referenceNumber = refStr.trim();
2076
+ const dateStr = await prompt4(rl, ` Payment Date [${todayISO()}]: `);
2077
+ if (dateStr.trim()) paymentDate = dateStr.trim();
2078
+ const notesStr = await prompt4(rl, " Notes: ");
2079
+ if (notesStr.trim()) notes = notesStr.trim();
2080
+ console.log(`
2081
+ Total Payment: ${formatAmount(amount ?? "0")}`);
2082
+ const confirm = await prompt4(rl, "\n Record this payment? (y/n) [y]: ");
2083
+ rl.close();
2084
+ if (confirm.trim().toLowerCase() === "n") {
2085
+ console.log(" Cancelled.");
2086
+ process.exit(0);
2087
+ }
2088
+ } else {
2089
+ rl.close();
2090
+ }
2091
+ }
2092
+ if (!partyId) fatalError("--party-id is required", EXIT.USAGE);
2093
+ if (!amount) fatalError("--amount is required", EXIT.USAGE);
2094
+ if (!mode) mode = "cash";
2095
+ const payment2 = await client.payment.create({
2096
+ partyId,
2097
+ amount,
2098
+ mode,
2099
+ referenceNumber,
2100
+ paymentDate,
2101
+ notes,
2102
+ invoiceId: opts.invoiceId
2103
+ });
2104
+ if (opts.json) {
2105
+ outputJSON(payment2);
2106
+ return;
2107
+ }
2108
+ success(`Recorded: ${payment2.paymentNumber} for ${formatINR(payment2.amount)}`);
2109
+ } catch (e) {
2110
+ if (e instanceof HisaaboApiError) {
2111
+ const err = e.hisaaboError;
2112
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2113
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2114
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2115
+ }
2116
+ fatalError(String(e instanceof Error ? e.message : e));
2117
+ }
2118
+ }
2119
+
2120
+ // src/commands/payment/delete.ts
2121
+ import * as readline8 from "readline";
2122
+ async function paymentDeleteCommand(id, opts) {
2123
+ const cfg = requireAuth();
2124
+ const client = new HisaaboClient(cfg);
2125
+ try {
2126
+ const payment2 = await client.payment.getById(id);
2127
+ if (!payment2) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
2128
+ if (!opts.yes && process.stdin.isTTY) {
2129
+ const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
2130
+ const answer = await new Promise((resolve2) => {
2131
+ rl.question(` Delete ${payment2.paymentNumber} (${formatINR(payment2.amount)})? (y/N): `, resolve2);
2132
+ });
2133
+ rl.close();
2134
+ if (answer.trim().toLowerCase() !== "y") {
2135
+ console.log(" Cancelled.");
2136
+ process.exit(0);
2137
+ }
2138
+ }
2139
+ const result = await client.payment.delete(id);
2140
+ if (opts.json) {
2141
+ outputJSON(result);
2142
+ return;
2143
+ }
2144
+ success(`Deleted: ${payment2.paymentNumber}`);
2145
+ } catch (e) {
2146
+ if (e instanceof HisaaboApiError) {
2147
+ const err = e.hisaaboError;
2148
+ if (err.code === "not_found") fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
2149
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2150
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
2151
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2152
+ }
2153
+ fatalError(String(e instanceof Error ? e.message : e));
2154
+ }
2155
+ }
2156
+
2157
+ // src/commands/expense/list.ts
2158
+ async function expenseListCommand(opts) {
2159
+ const cfg = requireAuth();
2160
+ const client = new HisaaboClient(cfg);
2161
+ const page = opts.page ?? 1;
2162
+ const limit = opts.limit ?? 20;
2163
+ try {
2164
+ const result = await client.expense.list({
2165
+ category: opts.category ?? null,
2166
+ fromDate: opts.from ?? null,
2167
+ toDate: opts.to ?? null,
2168
+ page,
2169
+ limit
2170
+ });
2171
+ if (opts.json) {
2172
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2173
+ return;
2174
+ }
2175
+ console.log(`
2176
+ Expenses ${result.total} total
2177
+ `);
2178
+ const cols = [
2179
+ { key: "expenseDate", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
2180
+ { key: "category", header: "Category", width: 18 },
2181
+ { key: "description", header: "Description", width: 22, format: (v) => String(v ?? "-") },
2182
+ { key: "amount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
2183
+ { key: "mode", header: "Mode", width: 8 }
2184
+ ];
2185
+ if (opts.format === "tsv") outputTSV(result.data, cols);
2186
+ else if (opts.format === "csv") outputCSV(result.data, cols);
2187
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
2188
+ else {
2189
+ outputTable(result.data, cols);
2190
+ paginationFooter(result.page, result.limit, result.total);
2191
+ }
2192
+ } catch (e) {
2193
+ if (e instanceof HisaaboApiError) {
2194
+ const err = e.hisaaboError;
2195
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2196
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2197
+ }
2198
+ fatalError(String(e instanceof Error ? e.message : e));
2199
+ }
2200
+ }
2201
+
2202
+ // src/commands/expense/create.ts
2203
+ async function expenseCreateCommand(opts) {
2204
+ const cfg = requireAuth();
2205
+ const client = new HisaaboClient(cfg);
2206
+ if (!opts.category) fatalError("--category is required", EXIT.USAGE);
2207
+ if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2208
+ const mode = opts.mode ?? "cash";
2209
+ try {
2210
+ const expense2 = await client.expense.create({
2211
+ category: opts.category,
2212
+ amount: opts.amount,
2213
+ mode,
2214
+ description: opts.description,
2215
+ expenseDate: opts.date ?? todayISO(),
2216
+ referenceNumber: opts.reference
2217
+ });
2218
+ if (opts.json) {
2219
+ outputJSON(expense2);
2220
+ return;
2221
+ }
2222
+ success(`Created: ${expense2.category} ${formatINR(expense2.amount)}`);
2223
+ } catch (e) {
2224
+ if (e instanceof HisaaboApiError) {
2225
+ const err = e.hisaaboError;
2226
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2227
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2228
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2229
+ }
2230
+ fatalError(String(e instanceof Error ? e.message : e));
2231
+ }
2232
+ }
2233
+
2234
+ // src/commands/expense/delete.ts
2235
+ import * as readline9 from "readline";
2236
+ async function expenseDeleteCommand(id, opts) {
2237
+ const cfg = requireAuth();
2238
+ const client = new HisaaboClient(cfg);
2239
+ try {
2240
+ const _list = await client.expense.list({ page: 1, limit: 1 });
2241
+ if (!opts.yes && process.stdin.isTTY) {
2242
+ const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
2243
+ const answer = await new Promise((resolve2) => {
2244
+ rl.question(` Delete expense ${id}? (y/N): `, resolve2);
2245
+ });
2246
+ rl.close();
2247
+ if (answer.trim().toLowerCase() !== "y") {
2248
+ console.log(" Cancelled.");
2249
+ process.exit(0);
2250
+ }
2251
+ }
2252
+ const result = await client.expense.delete(id);
2253
+ if (opts.json) {
2254
+ outputJSON(result);
2255
+ return;
2256
+ }
2257
+ success(`Deleted expense: ${id}`);
2258
+ } catch (e) {
2259
+ if (e instanceof HisaaboApiError) {
2260
+ const err = e.hisaaboError;
2261
+ if (err.code === "not_found") fatalError(`Expense not found: ${id}`, EXIT.NOT_FOUND);
2262
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2263
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
2264
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2265
+ }
2266
+ fatalError(String(e instanceof Error ? e.message : e));
2267
+ }
2268
+ }
2269
+
2270
+ // src/commands/gst/index.ts
2271
+ import * as fs2 from "fs";
2272
+ function resolveMonthYear(opts) {
2273
+ if (opts.quarter) {
2274
+ const range = quarterRange(opts.quarter);
2275
+ return { month: range.month, year: range.year };
2276
+ }
2277
+ const now = /* @__PURE__ */ new Date();
2278
+ return {
2279
+ month: opts.month ?? now.getMonth() + 1,
2280
+ year: opts.year ?? now.getFullYear()
2281
+ };
2282
+ }
2283
+ async function gstR1Command(opts) {
2284
+ const cfg = requireAuth();
2285
+ const client = new HisaaboClient(cfg);
2286
+ const { month, year } = resolveMonthYear(opts);
2287
+ try {
2288
+ const report2 = await client.gst.gstr1({ month, year });
2289
+ if (opts.json) {
2290
+ outputJSON(report2);
2291
+ return;
2292
+ }
2293
+ const quarterLabel = opts.quarter ? `${opts.quarter} ` : "";
2294
+ console.log(`
2295
+ GSTR-1 Summary ${quarterLabel}FY ${year}-${String(year + 1).slice(2)}`);
2296
+ console.log(` ${"\u2550".repeat(60)}
2297
+ `);
2298
+ if (report2.summary && typeof report2.summary === "object") {
2299
+ const s = report2.summary;
2300
+ if (s["totalTaxableValue"]) console.log(` Total Taxable: ${formatAmount(String(s["totalTaxableValue"]))}`);
2301
+ if (s["totalTax"]) console.log(` Total Tax: ${formatAmount(String(s["totalTax"]))}`);
2302
+ if (s["totalInvoices"]) console.log(` Total Invoices: ${s["totalInvoices"]}`);
2303
+ }
2304
+ console.log();
2305
+ console.log(" Use --json for full report data.");
2306
+ console.log(" Use: hisaabo gst r1-csv to download GSTN-compatible CSV.\n");
2307
+ } catch (e) {
2308
+ if (e instanceof HisaaboApiError) {
2309
+ const err = e.hisaaboError;
2310
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2311
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2312
+ }
2313
+ fatalError(String(e instanceof Error ? e.message : e));
2314
+ }
2315
+ }
2316
+ async function gstR3bCommand(opts) {
2317
+ const cfg = requireAuth();
2318
+ const client = new HisaaboClient(cfg);
2319
+ const { month, year } = resolveMonthYear(opts);
2320
+ try {
2321
+ const report2 = await client.gst.gstr3b({ month, year });
2322
+ if (opts.json) {
2323
+ outputJSON(report2);
2324
+ return;
2325
+ }
2326
+ console.log(`
2327
+ GSTR-3B Summary ${month}/${year}`);
2328
+ console.log(` ${"\u2550".repeat(60)}
2329
+ `);
2330
+ if (report2.summary && typeof report2.summary === "object") {
2331
+ const s = report2.summary;
2332
+ Object.entries(s).forEach(([k, v]) => {
2333
+ console.log(` ${k.padEnd(28)}: ${String(v ?? "-")}`);
2334
+ });
2335
+ }
2336
+ console.log();
2337
+ } catch (e) {
2338
+ if (e instanceof HisaaboApiError) {
2339
+ const err = e.hisaaboError;
2340
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2341
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2342
+ }
2343
+ fatalError(String(e instanceof Error ? e.message : e));
2344
+ }
2345
+ }
2346
+ async function gstR1CsvCommand(opts) {
2347
+ const cfg = requireAuth();
2348
+ const client = new HisaaboClient(cfg);
2349
+ const { month, year } = resolveMonthYear(opts);
2350
+ try {
2351
+ const result = await client.gst.gstr1CSV({ month, year });
2352
+ const outputPath = opts.output ?? result.filename;
2353
+ fs2.writeFileSync(outputPath, result.csv);
2354
+ console.log(` Saved: ${outputPath}`);
2355
+ } catch (e) {
2356
+ if (e instanceof HisaaboApiError) {
2357
+ const err = e.hisaaboError;
2358
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2359
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2360
+ }
2361
+ fatalError(String(e instanceof Error ? e.message : e));
2362
+ }
2363
+ }
2364
+
2365
+ // src/commands/report/index.ts
2366
+ function resolveRange(opts) {
2367
+ if (opts.thisFy) return { from: fyStart(), to: todayISO() };
2368
+ if (opts.thisMonth) return { from: monthStart(), to: monthEnd() };
2369
+ return { from: opts.from ?? fyStart(), to: opts.to ?? todayISO() };
2370
+ }
2371
+ async function reportDaybookCommand(opts) {
2372
+ const cfg = requireAuth();
2373
+ const client = new HisaaboClient(cfg);
2374
+ const { from, to } = resolveRange(opts);
2375
+ try {
2376
+ const result = await client.reports.daybook({ fromDate: from, toDate: to });
2377
+ if (opts.json) {
2378
+ outputJSON(result);
2379
+ return;
2380
+ }
2381
+ console.log(`
2382
+ Daybook Report ${from} \u2192 ${to}
2383
+ `);
2384
+ console.log(` ${"\u2550".repeat(70)}
2385
+ `);
2386
+ const cols = [
2387
+ { key: "time", header: "Time", width: 20, format: (v) => formatDate(String(v ?? "")) },
2388
+ { key: "entryType", header: "Type", width: 10 },
2389
+ { key: "number", header: "#", width: 12, format: (v) => String(v ?? "-") },
2390
+ { key: "partyOrCategory", header: "Party / Category", width: 22 },
2391
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
2392
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" }
2393
+ ];
2394
+ if (opts.format === "tsv") outputTSV(result.entries, cols);
2395
+ else if (opts.format === "csv") outputCSV(result.entries, cols);
2396
+ else {
2397
+ outputTable(result.entries, cols);
2398
+ const s = result.summary;
2399
+ console.log(`
2400
+ Sales Invoiced: ${formatAmount(s.totalSalesInvoiced).padStart(14)}`);
2401
+ console.log(` Purchases Invoiced: ${formatAmount(s.totalPurchaseInvoiced).padStart(14)}`);
2402
+ console.log(` Payments Received: ${formatAmount(s.totalPaymentsReceived).padStart(14)}`);
2403
+ console.log(` Payments Made: ${formatAmount(s.totalPaymentsMade).padStart(14)}`);
2404
+ console.log(` Expenses: ${formatAmount(s.totalExpenses).padStart(14)}`);
2405
+ console.log(` Net Cash Movement: ${formatAmount(s.netCashMovement).padStart(14)}
2406
+ `);
2407
+ }
2408
+ } catch (e) {
2409
+ if (e instanceof HisaaboApiError) {
2410
+ const err = e.hisaaboError;
2411
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2412
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2413
+ }
2414
+ fatalError(String(e instanceof Error ? e.message : e));
2415
+ }
2416
+ }
2417
+ async function reportOutstandingCommand(opts) {
2418
+ const cfg = requireAuth();
2419
+ const client = new HisaaboClient(cfg);
2420
+ try {
2421
+ const result = await client.reports.outstanding({
2422
+ type: opts.type ?? "both"
2423
+ });
2424
+ if (opts.json) {
2425
+ outputJSON(result);
2426
+ return;
2427
+ }
2428
+ console.log("\n Outstanding Report\n");
2429
+ console.log(" " + "\u2550".repeat(60) + "\n");
2430
+ if (result.receivables && Array.isArray(result.receivables)) {
2431
+ console.log(" Receivables:");
2432
+ result.receivables.forEach((row) => {
2433
+ console.log(` ${String(row["partyName"] ?? "").padEnd(25)} ${formatAmount(String(row["balance"] ?? "0")).padStart(14)}`);
2434
+ });
2435
+ }
2436
+ if (result.payables && Array.isArray(result.payables)) {
2437
+ console.log("\n Payables:");
2438
+ result.payables.forEach((row) => {
2439
+ console.log(` ${String(row["partyName"] ?? "").padEnd(25)} ${formatAmount(String(row["balance"] ?? "0")).padStart(14)}`);
2440
+ });
2441
+ }
2442
+ console.log();
2443
+ } catch (e) {
2444
+ if (e instanceof HisaaboApiError) {
2445
+ const err = e.hisaaboError;
2446
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2447
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2448
+ }
2449
+ fatalError(String(e instanceof Error ? e.message : e));
2450
+ }
2451
+ }
2452
+ async function reportTaxSummaryCommand(opts) {
2453
+ const cfg = requireAuth();
2454
+ const client = new HisaaboClient(cfg);
2455
+ const { from, to } = resolveRange(opts);
2456
+ try {
2457
+ const result = await client.reports.taxSummary({ fromDate: from, toDate: to });
2458
+ if (opts.json) {
2459
+ outputJSON(result);
2460
+ return;
2461
+ }
2462
+ console.log(`
2463
+ Tax Summary ${from} \u2192 ${to}
2464
+ `);
2465
+ console.log(" " + "\u2550".repeat(60) + "\n");
2466
+ if (Array.isArray(result.rows)) {
2467
+ result.rows.forEach((row) => {
2468
+ const rate = String(row["taxPercent"] ?? row["rate"] ?? "-");
2469
+ const taxable = formatAmount(String(row["taxableAmount"] ?? "0"));
2470
+ const tax = formatAmount(String(row["taxAmount"] ?? "0"));
2471
+ console.log(` ${rate.padEnd(6)}% Taxable: ${taxable.padStart(14)} Tax: ${tax.padStart(12)}`);
2472
+ });
2473
+ }
2474
+ console.log();
2475
+ } catch (e) {
2476
+ if (e instanceof HisaaboApiError) {
2477
+ const err = e.hisaaboError;
2478
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2479
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2480
+ }
2481
+ fatalError(String(e instanceof Error ? e.message : e));
2482
+ }
2483
+ }
2484
+ async function reportItemSalesCommand(opts) {
2485
+ const cfg = requireAuth();
2486
+ const client = new HisaaboClient(cfg);
2487
+ const { from, to } = resolveRange(opts);
2488
+ try {
2489
+ const result = await client.reports.itemSales({ fromDate: from, toDate: to });
2490
+ if (opts.json) {
2491
+ outputJSON(result);
2492
+ return;
2493
+ }
2494
+ console.log(`
2495
+ Item Sales ${from} \u2192 ${to}
2496
+ `);
2497
+ console.log(" " + "\u2550".repeat(70) + "\n");
2498
+ if (Array.isArray(result.rows)) {
2499
+ result.rows.slice(0, 50).forEach((row) => {
2500
+ const name = String(row["itemName"] ?? row["name"] ?? "-").padEnd(25);
2501
+ const qty = String(row["totalQuantity"] ?? row["qty"] ?? "-").padStart(8);
2502
+ const rev = formatAmount(String(row["totalRevenue"] ?? row["revenue"] ?? "0")).padStart(14);
2503
+ console.log(` ${name} ${qty} ${rev}`);
2504
+ });
2505
+ }
2506
+ console.log();
2507
+ } catch (e) {
2508
+ if (e instanceof HisaaboApiError) {
2509
+ const err = e.hisaaboError;
2510
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2511
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2512
+ }
2513
+ fatalError(String(e instanceof Error ? e.message : e));
2514
+ }
2515
+ }
2516
+ async function reportStockSummaryCommand(opts) {
2517
+ const cfg = requireAuth();
2518
+ const client = new HisaaboClient(cfg);
2519
+ try {
2520
+ const result = await client.reports.stockSummary({ category: opts.category });
2521
+ if (opts.json) {
2522
+ outputJSON(result);
2523
+ return;
2524
+ }
2525
+ console.log("\n Stock Summary\n");
2526
+ console.log(" " + "\u2550".repeat(60) + "\n");
2527
+ if (Array.isArray(result.rows)) {
2528
+ result.rows.forEach((row) => {
2529
+ const name = String(row["itemName"] ?? row["name"] ?? "-").padEnd(25);
2530
+ const stock = String(row["stockQuantity"] ?? row["stock"] ?? "-").padStart(10);
2531
+ const val = formatAmount(String(row["stockValue"] ?? row["value"] ?? "0")).padStart(14);
2532
+ console.log(` ${name} ${stock} ${val}`);
2533
+ });
2534
+ }
2535
+ console.log();
2536
+ } catch (e) {
2537
+ if (e instanceof HisaaboApiError) {
2538
+ const err = e.hisaaboError;
2539
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2540
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2541
+ }
2542
+ fatalError(String(e instanceof Error ? e.message : e));
2543
+ }
2544
+ }
2545
+
2546
+ // src/commands/bank/index.ts
2547
+ import * as readline10 from "readline";
2548
+ async function prompt5(rl, q) {
2549
+ return new Promise((resolve2) => rl.question(q, resolve2));
2550
+ }
2551
+ async function bankListCommand(opts) {
2552
+ const cfg = requireAuth();
2553
+ const client = new HisaaboClient(cfg);
2554
+ try {
2555
+ const [accounts, summary] = await Promise.all([
2556
+ client.bankAccount.list(),
2557
+ client.bankAccount.summary()
2558
+ ]);
2559
+ if (opts.json) {
2560
+ outputJSON({ accounts, summary });
2561
+ return;
2562
+ }
2563
+ console.log("\n Bank Accounts\n");
2564
+ console.log(` ${"\u2550".repeat(60)}
2565
+ `);
2566
+ const cols = [
2567
+ { key: "accountName", header: "Name", width: 22 },
2568
+ { key: "bankName", header: "Bank", width: 16, format: (v) => String(v ?? "-") },
2569
+ { key: "accountType", header: "Type", width: 10 },
2570
+ { key: "accountNumber", header: "Account #", width: 16, format: (v) => String(v ?? "-") },
2571
+ { key: "currentBalance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
2572
+ { key: "isDefault", header: "Default", width: 8, format: (v) => v ? "Yes" : "" }
2573
+ ];
2574
+ outputTable(accounts, cols);
2575
+ console.log(`
2576
+ Total Balance: ${formatINR(summary.totalBalance)}`);
2577
+ console.log(` Cash in Hand: ${formatINR(summary.cashInHand)}`);
2578
+ console.log(` Bank Balance: ${formatINR(summary.bankBalance)}
2579
+ `);
2580
+ } catch (e) {
2581
+ if (e instanceof HisaaboApiError) {
2582
+ const err = e.hisaaboError;
2583
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2584
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2585
+ }
2586
+ fatalError(String(e instanceof Error ? e.message : e));
2587
+ }
2588
+ }
2589
+ async function bankGetCommand(id, opts) {
2590
+ const cfg = requireAuth();
2591
+ const client = new HisaaboClient(cfg);
2592
+ try {
2593
+ const account = await client.bankAccount.get(id);
2594
+ if (!account) fatalError(`Bank account not found: ${id}`, EXIT.NOT_FOUND);
2595
+ if (opts.json) {
2596
+ outputJSON(account);
2597
+ return;
2598
+ }
2599
+ console.log(`
2600
+ ${account.accountName} (${account.accountType})`);
2601
+ console.log(" " + "\u2500".repeat(45));
2602
+ if (account.bankName) console.log(` Bank: ${account.bankName}`);
2603
+ if (account.accountNumber) console.log(` Account: ${account.accountNumber}`);
2604
+ if (account.ifsc) console.log(` IFSC: ${account.ifsc}`);
2605
+ console.log(` Balance: ${formatINR(account.currentBalance)}`);
2606
+ console.log();
2607
+ } catch (e) {
2608
+ if (e instanceof HisaaboApiError) {
2609
+ const err = e.hisaaboError;
2610
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2611
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2612
+ }
2613
+ fatalError(String(e instanceof Error ? e.message : e));
2614
+ }
2615
+ }
2616
+ async function bankCreateCommand(opts) {
2617
+ const cfg = requireAuth();
2618
+ const client = new HisaaboClient(cfg);
2619
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
2620
+ let name = opts.name;
2621
+ let accountType = opts.type ?? "current";
2622
+ let bankName = opts.bank;
2623
+ let accountNumber = opts.accountNumber;
2624
+ let ifsc = opts.ifsc;
2625
+ let openingBalance = opts.openingBalance;
2626
+ if (!isNonInteractive) {
2627
+ const rl = readline10.createInterface({ input: process.stdin, output: process.stdout });
2628
+ if (!name) name = (await prompt5(rl, " Account Name: ")).trim();
2629
+ const typeStr = await prompt5(rl, " Type (savings/current/cash/credit/other) [current]: ");
2630
+ accountType = typeStr.trim() || "current";
2631
+ const bankStr = await prompt5(rl, " Bank Name: ");
2632
+ if (bankStr.trim()) bankName = bankStr.trim();
2633
+ const numStr = await prompt5(rl, " Account Number: ");
2634
+ if (numStr.trim()) accountNumber = numStr.trim();
2635
+ const ifscStr = await prompt5(rl, " IFSC: ");
2636
+ if (ifscStr.trim()) ifsc = ifscStr.trim();
2637
+ const balStr = await prompt5(rl, " Opening Balance [0]: ");
2638
+ openingBalance = balStr.trim() || "0";
2639
+ rl.close();
2640
+ }
2641
+ if (!name) fatalError("--name is required", EXIT.USAGE);
2642
+ try {
2643
+ const account = await client.bankAccount.create({
2644
+ accountName: name,
2645
+ accountType,
2646
+ bankName,
2647
+ accountNumber,
2648
+ ifsc,
2649
+ openingBalance,
2650
+ isDefault: opts.default
2651
+ });
2652
+ if (opts.json) {
2653
+ outputJSON(account);
2654
+ return;
2655
+ }
2656
+ success(`Created: ${account.accountName}`);
2657
+ console.log(` ID: ${account.id}
2658
+ `);
2659
+ } catch (e) {
2660
+ if (e instanceof HisaaboApiError) {
2661
+ const err = e.hisaaboError;
2662
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2663
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2664
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2665
+ }
2666
+ fatalError(String(e instanceof Error ? e.message : e));
2667
+ }
2668
+ }
2669
+ async function bankTransferCommand(opts) {
2670
+ const cfg = requireAuth();
2671
+ const client = new HisaaboClient(cfg);
2672
+ if (!opts.from) fatalError("--from account ID is required", EXIT.USAGE);
2673
+ if (!opts.to) fatalError("--to account ID is required", EXIT.USAGE);
2674
+ if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2675
+ try {
2676
+ const result = await client.bankAccount.transfer({
2677
+ fromAccountId: opts.from,
2678
+ toAccountId: opts.to,
2679
+ amount: opts.amount,
2680
+ description: opts.description,
2681
+ transactionDate: opts.date
2682
+ });
2683
+ if (opts.json) {
2684
+ outputJSON(result);
2685
+ return;
2686
+ }
2687
+ success(`Transfer recorded: ${formatINR(opts.amount)}`);
2688
+ } catch (e) {
2689
+ if (e instanceof HisaaboApiError) {
2690
+ const err = e.hisaaboError;
2691
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2692
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2693
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2694
+ }
2695
+ fatalError(String(e instanceof Error ? e.message : e));
2696
+ }
2697
+ }
2698
+ async function bankTransactionsCommand(accountId, opts) {
2699
+ const cfg = requireAuth();
2700
+ const client = new HisaaboClient(cfg);
2701
+ const page = opts.page ?? 1;
2702
+ const limit = opts.limit ?? 20;
2703
+ try {
2704
+ const result = await client.bankAccount.listTransactions({
2705
+ bankAccountId: accountId,
2706
+ fromDate: opts.from,
2707
+ toDate: opts.to,
2708
+ page,
2709
+ limit
2710
+ });
2711
+ if (opts.json) {
2712
+ outputJSON(result);
2713
+ return;
2714
+ }
2715
+ const cols = [
2716
+ { key: "transactionDate", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
2717
+ { key: "type", header: "Type", width: 12 },
2718
+ { key: "description", header: "Description", width: 25, format: (v) => String(v ?? "-") },
2719
+ { key: "amount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
2720
+ { key: "balanceAfter", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) }
2721
+ ];
2722
+ console.log(`
2723
+ Transactions for ${accountId}
2724
+ `);
2725
+ outputTable(result.data, cols);
2726
+ paginationFooter(result.page, result.limit, result.total);
2727
+ } catch (e) {
2728
+ if (e instanceof HisaaboApiError) {
2729
+ const err = e.hisaaboError;
2730
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2731
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2732
+ }
2733
+ fatalError(String(e instanceof Error ? e.message : e));
2734
+ }
2735
+ }
2736
+
2737
+ // src/commands/shipment/index.ts
2738
+ async function shipmentListCommand(opts) {
2739
+ const cfg = requireAuth();
2740
+ const client = new HisaaboClient(cfg);
2741
+ const page = opts.page ?? 1;
2742
+ const limit = opts.limit ?? 20;
2743
+ try {
2744
+ const result = await client.shipment.list({
2745
+ status: opts.status ?? null,
2746
+ invoiceId: opts.invoiceId ?? null,
2747
+ page,
2748
+ limit
2749
+ });
2750
+ if (opts.json) {
2751
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2752
+ return;
2753
+ }
2754
+ console.log(`
2755
+ Shipments ${result.total} total
2756
+ `);
2757
+ const cols = [
2758
+ { key: "invoiceNumber", header: "Invoice", width: 12, format: (v) => String(v ?? "-") },
2759
+ { key: "partyName", header: "Party", width: 18, format: (v) => String(v ?? "-") },
2760
+ { key: "carrier", header: "Carrier", width: 12, format: (v) => String(v ?? "-") },
2761
+ { key: "trackingNumber", header: "Tracking", width: 16, format: (v) => String(v ?? "-") },
2762
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) },
2763
+ { key: "shipmentDate", header: "Shipped", width: 12, format: (v) => formatDate(v ? String(v) : null) }
2764
+ ];
2765
+ outputTable(result.data, cols);
2766
+ paginationFooter(result.page, result.limit, result.total);
2767
+ } catch (e) {
2768
+ if (e instanceof HisaaboApiError) {
2769
+ const err = e.hisaaboError;
2770
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2771
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2772
+ }
2773
+ fatalError(String(e instanceof Error ? e.message : e));
2774
+ }
2775
+ }
2776
+ async function shipmentGetCommand(id, opts) {
2777
+ const cfg = requireAuth();
2778
+ const client = new HisaaboClient(cfg);
2779
+ try {
2780
+ const shipment2 = await client.shipment.get(id);
2781
+ if (!shipment2) fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2782
+ if (opts.json) {
2783
+ outputJSON(shipment2);
2784
+ return;
2785
+ }
2786
+ console.log(`
2787
+ Shipment ${id}`);
2788
+ console.log(" " + "\u2500".repeat(45));
2789
+ if (shipment2.invoiceNumber) console.log(` Invoice: ${shipment2.invoiceNumber}`);
2790
+ if (shipment2.partyName) console.log(` Party: ${shipment2.partyName}`);
2791
+ if (shipment2.carrier) console.log(` Carrier: ${shipment2.carrier}`);
2792
+ if (shipment2.trackingNumber) console.log(` Tracking: ${shipment2.trackingNumber}`);
2793
+ if (shipment2.trackingUrl) console.log(` URL: ${shipment2.trackingUrl}`);
2794
+ console.log(` Status: ${formatStatus(shipment2.status)}`);
2795
+ if (shipment2.shipmentDate) console.log(` Shipped: ${formatDate(shipment2.shipmentDate)}`);
2796
+ if (shipment2.estimatedDelivery) console.log(` Est. Del: ${formatDate(shipment2.estimatedDelivery)}`);
2797
+ if (shipment2.actualDelivery) console.log(` Delivered:${formatDate(shipment2.actualDelivery)}`);
2798
+ console.log();
2799
+ } catch (e) {
2800
+ if (e instanceof HisaaboApiError) {
2801
+ const err = e.hisaaboError;
2802
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2803
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2804
+ }
2805
+ fatalError(String(e instanceof Error ? e.message : e));
2806
+ }
2807
+ }
2808
+ async function shipmentCreateCommand(opts) {
2809
+ const cfg = requireAuth();
2810
+ const client = new HisaaboClient(cfg);
2811
+ try {
2812
+ const shipment2 = await client.shipment.create({
2813
+ invoiceId: opts.invoiceId,
2814
+ partyId: opts.partyId,
2815
+ carrier: opts.carrier,
2816
+ trackingNumber: opts.tracking,
2817
+ mode: opts.mode,
2818
+ shipmentDate: opts.date
2819
+ });
2820
+ if (opts.json) {
2821
+ outputJSON(shipment2);
2822
+ return;
2823
+ }
2824
+ success(`Shipment created: ${shipment2.id}`);
2825
+ if (shipment2.trackingNumber) console.log(` Tracking: ${shipment2.trackingNumber}`);
2826
+ console.log();
2827
+ } catch (e) {
2828
+ if (e instanceof HisaaboApiError) {
2829
+ const err = e.hisaaboError;
2830
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2831
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2832
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2833
+ }
2834
+ fatalError(String(e instanceof Error ? e.message : e));
2835
+ }
2836
+ }
2837
+ async function shipmentUpdateCommand(id, opts) {
2838
+ const cfg = requireAuth();
2839
+ const client = new HisaaboClient(cfg);
2840
+ try {
2841
+ const shipment2 = await client.shipment.update({
2842
+ id,
2843
+ status: opts.status,
2844
+ trackingNumber: opts.tracking,
2845
+ carrier: opts.carrier
2846
+ });
2847
+ if (opts.json) {
2848
+ outputJSON(shipment2);
2849
+ return;
2850
+ }
2851
+ success(`Shipment updated: ${formatStatus(shipment2.status)}`);
2852
+ } catch (e) {
2853
+ if (e instanceof HisaaboApiError) {
2854
+ const err = e.hisaaboError;
2855
+ if (err.code === "not_found") fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2856
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2857
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2858
+ }
2859
+ fatalError(String(e instanceof Error ? e.message : e));
2860
+ }
2861
+ }
2862
+
2863
+ // src/commands/target/index.ts
2864
+ async function targetListCommand(opts) {
2865
+ const cfg = requireAuth();
2866
+ const client = new HisaaboClient(cfg);
2867
+ try {
2868
+ const targets = await client.target.list({});
2869
+ if (opts.json) {
2870
+ outputJSON(targets);
2871
+ return;
2872
+ }
2873
+ console.log("\n Sales Targets\n");
2874
+ const cols = [
2875
+ { key: "id", header: "ID", width: 10, format: (v) => String(v ?? "").slice(0, 8) + "..." },
2876
+ { key: "type", header: "Type", width: 14 },
2877
+ { key: "period", header: "Period", width: 12 },
2878
+ { key: "targetValue", header: "Target", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
2879
+ { key: "startDate", header: "Start", width: 13, format: (v) => formatDate(String(v ?? "")) },
2880
+ { key: "endDate", header: "End", width: 13, format: (v) => formatDate(v ? String(v) : null) }
2881
+ ];
2882
+ outputTable(targets, cols);
2883
+ } catch (e) {
2884
+ if (e instanceof HisaaboApiError) {
2885
+ const err = e.hisaaboError;
2886
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2887
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2888
+ }
2889
+ fatalError(String(e instanceof Error ? e.message : e));
2890
+ }
2891
+ }
2892
+ async function targetMyCommand(opts) {
2893
+ const cfg = requireAuth();
2894
+ const client = new HisaaboClient(cfg);
2895
+ try {
2896
+ const targets = await client.target.myTargets();
2897
+ if (opts.json) {
2898
+ outputJSON(targets);
2899
+ return;
2900
+ }
2901
+ console.log("\n My Targets\n");
2902
+ console.log(" " + "\u2550".repeat(60) + "\n");
2903
+ targets.forEach((t) => {
2904
+ const pct = Math.round(t.percentComplete);
2905
+ const bar = "\u2588".repeat(Math.floor(pct / 5)) + "\u2591".repeat(20 - Math.floor(pct / 5));
2906
+ console.log(` ${t.type} (${t.period})`);
2907
+ console.log(` Target: ${formatAmount(t.targetValue)} Current: ${formatAmount(t.currentValue)} ${pct}%`);
2908
+ console.log(` [${bar}]
2909
+ `);
2910
+ });
2911
+ } catch (e) {
2912
+ if (e instanceof HisaaboApiError) {
2913
+ const err = e.hisaaboError;
2914
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2915
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2916
+ }
2917
+ fatalError(String(e instanceof Error ? e.message : e));
2918
+ }
2919
+ }
2920
+ async function targetCreateCommand(opts) {
2921
+ const cfg = requireAuth();
2922
+ const client = new HisaaboClient(cfg);
2923
+ if (!opts.type) fatalError("--type is required (order_count/order_value/item_quantity)", EXIT.USAGE);
2924
+ if (!opts.value) fatalError("--value is required", EXIT.USAGE);
2925
+ if (!opts.startDate) fatalError("--start-date is required", EXIT.USAGE);
2926
+ try {
2927
+ const target2 = await client.target.create({
2928
+ type: opts.type,
2929
+ period: opts.period ?? "monthly",
2930
+ targetValue: opts.value,
2931
+ startDate: opts.startDate,
2932
+ endDate: opts.endDate,
2933
+ notes: opts.notes
2934
+ });
2935
+ if (opts.json) {
2936
+ outputJSON(target2);
2937
+ return;
2938
+ }
2939
+ success(`Target created: ${target2.type} ${target2.period} ${formatAmount(target2.targetValue)}`);
2940
+ } catch (e) {
2941
+ if (e instanceof HisaaboApiError) {
2942
+ const err = e.hisaaboError;
2943
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2944
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2945
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2946
+ }
2947
+ fatalError(String(e instanceof Error ? e.message : e));
2948
+ }
2949
+ }
2950
+
2951
+ // src/commands/store/index.ts
2952
+ async function storeSettingsCommand(opts) {
2953
+ const cfg = requireAuth();
2954
+ const client = new HisaaboClient(cfg);
2955
+ try {
2956
+ const settings = await client.store.getSettings();
2957
+ if (opts.json) {
2958
+ outputJSON(settings);
2959
+ return;
2960
+ }
2961
+ console.log("\n Store Settings\n " + "\u2500".repeat(35));
2962
+ console.log(` Enabled: ${settings.storeEnabled ? "Yes" : "No"}`);
2963
+ if (settings.storeSlug) console.log(` Slug: ${settings.storeSlug}`);
2964
+ if (settings.storeName) console.log(` Name: ${settings.storeName}`);
2965
+ if (settings.storeDescription) console.log(` About: ${settings.storeDescription}`);
2966
+ console.log();
2967
+ } catch (e) {
2968
+ if (e instanceof HisaaboApiError) {
2969
+ const err = e.hisaaboError;
2970
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2971
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2972
+ }
2973
+ fatalError(String(e instanceof Error ? e.message : e));
2974
+ }
2975
+ }
2976
+ async function storeOrdersCommand(opts) {
2977
+ const cfg = requireAuth();
2978
+ const client = new HisaaboClient(cfg);
2979
+ const page = opts.page ?? 1;
2980
+ const limit = opts.limit ?? 20;
2981
+ try {
2982
+ const result = await client.store.listOrders({ status: opts.status ?? null, page, limit });
2983
+ if (opts.json) {
2984
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2985
+ return;
2986
+ }
2987
+ console.log(`
2988
+ Store Orders ${result.total} total
2989
+ `);
2990
+ const cols = [
2991
+ { key: "orderNumber", header: "#", width: 12 },
2992
+ { key: "customerName", header: "Customer", width: 20 },
2993
+ { key: "createdAt", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
2994
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
2995
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
2996
+ ];
2997
+ outputTable(result.data, cols);
2998
+ paginationFooter(result.page, result.limit, result.total);
2999
+ } catch (e) {
3000
+ if (e instanceof HisaaboApiError) {
3001
+ const err = e.hisaaboError;
3002
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3003
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3004
+ }
3005
+ fatalError(String(e instanceof Error ? e.message : e));
3006
+ }
3007
+ }
3008
+
3009
+ // src/commands/import/index.ts
3010
+ import * as fs3 from "fs";
3011
+ import * as path2 from "path";
3012
+ function readJsonFile(filePath) {
3013
+ const abs = path2.resolve(filePath);
3014
+ if (!fs3.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
3015
+ const raw = fs3.readFileSync(abs, "utf-8");
3016
+ try {
3017
+ const parsed = JSON.parse(raw);
3018
+ if (!Array.isArray(parsed)) fatalError("Expected a JSON array", EXIT.USAGE);
3019
+ return parsed;
3020
+ } catch {
3021
+ fatalError(`Invalid JSON in file: ${abs}`, EXIT.USAGE);
3022
+ }
3023
+ }
3024
+ function readCsvFile(filePath) {
3025
+ const abs = path2.resolve(filePath);
3026
+ if (!fs3.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
3027
+ const lines = fs3.readFileSync(abs, "utf-8").split("\n").filter((l) => l.trim());
3028
+ if (lines.length < 2) fatalError("CSV must have at least a header row and one data row", EXIT.USAGE);
3029
+ const headers = (lines[0] ?? "").split(",").map((h) => h.trim().replace(/^"|"$/g, ""));
3030
+ return lines.slice(1).map((line) => {
3031
+ const vals = line.split(",").map((v) => v.trim().replace(/^"|"$/g, ""));
3032
+ const obj = {};
3033
+ headers.forEach((h, i) => {
3034
+ obj[h] = vals[i] ?? "";
3035
+ });
3036
+ return obj;
3037
+ });
3038
+ }
3039
+ async function importPartiesCommand(filePath, opts) {
3040
+ const cfg = requireAuth();
3041
+ const client = new HisaaboClient(cfg);
3042
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3043
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3044
+ console.log(` Importing ${data.length} parties...`);
3045
+ try {
3046
+ const result = await client.import.importParties({ parties: data });
3047
+ if (opts.json) {
3048
+ outputJSON(result);
3049
+ return;
3050
+ }
3051
+ success(`Imported: ${result.imported} parties`);
3052
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3053
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3054
+ } catch (e) {
3055
+ if (e instanceof HisaaboApiError) {
3056
+ const err = e.hisaaboError;
3057
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3058
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3059
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3060
+ }
3061
+ fatalError(String(e instanceof Error ? e.message : e));
3062
+ }
3063
+ }
3064
+ async function importItemsCommand(filePath, opts) {
3065
+ const cfg = requireAuth();
3066
+ const client = new HisaaboClient(cfg);
3067
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3068
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3069
+ console.log(` Importing ${data.length} items...`);
3070
+ try {
3071
+ const result = await client.import.importItems({ items: data });
3072
+ if (opts.json) {
3073
+ outputJSON(result);
3074
+ return;
3075
+ }
3076
+ success(`Imported: ${result.imported} items`);
3077
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3078
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3079
+ } catch (e) {
3080
+ if (e instanceof HisaaboApiError) {
3081
+ const err = e.hisaaboError;
3082
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3083
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3084
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3085
+ }
3086
+ fatalError(String(e instanceof Error ? e.message : e));
3087
+ }
3088
+ }
3089
+
3090
+ // src/bin/hisaabo.ts
3091
+ var program = new Command();
3092
+ program.name("hisaabo").description("Hisaabo CLI \u2014 Invoicing and business management").version("0.1.0");
3093
+ program.command("login").description("Authenticate and configure your Hisaabo server").option("--url <url>", "Server URL").option("--email <email>", "Email address").option("--password <password>", "Password").option("--token <token>", "API key (hisaabo_key_...) for passwordless auth").action(async (opts) => {
3094
+ let apiUrl = opts.url;
3095
+ if (opts.token) {
3096
+ if (!apiUrl) {
3097
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
3098
+ const ask = (q) => new Promise((res) => rl.question(q, res));
3099
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
3100
+ const u = await ask(" Server URL [http://localhost:3000]: ");
3101
+ rl.close();
3102
+ apiUrl = u.trim() || "http://localhost:3000";
3103
+ }
3104
+ await loginWithToken(apiUrl, opts.token);
3105
+ return;
3106
+ }
3107
+ let email = opts.email;
3108
+ let password = opts.password;
3109
+ if (!apiUrl || !email || !password) {
3110
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
3111
+ const ask = (q) => new Promise((res) => rl.question(q, res));
3112
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
3113
+ if (!apiUrl) {
3114
+ const u = await ask(" Server URL [http://localhost:3000]: ");
3115
+ apiUrl = u.trim() || "http://localhost:3000";
3116
+ }
3117
+ if (!email) email = (await ask(" Email: ")).trim();
3118
+ if (!password) {
3119
+ password = (await ask(" Password: ")).trim();
3120
+ }
3121
+ rl.close();
3122
+ console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
3123
+ }
3124
+ await login(apiUrl, email, password);
3125
+ });
3126
+ program.command("logout").description("Log out and clear saved credentials").action(async () => {
3127
+ await logout();
3128
+ });
3129
+ program.command("whoami").description("Show current user and active business").option("--json", "JSON output").action(async (opts) => {
3130
+ await whoami(!!opts.json);
3131
+ });
3132
+ program.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
3133
+ const cfg = requireAuth();
3134
+ const client = new HisaaboClient(cfg);
3135
+ try {
3136
+ const businesses = await client.business.list();
3137
+ if (opts.json) {
3138
+ outputJSON(businesses);
3139
+ return;
3140
+ }
3141
+ businesses.forEach((b, i) => {
3142
+ const active = b.id === cfg.businessId ? " [active]" : "";
3143
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
3144
+ });
3145
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
3146
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
3147
+ rl.close();
3148
+ const idx = parseInt(answer.trim(), 10) - 1;
3149
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
3150
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
3151
+ setConfig({ businessId: selected.id, businessName: selected.name });
3152
+ success(`Switched to: ${selected.name}`);
3153
+ } catch (e) {
3154
+ if (e instanceof HisaaboApiError) {
3155
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3156
+ }
3157
+ fatalError(String(e instanceof Error ? e.message : e));
3158
+ }
3159
+ });
3160
+ program.command("dashboard").alias("dash").description("Show financial summary dashboard").option("--json", "JSON output").action(async (opts) => {
3161
+ await dashboardCommand({ json: opts.json });
3162
+ });
3163
+ var invoice = program.command("invoice").description("Invoice management");
3164
+ invoice.command("list").description("List invoices").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--type <type>", "sale or purchase").option("--status <status>", "Filter by status").option("--party <name>", "Filter by party name").option("--party-id <id>", "Filter by party ID").option("--from <date>", "From date (YYYY-MM-DD)").option("--to <date>", "To date (YYYY-MM-DD)").option("--this-month", "Filter to current month").option("--this-quarter", "Filter to current quarter").option("--this-fy", "Filter to current financial year").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).option("--search <q>", "Search invoices").option("--sort-by <field>", "Sort field: date, amount, number").option("--sort-dir <dir>", "Sort direction: asc, desc").action(async (opts) => {
3165
+ await invoiceListCommand({
3166
+ json: opts.json,
3167
+ format: opts.format,
3168
+ type: opts.type,
3169
+ status: opts.status,
3170
+ party: opts.party,
3171
+ partyId: opts.partyId,
3172
+ from: opts.from,
3173
+ to: opts.to,
3174
+ thisMonth: opts.thisMonth,
3175
+ thisQuarter: opts.thisQuarter,
3176
+ thisFy: opts.thisFy,
3177
+ page: opts.page,
3178
+ limit: opts.limit,
3179
+ search: opts.search,
3180
+ sortBy: opts.sortBy,
3181
+ sortDir: opts.sortDir
3182
+ });
3183
+ });
3184
+ invoice.command("get <id>").description("Get invoice details").option("--json", "JSON output").action(async (id, opts) => {
3185
+ await invoiceGetCommand(id, { json: opts.json });
3186
+ });
3187
+ invoice.command("create").description("Create a new invoice").option("--json", "JSON output").option("--party <name>", "Party name").option("--party-id <id>", "Party UUID").option("--type <type>", "sale or purchase").option("--item <name>", "Item (repeatable)", (v, a) => [...a, v], []).option("--qty <n>", "Quantity (per --item)", (v, a) => [...a, v], []).option("--rate <n>", "Unit price (per --item)", (v, a) => [...a, v], []).option("--delivery <method>", "Delivery method").option("--notes <text>", "Invoice notes").option("--terms <text>", "Terms and conditions").option("-y, --yes", "Skip confirmation prompts").action(async (opts) => {
3188
+ await invoiceCreateCommand({
3189
+ json: opts.json,
3190
+ party: opts.party,
3191
+ partyId: opts.partyId,
3192
+ type: opts.type,
3193
+ items: opts.item,
3194
+ qty: opts.qty,
3195
+ rate: opts.rate,
3196
+ delivery: opts.delivery,
3197
+ notes: opts.notes,
3198
+ terms: opts.terms,
3199
+ yes: opts.yes
3200
+ });
3201
+ });
3202
+ invoice.command("status <id> <status>").description("Update invoice status").option("--json", "JSON output").action(async (id, status, opts) => {
3203
+ await invoiceStatusCommand(id, status, { json: opts.json });
3204
+ });
3205
+ invoice.command("pdf <id>").description("Download invoice as PDF").option("--output <path>", "Output path or directory").option("--open", "Open after download").action(async (id, opts) => {
3206
+ await invoicePdfCommand(id, { output: opts.output, open: opts.open });
3207
+ });
3208
+ invoice.command("delete <id>").description("Delete an invoice").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3209
+ await invoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
3210
+ });
3211
+ var party = program.command("party").description("Party (customer/supplier) management");
3212
+ party.command("list").description("List parties").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--type <type>", "customer or supplier").option("--search <q>", "Search").option("--category <cat>", "Filter by category").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3213
+ await partyListCommand({
3214
+ json: opts.json,
3215
+ format: opts.format,
3216
+ type: opts.type,
3217
+ search: opts.search,
3218
+ category: opts.category,
3219
+ page: opts.page,
3220
+ limit: opts.limit
3221
+ });
3222
+ });
3223
+ party.command("get <id>").description("Get party details").option("--json", "JSON output").action(async (id, opts) => {
3224
+ await partyGetCommand(id, { json: opts.json });
3225
+ });
3226
+ party.command("create").description("Create a new party").option("--json", "JSON output").option("--type <type>", "customer or supplier").option("--name <name>", "Party name").option("--phone <phone>", "Phone number").option("--email <email>", "Email address").option("--gstin <gstin>", "GSTIN").option("--city <city>", "City").option("--category <cat>", "Category").option("-y, --yes", "Skip confirmation").action(async (opts) => {
3227
+ await partyCreateCommand(opts);
3228
+ });
3229
+ party.command("delete <id>").description("Delete a party").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3230
+ await partyDeleteCommand(id, { yes: opts.yes, json: opts.json });
3231
+ });
3232
+ party.command("ledger <partyId>").description("Show party ledger (debit/credit history)").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--from <date>", "From date").option("--to <date>", "To date").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (partyId, opts) => {
3233
+ await partyLedgerCommand(partyId, opts);
3234
+ });
3235
+ var item = program.command("item").description("Item / product management");
3236
+ item.command("list").description("List items").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--search <q>", "Search").option("--category <cat>", "Filter by category").option("--type <type>", "product or service").option("--low-stock", "Show only low-stock items").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3237
+ await itemListCommand({
3238
+ json: opts.json,
3239
+ format: opts.format,
3240
+ search: opts.search,
3241
+ category: opts.category,
3242
+ type: opts.type,
3243
+ lowStock: opts.lowStock,
3244
+ page: opts.page,
3245
+ limit: opts.limit
3246
+ });
3247
+ });
3248
+ item.command("get <id>").description("Get item details").option("--json", "JSON output").action(async (id, opts) => {
3249
+ const cfg = requireAuth();
3250
+ const client = new HisaaboClient(cfg);
3251
+ try {
3252
+ const it = await client.item.get(id);
3253
+ if (opts.json) {
3254
+ outputJSON(it);
3255
+ return;
3256
+ }
3257
+ console.log(`
3258
+ ${it.name} (${it.itemType})`);
3259
+ console.log(" " + "\u2500".repeat(40));
3260
+ if (it.sku) console.log(` SKU: ${it.sku}`);
3261
+ if (it.hsn) console.log(` HSN: ${it.hsn}`);
3262
+ console.log(` Unit: ${it.unit}`);
3263
+ if (it.salePrice) console.log(` Sale: \u20B9${it.salePrice}`);
3264
+ if (it.purchasePrice) console.log(` Purchase: \u20B9${it.purchasePrice}`);
3265
+ console.log(` Tax: ${it.taxPercent}%`);
3266
+ if (it.itemType === "product") console.log(` Stock: ${it.stockQuantity}`);
3267
+ console.log();
3268
+ } catch (e) {
3269
+ if (e instanceof HisaaboApiError && e.hisaaboError.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
3270
+ fatalError(String(e instanceof Error ? e.message : e));
3271
+ }
3272
+ });
3273
+ item.command("create").description("Create a new item").option("--json", "JSON output").option("--name <name>", "Item name").option("--unit <unit>", "Unit (pcs, kg, etc.)").option("--sale-price <price>", "Sale price").option("--purchase-price <price>", "Purchase price").option("--tax <percent>", "Tax percentage").option("--stock <qty>", "Opening stock quantity").option("--hsn <code>", "HSN code").option("--category <cat>", "Category").option("--type <type>", "product or service").option("-y, --yes", "Skip confirmation").action(async (opts) => {
3274
+ await itemCreateCommand({
3275
+ json: opts.json,
3276
+ name: opts.name,
3277
+ unit: opts.unit,
3278
+ salePrice: opts.salePrice,
3279
+ purchasePrice: opts.purchasePrice,
3280
+ taxPercent: opts.tax,
3281
+ stock: opts.stock,
3282
+ hsn: opts.hsn,
3283
+ category: opts.category,
3284
+ type: opts.type,
3285
+ yes: opts.yes
3286
+ });
3287
+ });
3288
+ item.command("delete <id>").description("Delete an item").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3289
+ await itemDeleteCommand(id, { yes: opts.yes, json: opts.json });
3290
+ });
3291
+ item.command("stock <id> <adjustment>").description("Adjust item stock (+10, -5, 100)").option("--json", "JSON output").option("--reason <text>", "Reason for adjustment").action(async (id, adjustment, opts) => {
3292
+ await itemStockCommand(id, adjustment, { json: opts.json, reason: opts.reason });
3293
+ });
3294
+ var payment = program.command("payment").description("Payment recording");
3295
+ payment.command("list").description("List payments").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--party-id <id>", "Filter by party").option("--from <date>", "From date").option("--to <date>", "To date").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3296
+ await paymentListCommand(opts);
3297
+ });
3298
+ payment.command("create").description("Record a payment").option("--json", "JSON output").option("--party-id <id>", "Party UUID").option("--party <name>", "Party name").option("--amount <amount>", "Payment amount").option("--mode <mode>", "cash/bank/upi/cheque/other").option("--invoice-id <id>", "Link to invoice").option("--reference <ref>", "Reference number").option("--date <date>", "Payment date").option("--notes <text>", "Notes").option("-y, --yes", "Skip confirmation").action(async (opts) => {
3299
+ await paymentCreateCommand({
3300
+ json: opts.json,
3301
+ partyId: opts.partyId,
3302
+ party: opts.party,
3303
+ amount: opts.amount,
3304
+ mode: opts.mode,
3305
+ invoiceId: opts.invoiceId,
3306
+ reference: opts.reference,
3307
+ date: opts.date,
3308
+ notes: opts.notes,
3309
+ yes: opts.yes
3310
+ });
3311
+ });
3312
+ payment.command("delete <id>").description("Delete a payment").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3313
+ await paymentDeleteCommand(id, { yes: opts.yes, json: opts.json });
3314
+ });
3315
+ var expense = program.command("expense").description("Expense tracking");
3316
+ expense.command("list").description("List expenses").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--category <cat>", "Filter by category").option("--from <date>", "From date").option("--to <date>", "To date").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3317
+ await expenseListCommand(opts);
3318
+ });
3319
+ expense.command("create").description("Create a new expense").option("--json", "JSON output").option("--category <cat>", "Expense category").option("--amount <amount>", "Amount").option("--mode <mode>", "cash/bank/upi/cheque/other").option("--description <text>", "Description").option("--date <date>", "Expense date").option("--reference <ref>", "Reference number").action(async (opts) => {
3320
+ await expenseCreateCommand({
3321
+ json: opts.json,
3322
+ category: opts.category,
3323
+ amount: opts.amount,
3324
+ mode: opts.mode,
3325
+ description: opts.description,
3326
+ date: opts.date,
3327
+ reference: opts.reference
3328
+ });
3329
+ });
3330
+ expense.command("delete <id>").description("Delete an expense").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3331
+ await expenseDeleteCommand(id, { yes: opts.yes, json: opts.json });
3332
+ });
3333
+ var gst = program.command("gst").description("GST reports");
3334
+ gst.command("r1").description("GSTR-1 report").option("--json", "JSON output").option("--quarter <q>", "Quarter: Q1, Q2, Q3, Q4").option("--month <n>", "Month number (1-12)", parseInt).option("--year <n>", "Year", parseInt).action(async (opts) => {
3335
+ await gstR1Command({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
3336
+ });
3337
+ gst.command("r3b").description("GSTR-3B report").option("--json", "JSON output").option("--quarter <q>", "Quarter: Q1, Q2, Q3, Q4").option("--month <n>", "Month number (1-12)", parseInt).option("--year <n>", "Year", parseInt).action(async (opts) => {
3338
+ await gstR3bCommand({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
3339
+ });
3340
+ gst.command("r1-csv").description("Download GSTR-1 as GSTN-compatible CSV").option("--quarter <q>", "Quarter").option("--month <n>", "Month", parseInt).option("--year <n>", "Year", parseInt).option("--output <path>", "Output file path").action(async (opts) => {
3341
+ await gstR1CsvCommand({ quarter: opts.quarter, month: opts.month, year: opts.year, output: opts.output });
3342
+ });
3343
+ var report = program.command("report").description("Business reports");
3344
+ report.command("daybook").description("Day book report (all transactions)").option("--json", "JSON output").option("--format <format>", "tsv or csv").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-month", "Current month").option("--this-fy", "Current financial year").action(async (opts) => {
3345
+ await reportDaybookCommand(opts);
3346
+ });
3347
+ report.command("outstanding").description("Outstanding receivables and payables").option("--json", "JSON output").option("--type <type>", "receivable, payable, or both").action(async (opts) => {
3348
+ await reportOutstandingCommand({ json: opts.json, type: opts.type });
3349
+ });
3350
+ report.command("tax-summary").description("Tax summary by rate").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-fy", "Current financial year").action(async (opts) => {
3351
+ await reportTaxSummaryCommand(opts);
3352
+ });
3353
+ report.command("item-sales").description("Item sales report").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-fy", "Current financial year").action(async (opts) => {
3354
+ await reportItemSalesCommand(opts);
3355
+ });
3356
+ report.command("stock").description("Stock summary report").option("--json", "JSON output").option("--category <cat>", "Filter by category").action(async (opts) => {
3357
+ await reportStockSummaryCommand({ json: opts.json, category: opts.category });
3358
+ });
3359
+ var bank = program.command("bank").description("Bank account management");
3360
+ bank.command("list").description("List bank accounts with balances").option("--json", "JSON output").action(async (opts) => {
3361
+ await bankListCommand({ json: opts.json });
3362
+ });
3363
+ bank.command("get <id>").description("Get bank account details").option("--json", "JSON output").action(async (id, opts) => {
3364
+ await bankGetCommand(id, { json: opts.json });
3365
+ });
3366
+ bank.command("create").description("Create a new bank account").option("--json", "JSON output").option("--name <name>", "Account name").option("--type <type>", "savings/current/cash/credit/other").option("--bank <name>", "Bank name").option("--account-number <num>", "Account number").option("--ifsc <code>", "IFSC code").option("--opening-balance <amount>", "Opening balance").option("--default", "Set as default account").option("-y, --yes", "Skip prompts").action(async (opts) => {
3367
+ await bankCreateCommand({
3368
+ json: opts.json,
3369
+ name: opts.name,
3370
+ type: opts.type,
3371
+ bank: opts.bank,
3372
+ accountNumber: opts.accountNumber,
3373
+ ifsc: opts.ifsc,
3374
+ openingBalance: opts.openingBalance,
3375
+ default: opts.default,
3376
+ yes: opts.yes
3377
+ });
3378
+ });
3379
+ bank.command("transfer").description("Transfer between bank accounts").option("--json", "JSON output").option("--from <id>", "Source account ID").option("--to <id>", "Destination account ID").option("--amount <amount>", "Transfer amount").option("--description <text>", "Description").option("--date <date>", "Transfer date").action(async (opts) => {
3380
+ await bankTransferCommand({
3381
+ json: opts.json,
3382
+ from: opts.from,
3383
+ to: opts.to,
3384
+ amount: opts.amount,
3385
+ description: opts.description,
3386
+ date: opts.date
3387
+ });
3388
+ });
3389
+ bank.command("transactions <accountId>").description("List transactions for a bank account").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (accountId, opts) => {
3390
+ await bankTransactionsCommand(accountId, {
3391
+ json: opts.json,
3392
+ from: opts.from,
3393
+ to: opts.to,
3394
+ page: opts.page,
3395
+ limit: opts.limit
3396
+ });
3397
+ });
3398
+ var shipment = program.command("shipment").description("Shipment tracking");
3399
+ shipment.command("list").description("List shipments").option("--json", "JSON output").option("--status <status>", "Filter by status").option("--invoice-id <id>", "Filter by invoice").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3400
+ await shipmentListCommand({
3401
+ json: opts.json,
3402
+ status: opts.status,
3403
+ invoiceId: opts.invoiceId,
3404
+ page: opts.page,
3405
+ limit: opts.limit
3406
+ });
3407
+ });
3408
+ shipment.command("get <id>").description("Get shipment details").option("--json", "JSON output").action(async (id, opts) => {
3409
+ await shipmentGetCommand(id, { json: opts.json });
3410
+ });
3411
+ shipment.command("create").description("Create a new shipment").option("--json", "JSON output").option("--invoice-id <id>", "Invoice ID").option("--party-id <id>", "Party ID").option("--carrier <name>", "Carrier name").option("--tracking <number>", "Tracking number").option("--mode <mode>", "Shipping mode").option("--date <date>", "Shipment date").action(async (opts) => {
3412
+ await shipmentCreateCommand({
3413
+ json: opts.json,
3414
+ invoiceId: opts.invoiceId,
3415
+ partyId: opts.partyId,
3416
+ carrier: opts.carrier,
3417
+ tracking: opts.tracking,
3418
+ mode: opts.mode,
3419
+ date: opts.date
3420
+ });
3421
+ });
3422
+ shipment.command("update <id>").description("Update shipment status or tracking").option("--json", "JSON output").option("--status <status>", "New status").option("--tracking <number>", "Tracking number").option("--carrier <name>", "Carrier").action(async (id, opts) => {
3423
+ await shipmentUpdateCommand(id, {
3424
+ json: opts.json,
3425
+ status: opts.status,
3426
+ tracking: opts.tracking,
3427
+ carrier: opts.carrier
3428
+ });
3429
+ });
3430
+ var target = program.command("target").description("Sales target management");
3431
+ target.command("list").description("List sales targets").option("--json", "JSON output").action(async (opts) => {
3432
+ await targetListCommand({ json: opts.json });
3433
+ });
3434
+ target.command("my").description("Show my target progress").option("--json", "JSON output").action(async (opts) => {
3435
+ await targetMyCommand({ json: opts.json });
3436
+ });
3437
+ target.command("create").description("Create a new sales target").option("--json", "JSON output").option("--type <type>", "order_count, order_value, or item_quantity").option("--period <period>", "daily, weekly, monthly, quarterly, or custom").option("--value <n>", "Target value").option("--start-date <date>", "Start date").option("--end-date <date>", "End date").option("--notes <text>", "Notes").action(async (opts) => {
3438
+ await targetCreateCommand({
3439
+ json: opts.json,
3440
+ type: opts.type,
3441
+ period: opts.period,
3442
+ value: opts.value,
3443
+ startDate: opts.startDate,
3444
+ endDate: opts.endDate,
3445
+ notes: opts.notes
3446
+ });
3447
+ });
3448
+ var store = program.command("store").description("Online store management");
3449
+ store.command("settings").description("Show store settings").option("--json", "JSON output").action(async (opts) => {
3450
+ await storeSettingsCommand({ json: opts.json });
3451
+ });
3452
+ store.command("orders").description("List store orders").option("--json", "JSON output").option("--status <status>", "Filter by order status").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3453
+ await storeOrdersCommand({
3454
+ json: opts.json,
3455
+ status: opts.status,
3456
+ page: opts.page,
3457
+ limit: opts.limit
3458
+ });
3459
+ });
3460
+ var importCmd = program.command("import").description("Bulk import data");
3461
+ importCmd.command("parties <file>").description("Import parties from JSON or CSV file").option("--json", "JSON output").option("--format <format>", "json or csv (auto-detected from extension)").action(async (file, opts) => {
3462
+ await importPartiesCommand(file, { json: opts.json, format: opts.format });
3463
+ });
3464
+ importCmd.command("items <file>").description("Import items from JSON or CSV file").option("--json", "JSON output").option("--format <format>", "json or csv (auto-detected from extension)").action(async (file, opts) => {
3465
+ await importItemsCommand(file, { json: opts.json, format: opts.format });
3466
+ });
3467
+ var business = program.command("business").description("Business management");
3468
+ business.command("list").description("List all businesses").option("--json", "JSON output").action(async (opts) => {
3469
+ const cfg = requireAuth();
3470
+ const client = new HisaaboClient(cfg);
3471
+ try {
3472
+ const businesses = await client.business.list();
3473
+ if (opts.json) {
3474
+ outputJSON(businesses);
3475
+ return;
3476
+ }
3477
+ businesses.forEach((b, i) => {
3478
+ const active = b.id === cfg.businessId ? " [active]" : "";
3479
+ console.log(` ${i + 1} ${b.name.padEnd(30)} ${(b.gstin ?? "-").padEnd(18)} ${b.gstRegistrationType}${active}`);
3480
+ });
3481
+ console.log();
3482
+ } catch (e) {
3483
+ fatalError(String(e instanceof Error ? e.message : e));
3484
+ }
3485
+ });
3486
+ business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
3487
+ const cfg = requireAuth();
3488
+ const client = new HisaaboClient(cfg);
3489
+ try {
3490
+ const businesses = await client.business.list();
3491
+ if (opts.json) {
3492
+ outputJSON(businesses);
3493
+ return;
3494
+ }
3495
+ businesses.forEach((b, i) => {
3496
+ const active = b.id === cfg.businessId ? " [active]" : "";
3497
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
3498
+ });
3499
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
3500
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
3501
+ rl.close();
3502
+ const idx = parseInt(answer.trim(), 10) - 1;
3503
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
3504
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
3505
+ setConfig({ businessId: selected.id, businessName: selected.name });
3506
+ success(`Switched to: ${selected.name}`);
3507
+ } catch (e) {
3508
+ if (e instanceof HisaaboApiError) {
3509
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3510
+ }
3511
+ fatalError(String(e instanceof Error ? e.message : e));
3512
+ }
3513
+ });
3514
+ program.parseAsync(process.argv).catch((err) => {
3515
+ fatalError(String(err instanceof Error ? err.message : err));
3516
+ });