@hisaabo/cli 0.1.0 → 0.3.2

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 (146) hide show
  1. package/README.md +332 -0
  2. package/dist/bin/audit-trail-2YGXGUXW.js +78 -0
  3. package/dist/bin/categories-P5VFWD5F.js +47 -0
  4. package/dist/bin/check-slug-4TMOTWUJ.js +65 -0
  5. package/dist/bin/chunk-2P35S2C3.js +46 -0
  6. package/dist/bin/chunk-EYNDY7RB.js +175 -0
  7. package/dist/bin/chunk-FFBG6RU4.js +156 -0
  8. package/dist/bin/chunk-FTOBDKMO.js +804 -0
  9. package/dist/bin/client-QNJ2H5CW.js +11 -0
  10. package/dist/bin/collection-efficiency-WMKEGS6U.js +165 -0
  11. package/dist/bin/config-UKVQYPPR.js +18 -0
  12. package/dist/bin/create-Y22FAVOW.js +83 -0
  13. package/dist/bin/default-account-SA56M66A.js +58 -0
  14. package/dist/bin/expenses-VZAOLYUW.js +89 -0
  15. package/dist/bin/export-QZ6WT6PJ.js +59 -0
  16. package/dist/bin/factory-2DCU3B5T.js +483 -0
  17. package/dist/bin/get-6UYP6UVD.js +71 -0
  18. package/dist/bin/get-EXL44I2X.js +66 -0
  19. package/dist/bin/hisaabo.js +2029 -1450
  20. package/dist/bin/invite-O26SAL72.js +53 -0
  21. package/dist/bin/invoice-breakdown-XEATXVMR.js +97 -0
  22. package/dist/bin/items-3U5USBVG.js +62 -0
  23. package/dist/bin/items-toggle-YEKMI2CM.js +46 -0
  24. package/dist/bin/list-FX2C3NCL.js +46 -0
  25. package/dist/bin/list-VBAHY72W.js +79 -0
  26. package/dist/bin/members-5FPRUAB6.js +55 -0
  27. package/dist/bin/monthly-comparison-JEJ3TTY2.js +176 -0
  28. package/dist/bin/order-cancel-XI2LKYXV.js +55 -0
  29. package/dist/bin/order-confirm-HUFCU6MO.js +53 -0
  30. package/dist/bin/order-get-NSDMPUZR.js +88 -0
  31. package/dist/bin/order-update-C7QYSD5R.js +60 -0
  32. package/dist/bin/output-QFLEKG5W.js +35 -0
  33. package/dist/bin/payment-modes-WI3AWSES.js +126 -0
  34. package/dist/bin/profit-loss-5RIEOBKP.js +135 -0
  35. package/dist/bin/receivables-aging-L6DIQCNE.js +161 -0
  36. package/dist/bin/remove-M2B4TZ37.js +52 -0
  37. package/dist/bin/revoke-H3V2GNCD.js +52 -0
  38. package/dist/bin/sales-trend-TICB3KGF.js +71 -0
  39. package/dist/bin/sequence-XUD6FAKY.js +66 -0
  40. package/dist/bin/store-UQ2DDQ5I.js +82 -0
  41. package/dist/bin/summary-BPNFC7I2.js +113 -0
  42. package/dist/bin/top-customers-WGGJWKCN.js +81 -0
  43. package/dist/bin/top-items-C7ZDDJMR.js +84 -0
  44. package/dist/bin/top-outstanding-MOGWJIQS.js +64 -0
  45. package/dist/bin/unpaid-invoices-ZUPNMQJP.js +65 -0
  46. package/dist/bin/untracked-BCJEVDW4.js +67 -0
  47. package/dist/bin/update-HIU4PANX.js +54 -0
  48. package/dist/bin/update-IG565YIN.js +61 -0
  49. package/dist/bin/update-PVLAX7T3.js +57 -0
  50. package/dist/bin/update-role-Q4ZYJRYT.js +45 -0
  51. package/dist/bin/update-settings-XPC6L5WM.js +56 -0
  52. package/package.json +6 -1
  53. package/src/bin/hisaabo.ts +42 -933
  54. package/src/bin/registrars/api-key.ts +44 -0
  55. package/src/bin/registrars/auth.ts +153 -0
  56. package/src/bin/registrars/automated-invoice.ts +167 -0
  57. package/src/bin/registrars/bank.ts +90 -0
  58. package/src/bin/registrars/business.ts +120 -0
  59. package/src/bin/registrars/dashboard.ts +225 -0
  60. package/src/bin/registrars/document.ts +184 -0
  61. package/src/bin/registrars/expense.ts +87 -0
  62. package/src/bin/registrars/gst.ts +41 -0
  63. package/src/bin/registrars/import.ts +49 -0
  64. package/src/bin/registrars/invoice.ts +117 -0
  65. package/src/bin/registrars/item.ts +112 -0
  66. package/src/bin/registrars/party.ts +81 -0
  67. package/src/bin/registrars/payment.ts +128 -0
  68. package/src/bin/registrars/report.ts +142 -0
  69. package/src/bin/registrars/shipment.ts +74 -0
  70. package/src/bin/registrars/store.ts +128 -0
  71. package/src/bin/registrars/target.ts +46 -0
  72. package/src/bin/registrars/tenant.ts +55 -0
  73. package/src/client.ts +495 -4
  74. package/src/commands/api-key/create.ts +72 -0
  75. package/src/commands/api-key/list.ts +71 -0
  76. package/src/commands/api-key/revoke.ts +46 -0
  77. package/src/commands/automated-invoice/create.ts +85 -0
  78. package/src/commands/automated-invoice/delete.ts +42 -0
  79. package/src/commands/automated-invoice/get.ts +113 -0
  80. package/src/commands/automated-invoice/history.ts +65 -0
  81. package/src/commands/automated-invoice/index.ts +11 -0
  82. package/src/commands/automated-invoice/list.ts +91 -0
  83. package/src/commands/automated-invoice/pause.ts +29 -0
  84. package/src/commands/automated-invoice/resume.ts +29 -0
  85. package/src/commands/automated-invoice/run-now.ts +29 -0
  86. package/src/commands/automated-invoice/suggestions.ts +68 -0
  87. package/src/commands/automated-invoice/update.ts +54 -0
  88. package/src/commands/automated-invoice/usage.ts +68 -0
  89. package/src/commands/business/audit-trail.ts +79 -0
  90. package/src/commands/business/export.ts +52 -0
  91. package/src/commands/business/get.ts +55 -0
  92. package/src/commands/business/sequence.ts +65 -0
  93. package/src/commands/business/update.ts +64 -0
  94. package/src/commands/dashboard/collection-efficiency.ts +164 -0
  95. package/src/commands/dashboard/expenses.ts +76 -0
  96. package/src/commands/dashboard/invoice-breakdown.ts +89 -0
  97. package/src/commands/dashboard/monthly-comparison.ts +193 -0
  98. package/src/commands/dashboard/payment-modes.ts +121 -0
  99. package/src/commands/dashboard/profit-loss.ts +146 -0
  100. package/src/commands/dashboard/receivables-aging.ts +169 -0
  101. package/src/commands/dashboard/sales-trend.ts +68 -0
  102. package/src/commands/dashboard/summary.ts +105 -0
  103. package/src/commands/dashboard/top-customers.ts +70 -0
  104. package/src/commands/dashboard/top-items.ts +74 -0
  105. package/src/commands/dashboard/top-outstanding.ts +61 -0
  106. package/src/commands/document/factory.ts +590 -0
  107. package/src/commands/expense/categories.ts +40 -0
  108. package/src/commands/expense/update.ts +58 -0
  109. package/src/commands/import/index.ts +68 -0
  110. package/src/commands/item/categories.ts +40 -0
  111. package/src/commands/item/low-stock-count.ts +32 -0
  112. package/src/commands/item/merge.ts +53 -0
  113. package/src/commands/item/price-history.ts +59 -0
  114. package/src/commands/item/rename-unit.ts +39 -0
  115. package/src/commands/item/sales-stats.ts +44 -0
  116. package/src/commands/item/stock-history.ts +70 -0
  117. package/src/commands/item/switch-base-unit.ts +42 -0
  118. package/src/commands/item/update.ts +59 -0
  119. package/src/commands/item/variants-create.ts +58 -0
  120. package/src/commands/item/variants-delete.ts +47 -0
  121. package/src/commands/item/variants-list.ts +63 -0
  122. package/src/commands/item/variants-update.ts +61 -0
  123. package/src/commands/party/ledger-report.ts +81 -0
  124. package/src/commands/party/merge.ts +50 -0
  125. package/src/commands/party/stats.ts +40 -0
  126. package/src/commands/party/top-items.ts +57 -0
  127. package/src/commands/party/update.ts +65 -0
  128. package/src/commands/payment/default-account.ts +56 -0
  129. package/src/commands/payment/get.ts +59 -0
  130. package/src/commands/payment/unpaid-invoices.ts +69 -0
  131. package/src/commands/payment/untracked.ts +70 -0
  132. package/src/commands/payment/update.ts +54 -0
  133. package/src/commands/report/index.ts +348 -1
  134. package/src/commands/store/check-slug.ts +48 -0
  135. package/src/commands/store/items-toggle.ts +41 -0
  136. package/src/commands/store/items.ts +61 -0
  137. package/src/commands/store/order-cancel.ts +48 -0
  138. package/src/commands/store/order-confirm.ts +45 -0
  139. package/src/commands/store/order-get.ts +66 -0
  140. package/src/commands/store/order-update.ts +52 -0
  141. package/src/commands/store/update-settings.ts +52 -0
  142. package/src/commands/tenant/invite.ts +57 -0
  143. package/src/commands/tenant/list.ts +46 -0
  144. package/src/commands/tenant/members.ts +55 -0
  145. package/src/commands/tenant/remove.ts +47 -0
  146. package/src/commands/tenant/update-role.ts +41 -0
