@hisaabo/cli 0.1.0 → 0.4.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 (172) hide show
  1. package/.turbo/turbo-typecheck.log +1 -1
  2. package/README.md +332 -0
  3. package/dist/bin/audit-trail-5LOCJ7XZ.js +78 -0
  4. package/dist/bin/categories-64WWZTND.js +47 -0
  5. package/dist/bin/check-slug-FLHHUDYS.js +65 -0
  6. package/dist/bin/chunk-4MEL44QX.js +848 -0
  7. package/dist/bin/chunk-FIMJZAS4.js +84 -0
  8. package/dist/bin/chunk-NO4FIFMS.js +176 -0
  9. package/dist/bin/chunk-T63VQXNM.js +156 -0
  10. package/dist/bin/client-5NZ23GML.js +11 -0
  11. package/dist/bin/collection-efficiency-U56XNVEE.js +165 -0
  12. package/dist/bin/config-335MN4I7.js +18 -0
  13. package/dist/bin/create-RPDEORDD.js +83 -0
  14. package/dist/bin/default-account-AE6EXZZR.js +58 -0
  15. package/dist/bin/expenses-5N2QSG54.js +89 -0
  16. package/dist/bin/export-QICOQK34.js +59 -0
  17. package/dist/bin/factory-KOCW2AQM.js +483 -0
  18. package/dist/bin/get-A43QCI2S.js +66 -0
  19. package/dist/bin/get-GWH6S5SJ.js +71 -0
  20. package/dist/bin/hisaabo.js +2302 -1510
  21. package/dist/bin/invitations-P3EEN5WI.js +66 -0
  22. package/dist/bin/invite-T3CKX53E.js +53 -0
  23. package/dist/bin/invoice-breakdown-FN5BEFJD.js +97 -0
  24. package/dist/bin/items-2OOCQKVF.js +62 -0
  25. package/dist/bin/items-toggle-SKZWCGJH.js +46 -0
  26. package/dist/bin/list-A2RKI3ZG.js +79 -0
  27. package/dist/bin/list-NRMBMKMI.js +90 -0
  28. package/dist/bin/list-T74SN6IR.js +46 -0
  29. package/dist/bin/members-W2GW3ODT.js +55 -0
  30. package/dist/bin/monthly-comparison-T34ZFOHL.js +176 -0
  31. package/dist/bin/order-cancel-TI27JYYD.js +55 -0
  32. package/dist/bin/order-confirm-VMRAMNTD.js +53 -0
  33. package/dist/bin/order-get-C2RBUR4O.js +88 -0
  34. package/dist/bin/order-update-RE3HATNF.js +60 -0
  35. package/dist/bin/output-NUOL7KJW.js +35 -0
  36. package/dist/bin/payment-modes-WOOT22I7.js +126 -0
  37. package/dist/bin/profit-loss-T4RESJ32.js +135 -0
  38. package/dist/bin/receivables-aging-6XMENEWS.js +161 -0
  39. package/dist/bin/remove-6QZI4JCY.js +52 -0
  40. package/dist/bin/revoke-AVEMPAC7.js +40 -0
  41. package/dist/bin/revoke-YUCFZFNR.js +52 -0
  42. package/dist/bin/revoke-all-LFW5WBHO.js +33 -0
  43. package/dist/bin/revoke-invitation-DTGQRJR4.js +40 -0
  44. package/dist/bin/sales-trend-ZYBRUDUU.js +71 -0
  45. package/dist/bin/sequence-FPOJTI2P.js +66 -0
  46. package/dist/bin/store-IOB4Y67C.js +82 -0
  47. package/dist/bin/summary-5KYBA4ZO.js +113 -0
  48. package/dist/bin/top-customers-WSQ2UEJL.js +81 -0
  49. package/dist/bin/top-items-RWQPDGLN.js +84 -0
  50. package/dist/bin/top-outstanding-QAMO2E7Y.js +64 -0
  51. package/dist/bin/unpaid-invoices-WB3TK5B4.js +65 -0
  52. package/dist/bin/untracked-H733MYJL.js +67 -0
  53. package/dist/bin/update-H6LPO2Z4.js +61 -0
  54. package/dist/bin/update-JU2X3XU5.js +54 -0
  55. package/dist/bin/update-TLBUIC5J.js +57 -0
  56. package/dist/bin/update-role-QST7BVFX.js +45 -0
  57. package/dist/bin/update-settings-Q2EGRLKZ.js +56 -0
  58. package/package.json +7 -6
  59. package/src/auth.ts +12 -3
  60. package/src/bin/hisaabo.ts +49 -935
  61. package/src/bin/registrars/api-key.ts +44 -0
  62. package/src/bin/registrars/auth.ts +222 -0
  63. package/src/bin/registrars/automated-invoice.ts +167 -0
  64. package/src/bin/registrars/bank.ts +124 -0
  65. package/src/bin/registrars/business.ts +120 -0
  66. package/src/bin/registrars/dashboard.ts +225 -0
  67. package/src/bin/registrars/document.ts +184 -0
  68. package/src/bin/registrars/expense.ts +87 -0
  69. package/src/bin/registrars/gst.ts +41 -0
  70. package/src/bin/registrars/import.ts +49 -0
  71. package/src/bin/registrars/invoice.ts +117 -0
  72. package/src/bin/registrars/item.ts +112 -0
  73. package/src/bin/registrars/party.ts +81 -0
  74. package/src/bin/registrars/payment.ts +128 -0
  75. package/src/bin/registrars/report.ts +142 -0
  76. package/src/bin/registrars/session.ts +32 -0
  77. package/src/bin/registrars/shipment.ts +74 -0
  78. package/src/bin/registrars/store.ts +128 -0
  79. package/src/bin/registrars/target.ts +46 -0
  80. package/src/bin/registrars/tenant.ts +73 -0
  81. package/src/client.ts +589 -15
  82. package/src/commands/api-key/create.ts +72 -0
  83. package/src/commands/api-key/list.ts +71 -0
  84. package/src/commands/api-key/revoke.ts +46 -0
  85. package/src/commands/automated-invoice/create.ts +85 -0
  86. package/src/commands/automated-invoice/delete.ts +42 -0
  87. package/src/commands/automated-invoice/get.ts +113 -0
  88. package/src/commands/automated-invoice/history.ts +65 -0
  89. package/src/commands/automated-invoice/index.ts +11 -0
  90. package/src/commands/automated-invoice/list.ts +91 -0
  91. package/src/commands/automated-invoice/pause.ts +29 -0
  92. package/src/commands/automated-invoice/resume.ts +29 -0
  93. package/src/commands/automated-invoice/run-now.ts +29 -0
  94. package/src/commands/automated-invoice/suggestions.ts +68 -0
  95. package/src/commands/automated-invoice/update.ts +54 -0
  96. package/src/commands/automated-invoice/usage.ts +68 -0
  97. package/src/commands/bank/gateway-config.ts +61 -0
  98. package/src/commands/bank/update-gateway.ts +84 -0
  99. package/src/commands/business/audit-trail.ts +79 -0
  100. package/src/commands/business/export.ts +52 -0
  101. package/src/commands/business/get.ts +55 -0
  102. package/src/commands/business/sequence.ts +65 -0
  103. package/src/commands/business/update.ts +64 -0
  104. package/src/commands/dashboard/collection-efficiency.ts +164 -0
  105. package/src/commands/dashboard/expenses.ts +76 -0
  106. package/src/commands/dashboard/invoice-breakdown.ts +89 -0
  107. package/src/commands/dashboard/monthly-comparison.ts +193 -0
  108. package/src/commands/dashboard/payment-modes.ts +121 -0
  109. package/src/commands/dashboard/profit-loss.ts +146 -0
  110. package/src/commands/dashboard/receivables-aging.ts +169 -0
  111. package/src/commands/dashboard/sales-trend.ts +68 -0
  112. package/src/commands/dashboard/summary.ts +105 -0
  113. package/src/commands/dashboard/top-customers.ts +70 -0
  114. package/src/commands/dashboard/top-items.ts +74 -0
  115. package/src/commands/dashboard/top-outstanding.ts +61 -0
  116. package/src/commands/document/factory.ts +590 -0
  117. package/src/commands/expense/categories.ts +40 -0
  118. package/src/commands/expense/update.ts +58 -0
  119. package/src/commands/import/index.ts +68 -0
  120. package/src/commands/item/categories.ts +40 -0
  121. package/src/commands/item/low-stock-count.ts +32 -0
  122. package/src/commands/item/merge.ts +53 -0
  123. package/src/commands/item/price-history.ts +59 -0
  124. package/src/commands/item/rename-unit.ts +39 -0
  125. package/src/commands/item/sales-stats.ts +44 -0
  126. package/src/commands/item/stock-history.ts +70 -0
  127. package/src/commands/item/switch-base-unit.ts +42 -0
  128. package/src/commands/item/update.ts +59 -0
  129. package/src/commands/item/variants-create.ts +58 -0
  130. package/src/commands/item/variants-delete.ts +47 -0
  131. package/src/commands/item/variants-list.ts +63 -0
  132. package/src/commands/item/variants-update.ts +61 -0
  133. package/src/commands/party/ledger-report.ts +81 -0
  134. package/src/commands/party/merge.ts +50 -0
  135. package/src/commands/party/stats.ts +40 -0
  136. package/src/commands/party/top-items.ts +57 -0
  137. package/src/commands/party/update.ts +65 -0
  138. package/src/commands/payment/default-account.ts +56 -0
  139. package/src/commands/payment/get.ts +59 -0
  140. package/src/commands/payment/unpaid-invoices.ts +69 -0
  141. package/src/commands/payment/untracked.ts +70 -0
  142. package/src/commands/payment/update.ts +54 -0
  143. package/src/commands/report/index.ts +348 -1
  144. package/src/commands/session/list.ts +91 -0
  145. package/src/commands/session/revoke-all.ts +20 -0
  146. package/src/commands/session/revoke.ts +32 -0
  147. package/src/commands/store/check-slug.ts +48 -0
  148. package/src/commands/store/items-toggle.ts +41 -0
  149. package/src/commands/store/items.ts +61 -0
  150. package/src/commands/store/order-cancel.ts +48 -0
  151. package/src/commands/store/order-confirm.ts +45 -0
  152. package/src/commands/store/order-get.ts +66 -0
  153. package/src/commands/store/order-update.ts +52 -0
  154. package/src/commands/store/update-settings.ts +52 -0
  155. package/src/commands/tenant/invitations.ts +62 -0
  156. package/src/commands/tenant/invite.ts +57 -0
  157. package/src/commands/tenant/list.ts +46 -0
  158. package/src/commands/tenant/members.ts +55 -0
  159. package/src/commands/tenant/remove.ts +47 -0
  160. package/src/commands/tenant/revoke-invitation.ts +32 -0
  161. package/src/commands/tenant/update-role.ts +41 -0
  162. package/src/config.ts +51 -2
  163. package/src/error-handler.ts +53 -0
  164. package/src/output.ts +1 -0
  165. package/src/spinner.ts +39 -0
  166. package/tsup.config.ts +6 -1
  167. package/src/components/ErrorDisplay.tsx +0 -16
  168. package/src/components/Header.tsx +0 -26
  169. package/src/components/MoneyCell.tsx +0 -16
  170. package/src/components/Spinner.tsx +0 -12
  171. package/src/components/StatusBadge.tsx +0 -39
  172. package/src/components/Table.tsx +0 -63
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ HisaaboApiError,
4
+ HisaaboClient
5
+ } from "./chunk-4MEL44QX.js";
6
+ import {
7
+ requireAuth
8
+ } from "./chunk-FIMJZAS4.js";
9
+ import {
10
+ EXIT,
11
+ fatalError,
12
+ outputJSON
13
+ } from "./chunk-NO4FIFMS.js";
14
+
15
+ // src/commands/payment/default-account.ts
16
+ async function paymentDefaultAccountCommand(opts) {
17
+ const cfg = requireAuth();
18
+ const client = new HisaaboClient(cfg);
19
+ try {
20
+ const input = opts.partyId ? { partyId: opts.partyId } : void 0;
21
+ const result = await client.payment.defaultAccount(input);
22
+ if (opts.json) {
23
+ outputJSON(result);
24
+ return;
25
+ }
26
+ if (!result) {
27
+ console.log("\n No recommended bank account found.\n");
28
+ return;
29
+ }
30
+ const sep = "\u2500".repeat(48);
31
+ console.log(`
32
+ Recommended Bank Account`);
33
+ console.log(` ${sep}`);
34
+ if (typeof result === "object" && result !== null) {
35
+ const acct = result;
36
+ if (acct["id"]) console.log(` ID : ${acct["id"]}`);
37
+ if (acct["accountName"]) console.log(` Account : ${acct["accountName"]}`);
38
+ if (acct["bankName"]) console.log(` Bank : ${acct["bankName"]}`);
39
+ if (acct["accountNumber"]) console.log(` Number : ${acct["accountNumber"]}`);
40
+ if (acct["ifsc"]) console.log(` IFSC : ${acct["ifsc"]}`);
41
+ } else {
42
+ console.log(` ${String(result)}`);
43
+ }
44
+ console.log();
45
+ } catch (e) {
46
+ if (e instanceof HisaaboApiError) {
47
+ const err = e.hisaaboError;
48
+ if (err.code === "not_found") fatalError("No bank account configured.", EXIT.NOT_FOUND);
49
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
50
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
51
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
52
+ }
53
+ fatalError(String(e instanceof Error ? e.message : e));
54
+ }
55
+ }
56
+ export {
57
+ paymentDefaultAccountCommand
58
+ };
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ formatAmount,
4
+ fyStart,
5
+ monthEnd,
6
+ monthStart,
7
+ todayISO
8
+ } from "./chunk-T63VQXNM.js";
9
+ import {
10
+ HisaaboApiError,
11
+ HisaaboClient
12
+ } from "./chunk-4MEL44QX.js";
13
+ import {
14
+ requireAuth
15
+ } from "./chunk-FIMJZAS4.js";
16
+ import {
17
+ EXIT,
18
+ fatalError,
19
+ hasColor,
20
+ outputCSV,
21
+ outputJSON,
22
+ outputTSV,
23
+ outputTable
24
+ } from "./chunk-NO4FIFMS.js";
25
+
26
+ // src/commands/dashboard/expenses.ts
27
+ import chalk from "chalk";
28
+ async function dashboardExpensesCommand(opts) {
29
+ const cfg = requireAuth();
30
+ const client = new HisaaboClient(cfg);
31
+ let fromDate = opts.from;
32
+ let toDate = opts.to;
33
+ if (opts.thisMonth) {
34
+ fromDate = monthStart();
35
+ toDate = monthEnd();
36
+ } else if (opts.thisFy) {
37
+ fromDate = fyStart();
38
+ toDate = todayISO();
39
+ }
40
+ try {
41
+ const data = await client.dashboard.expensesByCategory({ fromDate, toDate });
42
+ if (opts.json) {
43
+ outputJSON(data);
44
+ return;
45
+ }
46
+ const items = Array.isArray(data) ? data : [];
47
+ const total = items.reduce((sum, r) => sum + parseFloat(String(r["totalAmount"] ?? r["amount"] ?? "0")), 0);
48
+ const rows = items.map((r) => {
49
+ const amt = parseFloat(String(r["totalAmount"] ?? r["amount"] ?? "0"));
50
+ const pct = total > 0 ? (amt / total * 100).toFixed(1) + "%" : "-";
51
+ return {
52
+ category: String(r["category"] ?? "-"),
53
+ amount: formatAmount(String(amt)),
54
+ count: String(r["count"] ?? r["expenseCount"] ?? "-"),
55
+ pct
56
+ };
57
+ });
58
+ const columns = [
59
+ { key: "category", header: "Category", align: "left" },
60
+ { key: "amount", header: "Amount \u20B9", align: "right" },
61
+ { key: "count", header: "Count", align: "right" },
62
+ { key: "pct", header: "% of Total", align: "right" }
63
+ ];
64
+ if (opts.format === "tsv") {
65
+ outputTSV(rows, columns);
66
+ } else if (opts.format === "csv") {
67
+ outputCSV(rows, columns);
68
+ } else {
69
+ if (hasColor()) process.stdout.write("\n" + chalk.bold(" Expenses by Category\n") + "\n");
70
+ else process.stdout.write("\n Expenses by Category\n\n");
71
+ outputTable(rows, columns);
72
+ if (total > 0) {
73
+ const totalStr = ` Total: \u20B9${formatAmount(String(total))}`;
74
+ process.stdout.write("\n" + (hasColor() ? chalk.bold(totalStr) : totalStr) + "\n");
75
+ }
76
+ process.stdout.write("\n");
77
+ }
78
+ } catch (e) {
79
+ if (e instanceof HisaaboApiError) {
80
+ const err = e.hisaaboError;
81
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
82
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
83
+ }
84
+ fatalError(String(e instanceof Error ? e.message : e));
85
+ }
86
+ }
87
+ export {
88
+ dashboardExpensesCommand
89
+ };
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ HisaaboApiError,
4
+ HisaaboClient
5
+ } from "./chunk-4MEL44QX.js";
6
+ import {
7
+ requireAuth
8
+ } from "./chunk-FIMJZAS4.js";
9
+ import {
10
+ EXIT,
11
+ fatalError,
12
+ outputJSON,
13
+ success
14
+ } from "./chunk-NO4FIFMS.js";
15
+
16
+ // src/commands/business/export.ts
17
+ import * as readline from "readline";
18
+ async function businessExportCommand(opts) {
19
+ const cfg = requireAuth();
20
+ const client = new HisaaboClient(cfg);
21
+ if (!opts.yes && process.stdin.isTTY) {
22
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
23
+ const answer = await new Promise((resolve) => {
24
+ rl.question(" Export all business data? This may take a moment. (y/N): ", resolve);
25
+ });
26
+ rl.close();
27
+ if (answer.trim().toLowerCase() !== "y") {
28
+ console.log(" Cancelled.");
29
+ process.exit(0);
30
+ }
31
+ }
32
+ try {
33
+ const result = await client.business.exportData();
34
+ if (opts.json) {
35
+ outputJSON(result);
36
+ return;
37
+ }
38
+ if (result?.url) {
39
+ success("Export complete.");
40
+ process.stdout.write(` Download URL: ${result.url}
41
+ `);
42
+ } else if (result?.status === "processing" || result?.queued) {
43
+ success("Export queued. You will be notified when the export is ready.");
44
+ } else {
45
+ success("Export initiated successfully.");
46
+ }
47
+ } catch (e) {
48
+ if (e instanceof HisaaboApiError) {
49
+ const err = e.hisaaboError;
50
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
51
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
52
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
53
+ }
54
+ fatalError(String(e instanceof Error ? e.message : e));
55
+ }
56
+ }
57
+ export {
58
+ businessExportCommand
59
+ };
@@ -0,0 +1,483 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ currentFY,
4
+ formatAmount,
5
+ formatDate,
6
+ formatINR,
7
+ formatStatus,
8
+ fyStart,
9
+ monthEnd,
10
+ monthStart,
11
+ todayISO
12
+ } from "./chunk-T63VQXNM.js";
13
+ import {
14
+ HisaaboApiError,
15
+ HisaaboClient
16
+ } from "./chunk-4MEL44QX.js";
17
+ import {
18
+ requireAuth
19
+ } from "./chunk-FIMJZAS4.js";
20
+ import {
21
+ EXIT,
22
+ fatalError,
23
+ getWidthTier,
24
+ hasColor,
25
+ outputCSV,
26
+ outputIds,
27
+ outputJSON,
28
+ outputTSV,
29
+ outputTable,
30
+ paginationFooter,
31
+ success,
32
+ termWidth
33
+ } from "./chunk-NO4FIFMS.js";
34
+
35
+ // src/commands/document/factory.ts
36
+ import * as readline from "readline";
37
+ import chalk from "chalk";
38
+ function getNs(client, nsKey) {
39
+ return client[nsKey];
40
+ }
41
+ async function promptLine(rl, question) {
42
+ return new Promise((resolve) => rl.question(question, resolve));
43
+ }
44
+ async function docListCommand(dt, opts) {
45
+ const cfg = requireAuth();
46
+ const client = new HisaaboClient(cfg);
47
+ const ns = getNs(client, dt.nsKey);
48
+ let from = opts.from;
49
+ let to = opts.to;
50
+ if (opts.thisFy) {
51
+ from = fyStart();
52
+ to = todayISO();
53
+ } else if (opts.thisMonth) {
54
+ from = monthStart();
55
+ to = monthEnd();
56
+ }
57
+ const page = opts.page ?? 1;
58
+ const limit = opts.limit ?? 20;
59
+ try {
60
+ const result = await ns.list({
61
+ status: opts.status ?? null,
62
+ partySearch: opts.party ?? null,
63
+ fromDate: from ?? null,
64
+ toDate: to ?? null,
65
+ page,
66
+ limit
67
+ });
68
+ if (opts.json) {
69
+ outputJSON({
70
+ data: result.data,
71
+ pagination: {
72
+ page: result.page,
73
+ limit: result.limit,
74
+ total: result.total,
75
+ hasMore: result.page * result.limit < result.total
76
+ }
77
+ });
78
+ return;
79
+ }
80
+ const tier = getWidthTier();
81
+ console.log(`
82
+ ${dt.label}s` + " ".repeat(Math.max(1, 40 - dt.label.length)) + `FY ${currentFY()}`);
83
+ console.log(` ${"\u2550".repeat(68)}
84
+ `);
85
+ const narrowCols = [
86
+ { key: "documentNumber", header: "#", width: 12 },
87
+ { key: "partyName", header: "Party", width: 18 },
88
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
89
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
90
+ ];
91
+ const standardCols = [
92
+ { key: "documentNumber", header: "#", width: 12 },
93
+ { key: "partyName", header: "Party", width: 18 },
94
+ { key: "documentDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
95
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
96
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
97
+ ];
98
+ const wideCols = [
99
+ { key: "documentNumber", header: "#", width: 12 },
100
+ { key: "partyName", header: "Party", width: 20 },
101
+ { key: "documentDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
102
+ { key: "dueDate", header: "Due", width: 12, format: (v) => formatDate(v ? String(v) : null) },
103
+ { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
104
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
105
+ ];
106
+ const cols = tier === "narrow" ? narrowCols : tier === "wide" ? wideCols : standardCols;
107
+ if (opts.format === "tsv") {
108
+ outputTSV(result.data, cols);
109
+ } else if (opts.format === "csv") {
110
+ outputCSV(result.data, cols);
111
+ } else if (opts.format === "ids") {
112
+ outputIds(result.data.map((r) => r.id));
113
+ } else {
114
+ outputTable(result.data, cols);
115
+ paginationFooter(result.page, result.limit, result.total);
116
+ }
117
+ } catch (e) {
118
+ if (e instanceof HisaaboApiError) {
119
+ const err = e.hisaaboError;
120
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
121
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
122
+ }
123
+ fatalError(String(e instanceof Error ? e.message : e));
124
+ }
125
+ }
126
+ async function docGetCommand(dt, id, opts) {
127
+ const cfg = requireAuth();
128
+ const client = new HisaaboClient(cfg);
129
+ const ns = getNs(client, dt.nsKey);
130
+ try {
131
+ let line2 = function(left, right) {
132
+ if (right !== void 0) {
133
+ const pad = Math.max(1, inner - left.length - right.length - 2);
134
+ process.stdout.write(`\u2502 ${left}${" ".repeat(pad)}${right} \u2502
135
+ `);
136
+ } else {
137
+ const vis = left.length;
138
+ const pad = Math.max(0, inner - vis);
139
+ process.stdout.write(`\u2502 ${left}${" ".repeat(pad)} \u2502
140
+ `);
141
+ }
142
+ }, divider2 = function() {
143
+ process.stdout.write(`\u251C${"\u2500".repeat(inner + 2)}\u2524
144
+ `);
145
+ };
146
+ var line = line2, divider = divider2;
147
+ const doc = await ns.getById({ id });
148
+ if (opts.json) {
149
+ outputJSON(doc);
150
+ return;
151
+ }
152
+ const w = Math.min(termWidth() - 2, 68);
153
+ const inner = w - 2;
154
+ const docNum = doc.documentNumber ?? doc.number ?? id;
155
+ const title = `${dt.label.toUpperCase()} ${docNum}`;
156
+ const statusBadge = formatStatus(doc.status ?? "draft");
157
+ const statusLen = statusBadge.replace(/\x1b\[[0-9;]*m/g, "").length;
158
+ const topPad = Math.max(1, inner - title.length - statusLen);
159
+ process.stdout.write(`
160
+ \u250C${"\u2500".repeat(inner + 2)}\u2510
161
+ `);
162
+ process.stdout.write(`\u2502 ${hasColor() ? chalk.bold(title) : title}${" ".repeat(topPad)}${statusBadge} \u2502
163
+ `);
164
+ divider2();
165
+ if (doc.partyName) line2(`Party: ${doc.partyName}`);
166
+ if (doc.documentDate ?? doc.date) line2(`Date: ${formatDate(doc.documentDate ?? doc.date)}`);
167
+ if (doc.dueDate) line2(`Due: ${formatDate(doc.dueDate)}`);
168
+ if (doc.createdByName) line2(`Created: ${doc.createdByName}${doc.createdAt ? ` (${formatDate(doc.createdAt)})` : ""}`);
169
+ divider2();
170
+ const items = doc.lineItems ?? doc.items ?? [];
171
+ if (items.length > 0) {
172
+ process.stdout.write(`\u2502${"\u2500".repeat(inner + 2)}\u2502
173
+ `);
174
+ process.stdout.write(`\u2502 # ${"Item".padEnd(18)} ${"Qty".padStart(5)} ${"Rate (\u20B9)".padStart(10)} ${"Amount (\u20B9)".padStart(12)} \u2502
175
+ `);
176
+ process.stdout.write(`\u2502 ${"\u2500\u2500".padEnd(2)} ${"\u2500".repeat(18)} ${"\u2500".repeat(5)} ${"\u2500".repeat(10)} ${"\u2500".repeat(12)} \u2502
177
+ `);
178
+ items.forEach((item, i) => {
179
+ const idx = String(i + 1).padStart(2);
180
+ const desc = (item.description ?? item.name ?? "").slice(0, 18).padEnd(18);
181
+ const qty = String(item.quantity ?? "1").padStart(5);
182
+ const rate = formatAmount(String(item.unitPrice ?? item.rate ?? "0")).padStart(10);
183
+ const amt = formatAmount(String(item.amount ?? "0")).padStart(12);
184
+ process.stdout.write(`\u2502 ${idx} ${desc} ${qty} ${rate} ${amt} \u2502
185
+ `);
186
+ });
187
+ process.stdout.write(`\u2502${"\u2500".repeat(inner + 2)}\u2502
188
+ `);
189
+ divider2();
190
+ }
191
+ if (doc.totalAmount !== void 0) {
192
+ if (doc.subtotal !== void 0) line2(`Subtotal:`, formatAmount(String(doc.subtotal)).padStart(16));
193
+ if (doc.totalDiscount !== void 0 && parseFloat(String(doc.totalDiscount)) !== 0)
194
+ line2(`Discount:`, ("-" + formatAmount(String(doc.totalDiscount))).padStart(16));
195
+ process.stdout.write(`\u2502 ${"\u2500".repeat(inner - 2)} \u2502
196
+ `);
197
+ line2(`Total:`, (hasColor() ? chalk.bold(formatAmount(String(doc.totalAmount))) : formatAmount(String(doc.totalAmount))).padStart(16));
198
+ }
199
+ if (doc.notes || doc.termsAndConditions) {
200
+ divider2();
201
+ if (doc.notes) line2(`Notes: ${doc.notes}`);
202
+ if (doc.termsAndConditions) line2(`Terms: ${doc.termsAndConditions}`);
203
+ }
204
+ process.stdout.write(` \u2514${"\u2500".repeat(inner + 2)}\u2518
205
+
206
+ `);
207
+ } catch (e) {
208
+ if (e instanceof HisaaboApiError) {
209
+ const err = e.hisaaboError;
210
+ if (err.code === "not_found") fatalError(`${dt.label} not found: ${id}`, EXIT.NOT_FOUND);
211
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
212
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
213
+ }
214
+ fatalError(String(e instanceof Error ? e.message : e));
215
+ }
216
+ }
217
+ async function docCreateCommand(dt, opts) {
218
+ const cfg = requireAuth();
219
+ const client = new HisaaboClient(cfg);
220
+ const ns = getNs(client, dt.nsKey);
221
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
222
+ try {
223
+ let partyId = opts.partyId;
224
+ let partyName = opts.party ?? "";
225
+ if (!partyId) {
226
+ if (!isNonInteractive) {
227
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
228
+ console.log(`
229
+ New ${dt.label}`);
230
+ console.log(" " + "\u2500".repeat(40) + "\n");
231
+ const search = await promptLine(rl, " Select Party:\n > Search: ");
232
+ const parties = await client.party.list({ search: search.trim(), limit: 5 });
233
+ if (parties.data.length === 0) {
234
+ rl.close();
235
+ fatalError("No parties found. Create one with: hisaabo party create", EXIT.NOT_FOUND);
236
+ }
237
+ parties.data.forEach((p, i) => {
238
+ console.log(` ${i + 1} ${p.name.padEnd(20)} ${(p.phone ?? "").padEnd(14)} ${p.type}`);
239
+ });
240
+ const partyChoice = await promptLine(rl, "\n Party [1]: ");
241
+ const idx = parseInt(partyChoice.trim() || "1", 10) - 1;
242
+ const selected = parties.data[Math.max(0, Math.min(idx, parties.data.length - 1))];
243
+ if (!selected) {
244
+ rl.close();
245
+ fatalError("Invalid selection.", EXIT.USAGE);
246
+ }
247
+ partyId = selected.id;
248
+ partyName = selected.name;
249
+ console.log(` Party: ${partyName}
250
+ `);
251
+ rl.close();
252
+ } else {
253
+ if (!partyName) fatalError("--party or --party-id is required", EXIT.USAGE);
254
+ const parties = await client.party.list({ search: partyName, limit: 5 });
255
+ if (parties.data.length === 0) fatalError(`Party not found: ${partyName}`, EXIT.NOT_FOUND);
256
+ partyId = parties.data[0].id;
257
+ partyName = parties.data[0].name;
258
+ }
259
+ }
260
+ const lineItems = [];
261
+ if (opts.item && opts.item.length > 0) {
262
+ for (let i = 0; i < opts.item.length; i++) {
263
+ const itemName = opts.item[i];
264
+ const qty = opts.qty?.[i] ?? "1";
265
+ let unitPrice = opts.rate?.[i] ?? "";
266
+ if (!unitPrice) {
267
+ const items = await client.item.list({ search: itemName, limit: 3 });
268
+ if (items.data.length > 0 && items.data[0]?.salePrice) {
269
+ unitPrice = items.data[0].salePrice;
270
+ lineItems.push({
271
+ itemId: items.data[0].id,
272
+ description: items.data[0].name,
273
+ quantity: qty,
274
+ unitPrice,
275
+ taxPercent: items.data[0].taxPercent
276
+ });
277
+ } else {
278
+ fatalError(`Item not found or has no price: ${itemName}. Use --rate to specify price.`, EXIT.NOT_FOUND);
279
+ }
280
+ } else {
281
+ const items = await client.item.list({ search: itemName, limit: 3 });
282
+ const matched = items.data.find(
283
+ (it) => it.name.toLowerCase().includes(itemName.toLowerCase())
284
+ );
285
+ if (matched) {
286
+ lineItems.push({
287
+ itemId: matched.id,
288
+ description: matched.name,
289
+ quantity: qty,
290
+ unitPrice,
291
+ taxPercent: matched.taxPercent
292
+ });
293
+ } else {
294
+ lineItems.push({ description: itemName, quantity: qty, unitPrice });
295
+ }
296
+ }
297
+ }
298
+ } else if (!isNonInteractive) {
299
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
300
+ console.log(" Add Line Items (empty description to finish):\n");
301
+ let itemNum = 1;
302
+ while (true) {
303
+ console.log(` Item ${itemNum}:`);
304
+ const search = await promptLine(rl, " Search item (or description): ");
305
+ if (!search.trim()) break;
306
+ let description = search.trim();
307
+ let itemId;
308
+ let defaultPrice = "";
309
+ let defaultTax = "0";
310
+ const items = await client.item.list({ search: search.trim(), limit: 5 });
311
+ if (items.data.length > 0) {
312
+ items.data.forEach((it, i) => {
313
+ const stock = it.itemType === "service" ? "-" : String(it.stockQuantity);
314
+ const price = it.salePrice ? formatINR(it.salePrice) : "no price";
315
+ console.log(` ${i + 1} ${it.name.padEnd(20)} ${price.padEnd(12)} Stock: ${stock}`);
316
+ });
317
+ const choice = await promptLine(rl, " Item [1] (or 0 to use as description): ");
318
+ const idx = parseInt(choice.trim() || "1", 10);
319
+ if (idx > 0) {
320
+ const selected = items.data[idx - 1];
321
+ if (selected) {
322
+ itemId = selected.id;
323
+ description = selected.name;
324
+ defaultPrice = selected.salePrice ?? "";
325
+ defaultTax = selected.taxPercent;
326
+ }
327
+ }
328
+ }
329
+ const qtyStr = await promptLine(rl, " Quantity [1]: ");
330
+ const qty = qtyStr.trim() || "1";
331
+ const rateStr = await promptLine(rl, ` Unit Price [${defaultPrice || "0.00"}]: `);
332
+ const unitPrice = rateStr.trim() || defaultPrice || "0.00";
333
+ const taxStr = await promptLine(rl, ` Tax % [${defaultTax}]: `);
334
+ const taxPercent = taxStr.trim() || defaultTax;
335
+ const discStr = await promptLine(rl, " Discount % [0]: ");
336
+ const discountPercent = discStr.trim() || "0";
337
+ const amount = parseFloat(qty) * parseFloat(unitPrice) * (1 + parseFloat(taxPercent) / 100) * (1 - parseFloat(discountPercent) / 100);
338
+ console.log(
339
+ ` > ${description} x${qty} @${formatAmount(unitPrice)} ${taxPercent}% tax = ${formatAmount(String(amount))}
340
+ `
341
+ );
342
+ lineItems.push({ itemId, description, quantity: qty, unitPrice, taxPercent, discountPercent });
343
+ itemNum++;
344
+ }
345
+ rl.close();
346
+ if (lineItems.length === 0) fatalError("No line items added.", EXIT.USAGE);
347
+ } else {
348
+ fatalError("No items specified. Use --item flags.", EXIT.USAGE);
349
+ }
350
+ const subtotal = lineItems.reduce((s, item) => {
351
+ return s + parseFloat(item.quantity) * parseFloat(item.unitPrice);
352
+ }, 0);
353
+ const taxTotal = lineItems.reduce((s, item) => {
354
+ const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
355
+ return s + amt * (parseFloat(item.taxPercent ?? "0") / 100);
356
+ }, 0);
357
+ let documentDate = opts.date ?? todayISO();
358
+ let dueDate = opts.dueDate;
359
+ let notes = opts.notes;
360
+ if (!isNonInteractive) {
361
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
362
+ console.log(`
363
+ \u2500\u2500\u2500 ${dt.label} 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`);
364
+ console.log(` Subtotal: ${formatAmount(String(subtotal))}`);
365
+ console.log(` Tax: ${formatAmount(String(taxTotal))}`);
366
+ console.log(` Total: ${formatAmount(String(subtotal + taxTotal))}`);
367
+ 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");
368
+ const dateStr = await promptLine(rl, ` Date [${todayISO()}]: `);
369
+ if (dateStr.trim()) documentDate = dateStr.trim();
370
+ const dueStr = await promptLine(rl, " Due Date [optional]: ");
371
+ if (dueStr.trim()) dueDate = dueStr.trim();
372
+ const notesStr = await promptLine(rl, " Notes: ");
373
+ if (notesStr.trim()) notes = notesStr.trim();
374
+ 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");
375
+ const confirm = await promptLine(rl, `
376
+ Create this ${dt.label}? (y/n) [y]: `);
377
+ rl.close();
378
+ if (confirm.trim().toLowerCase() === "n") {
379
+ console.log(" Cancelled.");
380
+ process.exit(EXIT.SUCCESS);
381
+ }
382
+ }
383
+ const doc = await ns.create({
384
+ partyId,
385
+ documentDate,
386
+ dueDate,
387
+ notes,
388
+ lineItems,
389
+ ...opts.discount ? { invoiceDiscount: opts.discount } : {}
390
+ });
391
+ if (opts.json) {
392
+ outputJSON(doc);
393
+ return;
394
+ }
395
+ const docNum = doc.documentNumber ?? doc.number ?? doc.id;
396
+ const total = doc.totalAmount ?? String(subtotal + taxTotal);
397
+ success(`Created: ${docNum} for ${formatINR(total)}`);
398
+ console.log(` View: hisaabo ${dt.cmd} get ${doc.id}
399
+ `);
400
+ } catch (e) {
401
+ if (e instanceof HisaaboApiError) {
402
+ const err = e.hisaaboError;
403
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
404
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
405
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
406
+ }
407
+ fatalError(String(e instanceof Error ? e.message : e));
408
+ }
409
+ }
410
+ async function docStatusCommand(dt, id, status, opts) {
411
+ const cfg = requireAuth();
412
+ const client = new HisaaboClient(cfg);
413
+ const ns = getNs(client, dt.nsKey);
414
+ if (!dt.statuses.includes(status)) {
415
+ fatalError(`Invalid status: ${status}. Valid: ${dt.statuses.join(", ")}`, EXIT.USAGE);
416
+ }
417
+ try {
418
+ const before = await ns.getById({ id });
419
+ const updated = await ns.updateStatus({ id, status });
420
+ if (opts.json) {
421
+ outputJSON(updated);
422
+ return;
423
+ }
424
+ const fromBadge = formatStatus(before.status ?? "draft");
425
+ const toBadge = formatStatus(status);
426
+ console.log(` ${id} status updated: ${fromBadge} -> ${toBadge}`);
427
+ } catch (e) {
428
+ if (e instanceof HisaaboApiError) {
429
+ const err = e.hisaaboError;
430
+ if (err.code === "not_found") fatalError(`${dt.label} not found: ${id}`, EXIT.NOT_FOUND);
431
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
432
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
433
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
434
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
435
+ }
436
+ fatalError(String(e instanceof Error ? e.message : e));
437
+ }
438
+ }
439
+ async function docDeleteCommand(dt, id, opts) {
440
+ const cfg = requireAuth();
441
+ const client = new HisaaboClient(cfg);
442
+ const ns = getNs(client, dt.nsKey);
443
+ try {
444
+ const doc = await ns.getById({ id });
445
+ const docNum = doc.documentNumber ?? doc.number ?? id;
446
+ if (!opts.yes && process.stdin.isTTY) {
447
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
448
+ const answer = await new Promise((resolve) => {
449
+ rl.question(
450
+ ` Delete ${docNum} (${doc.partyName ?? ""}, ${doc.totalAmount ?? ""})? (y/N): `,
451
+ resolve
452
+ );
453
+ });
454
+ rl.close();
455
+ if (answer.trim().toLowerCase() !== "y") {
456
+ console.log(" Cancelled.");
457
+ process.exit(0);
458
+ }
459
+ }
460
+ const result = await ns.delete({ id });
461
+ if (opts.json) {
462
+ outputJSON(result);
463
+ return;
464
+ }
465
+ success(`Deleted: ${docNum}`);
466
+ } catch (e) {
467
+ if (e instanceof HisaaboApiError) {
468
+ const err = e.hisaaboError;
469
+ if (err.code === "not_found") fatalError(`${dt.label} not found: ${id}`, EXIT.NOT_FOUND);
470
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
471
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
472
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
473
+ }
474
+ fatalError(String(e instanceof Error ? e.message : e));
475
+ }
476
+ }
477
+ export {
478
+ docCreateCommand,
479
+ docDeleteCommand,
480
+ docGetCommand,
481
+ docListCommand,
482
+ docStatusCommand
483
+ };