@@ -0,0 +1,54 @@
1
+ import { HisaaboClient, HisaaboApiError, type PaymentUpdateInput } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
4
+ import { formatINR } from "../../format.js";
5
+
6
+ interface UpdateOpts {
7
+ json?: boolean;
8
+ amount?: string;
9
+ mode?: string;
10
+ date?: string;
11
+ reference?: string;
12
+ notes?: string;
13
+ }
14
+
15
+ export async function paymentUpdateCommand(id: string, opts: UpdateOpts): Promise<void> {
16
+ const cfg = requireAuth();
17
+ const client = new HisaaboClient(cfg);
18
+
19
+ // Build update payload — only send fields explicitly provided
20
+ const input: PaymentUpdateInput = { id };
21
+
22
+ if (opts.amount !== undefined) input.amount = opts.amount;
23
+ if (opts.mode !== undefined) input.mode = opts.mode as PaymentUpdateInput["mode"];
24
+ if (opts.date !== undefined) input.paymentDate = opts.date;
25
+ if (opts.reference !== undefined) input.referenceNumber = opts.reference || null;
26
+ if (opts.notes !== undefined) input.notes = opts.notes || null;
27
+
28
+ const hasUpdates = Object.keys(input).length > 1;
29
+ if (!hasUpdates) {
30
+ fatalError("No fields to update. Provide at least one option: --amount, --mode, --date, --reference, --notes", EXIT.USAGE);
31
+ }
32
+
33
+ try {
34
+ const payment = await client.payment.update(input);
35
+
36
+ if (opts.json) {
37
+ outputJSON(payment);
38
+ return;
39
+ }
40
+
41
+ success(`Updated: ${payment.paymentNumber} — ${formatINR(payment.amount)}`);
42
+
43
+ } catch (e) {
44
+ if (e instanceof HisaaboApiError) {
45
+ const err = e.hisaaboError;
46
+ if (err.code === "not_found") fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
47
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
48
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
49
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
50
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
51
+ }
52
+ fatalError(String(e instanceof Error ? e.message : e));
53
+ }
54
+ }
@@ -3,7 +3,7 @@ import { requireAuth } from "../../config.js";
3
3
  import {
4
4
  fatalError, outputJSON, outputTable, outputTSV, outputCSV, EXIT, type ColumnDef,
5
5
  } from "../../output.js";
6
- import { formatAmount, formatDate, todayISO, fyStart, monthStart, monthEnd } from "../../format.js";
6
+ import { formatAmount, formatDate, formatStatus, todayISO, fyStart, monthStart, monthEnd } from "../../format.js";
7
7
 
8
8
  interface ReportOpts {
9
9
  json?: boolean;
@@ -216,3 +216,350 @@ export async function reportStockSummaryCommand(opts: { json?: boolean; category
216
216
  fatalError(String(e instanceof Error ? e.message : e));
217
217
  }
218
218
  }
219
+
220
+ // ── Sales Register ─────────────────────────────────────────────────────────
221
+
222
+ interface RegisterRow {
223
+ date?: string;
224
+ invoiceDate?: string;
225
+ invoiceNumber?: string;
226
+ number?: string;
227
+ partyName?: string;
228
+ party?: string;
229
+ subtotal?: string;
230
+ taxAmount?: string;
231
+ tax?: string;
232
+ total?: string;
233
+ totalAmount?: string;
234
+ status?: string;
235
+ [key: string]: unknown;
236
+ }
237
+
238
+ export async function reportSalesRegisterCommand(
239
+ opts: ReportOpts & { partyId?: string },
240
+ ): Promise<void> {
241
+ const cfg = requireAuth();
242
+ const client = new HisaaboClient(cfg);
243
+ const { from, to } = resolveRange(opts);
244
+
245
+ try {
246
+ const result = await client.reports.salesRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
247
+
248
+ if (opts.json) {
249
+ outputJSON(result);
250
+ return;
251
+ }
252
+
253
+ console.log(`\n Sales Register ${from} → ${to}\n`);
254
+ console.log(` ${"═".repeat(80)}\n`);
255
+
256
+ const rows: RegisterRow[] = Array.isArray(result) ? result
257
+ : Array.isArray(result.rows) ? result.rows
258
+ : Array.isArray(result.invoices) ? result.invoices
259
+ : [];
260
+
261
+ const cols: ColumnDef<RegisterRow>[] = [
262
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
263
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
264
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
265
+ { key: "subtotal", header: "Subtotal (₹)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
266
+ { key: "taxAmount", header: "Tax (₹)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
267
+ { key: "total", header: "Total (₹)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
268
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) },
269
+ ];
270
+
271
+ if (opts.format === "tsv") outputTSV(rows, cols);
272
+ else if (opts.format === "csv") outputCSV(rows, cols);
273
+ else outputTable(rows, cols);
274
+
275
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
276
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
277
+ console.log(`\n Total: ${formatAmount(String(total)).padStart(14)}\n`);
278
+ }
279
+
280
+ } catch (e) {
281
+ if (e instanceof HisaaboApiError) {
282
+ const err = e.hisaaboError;
283
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
284
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
285
+ }
286
+ fatalError(String(e instanceof Error ? e.message : e));
287
+ }
288
+ }
289
+
290
+ // ── Purchase Register ──────────────────────────────────────────────────────
291
+
292
+ export async function reportPurchaseRegisterCommand(
293
+ opts: ReportOpts & { partyId?: string },
294
+ ): Promise<void> {
295
+ const cfg = requireAuth();
296
+ const client = new HisaaboClient(cfg);
297
+ const { from, to } = resolveRange(opts);
298
+
299
+ try {
300
+ const result = await client.reports.purchaseRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
301
+
302
+ if (opts.json) {
303
+ outputJSON(result);
304
+ return;
305
+ }
306
+
307
+ console.log(`\n Purchase Register ${from} → ${to}\n`);
308
+ console.log(` ${"═".repeat(80)}\n`);
309
+
310
+ const rows: RegisterRow[] = Array.isArray(result) ? result
311
+ : Array.isArray(result.rows) ? result.rows
312
+ : Array.isArray(result.invoices) ? result.invoices
313
+ : [];
314
+
315
+ const cols: ColumnDef<RegisterRow>[] = [
316
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
317
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
318
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
319
+ { key: "subtotal", header: "Subtotal (₹)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
320
+ { key: "taxAmount", header: "Tax (₹)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
321
+ { key: "total", header: "Total (₹)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
322
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) },
323
+ ];
324
+
325
+ if (opts.format === "tsv") outputTSV(rows, cols);
326
+ else if (opts.format === "csv") outputCSV(rows, cols);
327
+ else outputTable(rows, cols);
328
+
329
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
330
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
331
+ console.log(`\n Total: ${formatAmount(String(total)).padStart(14)}\n`);
332
+ }
333
+
334
+ } catch (e) {
335
+ if (e instanceof HisaaboApiError) {
336
+ const err = e.hisaaboError;
337
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
338
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
339
+ }
340
+ fatalError(String(e instanceof Error ? e.message : e));
341
+ }
342
+ }
343
+
344
+ // ── Party Statement ────────────────────────────────────────────────────────
345
+
346
+ interface StatementRow {
347
+ date?: string;
348
+ type?: string;
349
+ entryType?: string;
350
+ number?: string;
351
+ invoiceNumber?: string;
352
+ debit?: string;
353
+ credit?: string;
354
+ balance?: string;
355
+ runningBalance?: string;
356
+ [key: string]: unknown;
357
+ }
358
+
359
+ export async function reportPartyStatementCommand(
360
+ partyId: string,
361
+ opts: ReportOpts,
362
+ ): Promise<void> {
363
+ const cfg = requireAuth();
364
+ const client = new HisaaboClient(cfg);
365
+ const { from, to } = resolveRange(opts);
366
+
367
+ try {
368
+ const result = await client.reports.partyStatement({ partyId, fromDate: from, toDate: to });
369
+
370
+ if (opts.json) {
371
+ outputJSON(result);
372
+ return;
373
+ }
374
+
375
+ const res = result as Record<string, unknown>;
376
+ const partyName = String(res["partyName"] ?? res["party"] ?? partyId);
377
+ console.log(`\n Party Statement — ${partyName} ${from} → ${to}\n`);
378
+ console.log(` ${"═".repeat(75)}\n`);
379
+
380
+ const openingBalance = String(res["openingBalance"] ?? "0");
381
+ console.log(` Opening Balance: ${formatAmount(openingBalance).padStart(14)}\n`);
382
+
383
+ const rows: StatementRow[] = Array.isArray(res["entries"]) ? res["entries"] as StatementRow[]
384
+ : Array.isArray(res["rows"]) ? res["rows"] as StatementRow[]
385
+ : [];
386
+
387
+ const cols: ColumnDef<StatementRow>[] = [
388
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? v ?? "")) },
389
+ { key: "type", header: "Type", width: 12, format: (v, r) => String(r.type ?? r.entryType ?? v ?? "-") },
390
+ { key: "number", header: "Number", width: 14, format: (v, r) => String(r.number ?? r.invoiceNumber ?? v ?? "-") },
391
+ { key: "debit", header: "Debit (₹)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.debit ?? v ?? "0")) !== 0 ? formatAmount(String(r.debit ?? v)) : "-" },
392
+ { key: "credit", header: "Credit (₹)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.credit ?? v ?? "0")) !== 0 ? formatAmount(String(r.credit ?? v)) : "-" },
393
+ { key: "balance", header: "Balance (₹)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.balance ?? r.runningBalance ?? v ?? "0")) },
394
+ ];
395
+
396
+ if (opts.format === "tsv") outputTSV(rows, cols);
397
+ else if (opts.format === "csv") outputCSV(rows, cols);
398
+ else outputTable(rows, cols);
399
+
400
+ if (opts.format !== "tsv" && opts.format !== "csv") {
401
+ const closingBalance = String(res["closingBalance"] ?? res["balance"] ?? "0");
402
+ console.log(`\n Closing Balance: ${formatAmount(closingBalance).padStart(14)}\n`);
403
+ }
404
+
405
+ } catch (e) {
406
+ if (e instanceof HisaaboApiError) {
407
+ const err = e.hisaaboError;
408
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
409
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
410
+ }
411
+ fatalError(String(e instanceof Error ? e.message : e));
412
+ }
413
+ }
414
+
415
+ // ── Payment Summary ────────────────────────────────────────────────────────
416
+
417
+ export async function reportPaymentSummaryCommand(
418
+ opts: ReportOpts & { type?: string },
419
+ ): Promise<void> {
420
+ const cfg = requireAuth();
421
+ const client = new HisaaboClient(cfg);
422
+ const { from, to } = resolveRange(opts);
423
+
424
+ try {
425
+ const result = await client.reports.paymentSummary({
426
+ fromDate: from,
427
+ toDate: to,
428
+ type: opts.type as "received" | "made" | "both" | undefined ?? "both",
429
+ });
430
+
431
+ if (opts.json) {
432
+ outputJSON(result);
433
+ return;
434
+ }
435
+
436
+ const res = result as Record<string, unknown>;
437
+ console.log(`\n Payment Summary ${from} → ${to}\n`);
438
+ console.log(" " + "═".repeat(60) + "\n");
439
+
440
+ const received = String(res["totalReceived"] ?? res["received"] ?? "0");
441
+ const made = String(res["totalMade"] ?? res["made"] ?? "0");
442
+ const net = String(res["net"] ?? res["netCash"] ?? "0");
443
+
444
+ console.log(` Total Received: ${formatAmount(received).padStart(14)}`);
445
+ console.log(` Total Made: ${formatAmount(made).padStart(14)}`);
446
+ console.log(` Net: ${formatAmount(net).padStart(14)}`);
447
+
448
+ const breakdown = res["breakdown"] ?? res["byMode"] ?? res["modes"];
449
+ if (breakdown && Array.isArray(breakdown)) {
450
+ console.log(`\n By Payment Mode:\n`);
451
+ (breakdown as Array<Record<string, unknown>>).forEach((row) => {
452
+ const mode = String(row["mode"] ?? row["paymentMode"] ?? "-").padEnd(18);
453
+ const amount = formatAmount(String(row["amount"] ?? row["total"] ?? "0")).padStart(14);
454
+ console.log(` ${mode} ${amount}`);
455
+ });
456
+ }
457
+ console.log();
458
+
459
+ } catch (e) {
460
+ if (e instanceof HisaaboApiError) {
461
+ const err = e.hisaaboError;
462
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
463
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
464
+ }
465
+ fatalError(String(e instanceof Error ? e.message : e));
466
+ }
467
+ }
468
+
469
+ // ── Cash Flow Forecast ─────────────────────────────────────────────────────
470
+
471
+ export async function reportCashFlowCommand(opts: { json?: boolean }): Promise<void> {
472
+ const cfg = requireAuth();
473
+ const client = new HisaaboClient(cfg);
474
+
475
+ try {
476
+ const result = await client.reports.cashFlowForecast();
477
+
478
+ if (opts.json) {
479
+ outputJSON(result);
480
+ return;
481
+ }
482
+
483
+ const res = result as Record<string, unknown>;
484
+ console.log("\n Cash Flow Forecast\n");
485
+ console.log(" " + "═".repeat(60) + "\n");
486
+
487
+ const currentBalance = String(res["currentBalance"] ?? res["balance"] ?? "0");
488
+ const avgDailyExpenses = String(res["avgDailyExpenses"] ?? res["dailyBurn"] ?? "0");
489
+
490
+ console.log(` Current Balance: ${formatAmount(currentBalance).padStart(14)}`);
491
+ console.log(` Avg Daily Expenses: ${formatAmount(avgDailyExpenses).padStart(14)}`);
492
+
493
+ const forecasts = res["forecasts"] ?? res["forecast"];
494
+ if (forecasts && Array.isArray(forecasts)) {
495
+ console.log(`\n Forecast:\n`);
496
+ (forecasts as Array<Record<string, unknown>>).forEach((f) => {
497
+ const days = String(f["days"] ?? f["day"] ?? "-");
498
+ const balance = formatAmount(String(f["balance"] ?? f["amount"] ?? "0")).padStart(14);
499
+ console.log(` ${`${days}d`.padEnd(6)} ${balance}`);
500
+ });
501
+ } else {
502
+ // Fall back to computing from balance and daily burn if no forecasts array
503
+ const current = parseFloat(currentBalance);
504
+ const daily = parseFloat(avgDailyExpenses);
505
+ if (!isNaN(current) && !isNaN(daily)) {
506
+ console.log(`\n Forecast:\n`);
507
+ for (const days of [7, 14, 30]) {
508
+ const projected = current - daily * days;
509
+ console.log(` ${`${days}d`.padEnd(6)} ${formatAmount(String(projected)).padStart(14)}`);
510
+ }
511
+ }
512
+ }
513
+ console.log();
514
+
515
+ } catch (e) {
516
+ if (e instanceof HisaaboApiError) {
517
+ const err = e.hisaaboError;
518
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
519
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
520
+ }
521
+ fatalError(String(e instanceof Error ? e.message : e));
522
+ }
523
+ }
524
+
525
+ // ── Collection Efficiency ──────────────────────────────────────────────────
526
+
527
+ export async function reportCollectionEfficiencyCommand(opts: ReportOpts): Promise<void> {
528
+ const cfg = requireAuth();
529
+ const client = new HisaaboClient(cfg);
530
+ const { from, to } = resolveRange(opts);
531
+
532
+ try {
533
+ const result = await client.reports.collectionEfficiency({ fromDate: from, toDate: to });
534
+
535
+ if (opts.json) {
536
+ outputJSON(result);
537
+ return;
538
+ }
539
+
540
+ const res = result as Record<string, unknown>;
541
+ console.log(`\n Collection Efficiency ${from} → ${to}\n`);
542
+ console.log(" " + "═".repeat(60) + "\n");
543
+
544
+ const rate = String(res["collectionRate"] ?? res["rate"] ?? "0");
545
+ const dso = String(res["dso"] ?? res["daysSalesOutstanding"] ?? "-");
546
+ const paidOnTime = String(res["paidOnTime"] ?? res["onTimeCount"] ?? "-");
547
+ const totalInvoiced = String(res["totalInvoiced"] ?? res["invoiced"] ?? "-");
548
+
549
+ console.log(` Collection Rate: ${(parseFloat(rate)).toFixed(1).padStart(8)}%`);
550
+ console.log(` DSO (Days): ${dso.padStart(8)}`);
551
+ console.log(` Paid On Time: ${paidOnTime.padStart(8)}`);
552
+ if (totalInvoiced !== "-") {
553
+ console.log(` Total Invoiced: ${formatAmount(totalInvoiced).padStart(14)}`);
554
+ }
555
+ console.log();
556
+
557
+ } catch (e) {
558
+ if (e instanceof HisaaboApiError) {
559
+ const err = e.hisaaboError;
560
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
561
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
562
+ }
563
+ fatalError(String(e instanceof Error ? e.message : e));
564
+ }
565
+ }
@@ -0,0 +1,48 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, hasColor } from "../../output.js";
4
+ import chalk from "chalk";
5
+
6
+ export async function storeCheckSlugCommand(
7
+ slug: string,
8
+ opts: { json?: boolean },
9
+ ): Promise<void> {
10
+ const cfg = requireAuth();
11
+ const client = new HisaaboClient(cfg);
12
+
13
+ try {
14
+ const result = await client.store.checkSlug({ slug });
15
+
16
+ if (opts.json) {
17
+ outputJSON(result);
18
+ return;
19
+ }
20
+
21
+ const available =
22
+ typeof result === "object" && result !== null
23
+ ? (result as Record<string, unknown>)["available"]
24
+ : result;
25
+
26
+ if (available) {
27
+ if (hasColor()) {
28
+ process.stdout.write(chalk.green(`\n ✓ "${slug}" is available\n\n`));
29
+ } else {
30
+ process.stdout.write(`\n OK: "${slug}" is available\n\n`);
31
+ }
32
+ } else {
33
+ if (hasColor()) {
34
+ process.stdout.write(chalk.red(`\n ✗ "${slug}" is already taken\n\n`));
35
+ } else {
36
+ process.stdout.write(`\n TAKEN: "${slug}" is already taken\n\n`);
37
+ }
38
+ }
39
+ } catch (e) {
40
+ if (e instanceof HisaaboApiError) {
41
+ const err = e.hisaaboError;
42
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
43
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
44
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
45
+ }
46
+ fatalError(String(e instanceof Error ? e.message : e));
47
+ }
48
+ }
@@ -0,0 +1,41 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { outputJSON, EXIT, fatalError, success } from "../../output.js";
4
+
5
+ export async function storeItemsToggleCommand(opts: {
6
+ enable?: string;
7
+ disable?: string;
8
+ json?: boolean;
9
+ }): Promise<void> {
10
+ const cfg = requireAuth();
11
+ const client = new HisaaboClient(cfg);
12
+
13
+ if (!opts.enable && !opts.disable) {
14
+ fatalError("At least one of --enable or --disable is required", EXIT.USAGE);
15
+ }
16
+
17
+ const enableIds = opts.enable ? opts.enable.split(",").map((s) => s.trim()).filter(Boolean) : [];
18
+ const disableIds = opts.disable ? opts.disable.split(",").map((s) => s.trim()).filter(Boolean) : [];
19
+
20
+ try {
21
+ const result = await client.store.bulkToggleItems({ enable: enableIds, disable: disableIds });
22
+
23
+ if (opts.json) {
24
+ outputJSON(result);
25
+ return;
26
+ }
27
+
28
+ if (enableIds.length > 0) success(`Enabled ${enableIds.length} item(s)`);
29
+ if (disableIds.length > 0) success(`Disabled ${disableIds.length} item(s)`);
30
+ console.log();
31
+
32
+ } catch (e) {
33
+ if (e instanceof HisaaboApiError) {
34
+ const err = e.hisaaboError;
35
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
36
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
37
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
38
+ }
39
+ fatalError(String(e instanceof Error ? e.message : e));
40
+ }
41
+ }
@@ -0,0 +1,61 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import {
4
+ outputJSON, outputTable, outputTSV, outputCSV, EXIT, fatalError, type ColumnDef,
5
+ } from "../../output.js";
6
+ import { formatAmount } from "../../format.js";
7
+
8
+ interface StoreItem {
9
+ id: string;
10
+ name: string;
11
+ price: string;
12
+ enabled: boolean;
13
+ stock: number | null;
14
+ [key: string]: unknown;
15
+ }
16
+
17
+ export async function storeItemsCommand(opts: {
18
+ json?: boolean;
19
+ format?: string;
20
+ }): Promise<void> {
21
+ const cfg = requireAuth();
22
+ const client = new HisaaboClient(cfg);
23
+
24
+ try {
25
+ const items: StoreItem[] = await client.store.listStoreItems({});
26
+
27
+ if (opts.json) {
28
+ outputJSON(items);
29
+ return;
30
+ }
31
+
32
+ const cols: ColumnDef<StoreItem>[] = [
33
+ { key: "id", header: "ID", width: 36 },
34
+ { key: "name", header: "Name", width: 30 },
35
+ { key: "price", header: "Price (₹)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
36
+ { key: "enabled", header: "Status", width: 10, format: (v) => v ? "Enabled" : "Disabled" },
37
+ { key: "stock", header: "Stock", align: "right", width: 8, format: (v) => v == null ? "-" : String(v) },
38
+ ];
39
+
40
+ if (opts.format === "tsv") {
41
+ outputTSV(items, cols);
42
+ return;
43
+ }
44
+ if (opts.format === "csv") {
45
+ outputCSV(items, cols);
46
+ return;
47
+ }
48
+
49
+ console.log(`\n Store Items (${items.length} total)\n`);
50
+ outputTable(items, cols);
51
+ console.log();
52
+
53
+ } catch (e) {
54
+ if (e instanceof HisaaboApiError) {
55
+ const err = e.hisaaboError;
56
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
57
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
58
+ }
59
+ fatalError(String(e instanceof Error ? e.message : e));
60
+ }
61
+ }
@@ -0,0 +1,48 @@
1
+ import * as readline from "readline";
2
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
3
+ import { requireAuth } from "../../config.js";
4
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
5
+
6
+ export async function storeOrderCancelCommand(
7
+ id: string,
8
+ opts: { json?: boolean; yes?: boolean; reason?: string },
9
+ ): Promise<void> {
10
+ const cfg = requireAuth();
11
+ const client = new HisaaboClient(cfg);
12
+
13
+ if (!opts.yes && process.stdin.isTTY) {
14
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
15
+ const answer = await new Promise<string>((resolve) => {
16
+ rl.question(` Cancel order ${id}? This cannot be undone. (y/n): `, resolve);
17
+ });
18
+ rl.close();
19
+ if (answer.trim().toLowerCase() !== "y") {
20
+ console.log(" Cancelled.");
21
+ process.exit(0);
22
+ }
23
+ }
24
+
25
+ try {
26
+ const input: Record<string, unknown> = { orderId: id };
27
+ if (opts.reason) input["reason"] = opts.reason;
28
+
29
+ const result = await client.store.cancelOrder(input);
30
+
31
+ if (opts.json) {
32
+ outputJSON(result);
33
+ return;
34
+ }
35
+
36
+ success(`Order ${id} cancelled`);
37
+ console.log();
38
+ } catch (e) {
39
+ if (e instanceof HisaaboApiError) {
40
+ const err = e.hisaaboError;
41
+ if (err.code === "not_found") fatalError(`Order not found: ${id}`, EXIT.NOT_FOUND);
42
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
43
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
44
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
45
+ }
46
+ fatalError(String(e instanceof Error ? e.message : e));
47
+ }
48
+ }
@@ -0,0 +1,45 @@
1
+ import * as readline from "readline";
2
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
3
+ import { requireAuth } from "../../config.js";
4
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
5
+
6
+ export async function storeOrderConfirmCommand(
7
+ id: string,
8
+ opts: { json?: boolean; yes?: boolean },
9
+ ): Promise<void> {
10
+ const cfg = requireAuth();
11
+ const client = new HisaaboClient(cfg);
12
+
13
+ if (!opts.yes && process.stdin.isTTY) {
14
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
15
+ const answer = await new Promise<string>((resolve) => {
16
+ rl.question(` Confirm order ${id}? (y/n): `, resolve);
17
+ });
18
+ rl.close();
19
+ if (answer.trim().toLowerCase() !== "y") {
20
+ console.log(" Cancelled.");
21
+ process.exit(0);
22
+ }
23
+ }
24
+
25
+ try {
26
+ const result = await client.store.confirmOrder({ orderId: id });
27
+
28
+ if (opts.json) {
29
+ outputJSON(result);
30
+ return;
31
+ }
32
+
33
+ success(`Order ${id} confirmed`);
34
+ console.log();
35
+ } catch (e) {
36
+ if (e instanceof HisaaboApiError) {
37
+ const err = e.hisaaboError;
38
+ if (err.code === "not_found") fatalError(`Order not found: ${id}`, EXIT.NOT_FOUND);
39
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
40
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
41
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
42
+ }
43
+ fatalError(String(e instanceof Error ? e.message : e));
44
+ }
45
+ }