@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
@@ -1,609 +1,60 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ currentFY,
4
+ deliveryMethodLabel,
5
+ formatAmount,
6
+ formatDate,
7
+ formatINR,
8
+ formatStatus,
9
+ fyStart,
10
+ monthEnd,
11
+ monthStart,
12
+ quarterRange,
13
+ todayISO
14
+ } from "./chunk-T63VQXNM.js";
15
+ import {
16
+ HisaaboApiError,
17
+ HisaaboClient
18
+ } from "./chunk-4MEL44QX.js";
19
+ import {
20
+ clearConfig,
21
+ getConfig,
22
+ getConfigPath,
23
+ requireAuth,
24
+ setConfig
25
+ } from "./chunk-FIMJZAS4.js";
26
+ import {
27
+ EXIT,
28
+ fatalError,
29
+ getWidthTier,
30
+ hasColor,
31
+ outputCSV,
32
+ outputIds,
33
+ outputJSON,
34
+ outputTSV,
35
+ outputTable,
36
+ paginationFooter,
37
+ success,
38
+ termWidth,
39
+ warn
40
+ } from "./chunk-NO4FIFMS.js";
2
41
 
3
42
  // src/bin/hisaabo.ts
4
43
  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
44
 
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
- }
45
+ // src/bin/registrars/auth.ts
46
+ import * as readline from "readline";
575
47
 
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);
48
+ // src/auth.ts
49
+ function validateApiUrl(url) {
50
+ const parsed = new URL(url);
51
+ if (!["http:", "https:"].includes(parsed.protocol)) {
52
+ fatalError("API URL must use http:// or https://", EXIT.USAGE);
597
53
  }
598
- return cfg;
599
- }
600
- function getConfigPath() {
601
- return conf.path;
54
+ return parsed.origin + parsed.pathname.replace(/\/$/, "");
602
55
  }
603
-
604
- // src/auth.ts
605
56
  async function loginWithToken(apiUrl, token) {
606
- const base = apiUrl.replace(/\/$/, "");
57
+ const base = validateApiUrl(apiUrl);
607
58
  const client = new HisaaboClient({
608
59
  apiUrl: base,
609
60
  token,
@@ -649,8 +100,8 @@ async function loginWithToken(apiUrl, token) {
649
100
  console.log();
650
101
  let selected = businesses[0];
651
102
  if (businesses.length > 1) {
652
- const readline12 = await import("readline");
653
- const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
103
+ const readline14 = await import("readline");
104
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
654
105
  const answer = await new Promise((resolve2) => {
655
106
  rl.question(" Select business [1]: ", resolve2);
656
107
  });
@@ -664,14 +115,15 @@ async function loginWithToken(apiUrl, token) {
664
115
  setConfig({
665
116
  businessId: selected.id,
666
117
  businessName: selected.name,
667
- tenantId: selected.id
118
+ tenantId: selected.id,
119
+ tokenCreatedAt: Date.now()
668
120
  });
669
121
  success(`Authenticated as ${user.name ?? user.email} (${user.email}) via API key`);
670
122
  console.log(" Active business: " + selected.name);
671
123
  console.log(" Config saved to " + getConfigPath() + "\n");
672
124
  }
673
125
  async function login(apiUrl, email, password) {
674
- const base = apiUrl.replace(/\/$/, "");
126
+ const base = validateApiUrl(apiUrl);
675
127
  const client = new HisaaboClient({
676
128
  apiUrl: base,
677
129
  token: "",
@@ -705,8 +157,8 @@ async function login(apiUrl, email, password) {
705
157
  console.log();
706
158
  let selected = businesses[0];
707
159
  if (businesses.length > 1) {
708
- const readline12 = await import("readline");
709
- const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
160
+ const readline14 = await import("readline");
161
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
710
162
  const answer = await new Promise((resolve2) => {
711
163
  rl.question(" Select business [1]: ", resolve2);
712
164
  });
@@ -720,8 +172,9 @@ async function login(apiUrl, email, password) {
720
172
  setConfig({
721
173
  businessId: selected.id,
722
174
  businessName: selected.name,
723
- tenantId: selected.id
175
+ tenantId: selected.id,
724
176
  // fallback; real tenantId may differ
177
+ tokenCreatedAt: Date.now()
725
178
  });
726
179
  success(`Active business: ${selected.name}`);
727
180
  console.log(" Config saved to " + getConfigPath());
@@ -773,231 +226,272 @@ async function whoami(jsonMode) {
773
226
  }
774
227
  }
775
228
 
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")}`;
229
+ // src/bin/registrars/auth.ts
230
+ function ask(rl, q) {
231
+ return new Promise((res) => rl.question(q, res));
888
232
  }
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";
233
+ function askSecret(prompt6) {
234
+ return new Promise((resolve2) => {
235
+ const rl = readline.createInterface({ input: process.stdin, terminal: true });
236
+ process.stdout.write(prompt6);
237
+ const chars = [];
238
+ const cleanup = () => {
239
+ process.stdin.removeListener("data", onData);
240
+ process.stdin.setRawMode?.(false);
241
+ process.stdin.pause();
242
+ };
243
+ const onSignal = () => {
244
+ cleanup();
245
+ process.exit(130);
246
+ };
247
+ process.once("SIGTERM", onSignal);
248
+ process.once("SIGHUP", onSignal);
249
+ const onData = (key) => {
250
+ const ch = key.toString();
251
+ if (ch === "\n" || ch === "\r") {
252
+ process.removeListener("SIGTERM", onSignal);
253
+ process.removeListener("SIGHUP", onSignal);
254
+ cleanup();
255
+ process.stdout.write("\n");
256
+ rl.close();
257
+ const result = chars.join("");
258
+ chars.length = 0;
259
+ resolve2(result);
260
+ } else if (ch === "\x7F" || ch === "\b") {
261
+ if (chars.length > 0) {
262
+ chars.pop();
263
+ process.stdout.write("\b \b");
264
+ }
265
+ } else if (ch === "") {
266
+ cleanup();
267
+ process.stdout.write("\n");
268
+ process.exit(130);
269
+ } else if (ch.charCodeAt(0) >= 32) {
270
+ chars.push(ch);
271
+ process.stdout.write("*");
272
+ }
273
+ };
274
+ if (process.stdin.isTTY) {
275
+ process.stdin.setRawMode?.(true);
276
+ process.stdin.resume();
277
+ process.stdin.on("data", onData);
278
+ } else {
279
+ rl.question("", (answer) => {
280
+ rl.close();
281
+ resolve2(answer.trim());
282
+ });
283
+ }
924
284
  });
925
- return [border, ...padded, bottom];
926
285
  }
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);
286
+ function registerAuthCommands(program2) {
287
+ program2.command("login").description("Authenticate and configure your Hisaabo server").option("--api-url <url>", "Server URL").option("--email <email>", "Email address").option("--password <password>", "Password (visible in shell history \u2014 prefer interactive prompt)").option("--token <token>", "API key (visible in shell history \u2014 prefer HISAABO_TOKEN env var)").action(async (opts) => {
288
+ let apiUrl = opts.apiUrl;
289
+ if (opts.token) {
290
+ if (!apiUrl) {
291
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
292
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
293
+ const u = await ask(rl, " Server URL [http://localhost:3000]: ");
294
+ rl.close();
295
+ apiUrl = u.trim() || "http://localhost:3000";
296
+ }
297
+ await loginWithToken(apiUrl, opts.token);
943
298
  return;
944
299
  }
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}`);
300
+ let email = opts.email;
301
+ let password = opts.password;
302
+ if (!apiUrl || !email || !password) {
303
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
304
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
305
+ if (!apiUrl) {
306
+ const u = await ask(rl, " Server URL [http://localhost:3000]: ");
307
+ apiUrl = u.trim() || "http://localhost:3000";
308
+ }
309
+ if (!email) email = (await ask(rl, " Email: ")).trim();
310
+ rl.close();
311
+ if (!password) {
312
+ password = await askSecret(" Password: ");
313
+ }
314
+ console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
967
315
  }
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);
316
+ await login(apiUrl, email, password);
317
+ });
318
+ program2.command("logout").description("Log out and clear saved credentials").option("--all", "Invalidate all sessions across all devices").action(async (opts) => {
319
+ if (opts.all) {
320
+ const cfg = requireAuth();
321
+ const client = new HisaaboClient(cfg);
322
+ try {
323
+ await client.auth.logoutAll();
324
+ await logout();
325
+ success("Logged out from all sessions.");
326
+ } catch (e) {
327
+ if (e instanceof HisaaboApiError) {
328
+ if (e.hisaaboError.code === "unauthorized") {
329
+ await logout();
330
+ success("Logged out from all sessions.");
331
+ return;
332
+ }
333
+ }
334
+ fatalError(String(e instanceof Error ? e.message : e));
335
+ }
336
+ return;
995
337
  }
996
- fatalError(String(e instanceof Error ? e.message : e));
997
- }
338
+ await logout();
339
+ });
340
+ program2.command("whoami").description("Show current user and active business").option("--json", "JSON output").action(async (opts) => {
341
+ await whoami(!!opts.json);
342
+ });
343
+ const profile = program2.command("profile").description("Manage your profile");
344
+ profile.command("update-name <name>").description("Update your display name").action(async (name) => {
345
+ const cfg = requireAuth();
346
+ const client = new HisaaboClient(cfg);
347
+ try {
348
+ await client.auth.updateName({ name });
349
+ success(`Name updated to: ${name}`);
350
+ } catch (e) {
351
+ if (e instanceof HisaaboApiError) {
352
+ const err = e.hisaaboError;
353
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
354
+ if (err.code === "validation_failed") fatalError(String(err.fields?.["name"]?.[0] ?? "Validation failed."), EXIT.VALIDATION);
355
+ }
356
+ fatalError(String(e instanceof Error ? e.message : e));
357
+ }
358
+ });
359
+ program2.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
360
+ const cfg = requireAuth();
361
+ const client = new HisaaboClient(cfg);
362
+ try {
363
+ const businesses = await client.business.list();
364
+ if (opts.json) {
365
+ outputJSON(businesses);
366
+ return;
367
+ }
368
+ businesses.forEach((b, i) => {
369
+ const active = b.id === cfg.businessId ? " [active]" : "";
370
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
371
+ });
372
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
373
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
374
+ rl.close();
375
+ const idx = parseInt(answer.trim(), 10) - 1;
376
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
377
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
378
+ setConfig({ businessId: selected.id, businessName: selected.name });
379
+ success(`Switched to: ${selected.name}`);
380
+ } catch (e) {
381
+ if (e instanceof HisaaboApiError) {
382
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
383
+ }
384
+ fatalError(String(e instanceof Error ? e.message : e));
385
+ }
386
+ });
998
387
  }
999
388
 
1000
- // src/commands/invoice/list.ts
389
+ // src/bin/registrars/dashboard.ts
390
+ function registerDashboardCommands(program2) {
391
+ const dash = program2.command("dashboard").alias("dash").description("Business dashboard & analytics");
392
+ dash.command("summary").description("Financial summary overview (FY to date)").option("--json", "JSON output").action(async (opts) => {
393
+ const { dashboardCommand } = await import("./summary-5KYBA4ZO.js");
394
+ await dashboardCommand({ json: opts.json });
395
+ });
396
+ dash.command("sales-trend").description("Sales trend over time").option("--months <n>", "Number of months to show", (v) => parseInt(v, 10)).option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--granularity <g>", "daily | weekly | monthly").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
397
+ const { dashboardSalesTrendCommand } = await import("./sales-trend-ZYBRUDUU.js");
398
+ await dashboardSalesTrendCommand(opts);
399
+ });
400
+ dash.command("top-outstanding").description("Parties with highest outstanding balances").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
401
+ const { dashboardTopOutstandingCommand } = await import("./top-outstanding-QAMO2E7Y.js");
402
+ await dashboardTopOutstandingCommand(opts);
403
+ });
404
+ dash.command("top-customers").description("Top customers by revenue").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
405
+ const { dashboardTopCustomersCommand } = await import("./top-customers-WSQ2UEJL.js");
406
+ await dashboardTopCustomersCommand({
407
+ limit: opts.limit,
408
+ from: opts.from,
409
+ to: opts.to,
410
+ thisMonth: opts.thisMonth,
411
+ thisFy: opts.thisFy,
412
+ json: opts.json,
413
+ format: opts.format
414
+ });
415
+ });
416
+ dash.command("top-items").description("Top selling items by revenue and quantity").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--type <type>", "Item type filter (product | service)").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
417
+ const { dashboardTopItemsCommand } = await import("./top-items-RWQPDGLN.js");
418
+ await dashboardTopItemsCommand({
419
+ limit: opts.limit,
420
+ type: opts.type,
421
+ from: opts.from,
422
+ to: opts.to,
423
+ thisMonth: opts.thisMonth,
424
+ thisFy: opts.thisFy,
425
+ json: opts.json,
426
+ format: opts.format
427
+ });
428
+ });
429
+ const expensesCmd = dash.command("expenses").description("Expenses broken down by category").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
430
+ const { dashboardExpensesCommand } = await import("./expenses-5N2QSG54.js");
431
+ await dashboardExpensesCommand({
432
+ from: opts.from,
433
+ to: opts.to,
434
+ thisMonth: opts.thisMonth,
435
+ thisFy: opts.thisFy,
436
+ json: opts.json,
437
+ format: opts.format
438
+ });
439
+ });
440
+ expensesCmd.alias("expenses-by-category");
441
+ dash.command("invoice-breakdown").description("Invoice count and amounts by status").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").action(async (opts) => {
442
+ const { dashboardInvoiceBreakdownCommand } = await import("./invoice-breakdown-FN5BEFJD.js");
443
+ await dashboardInvoiceBreakdownCommand({
444
+ from: opts.from,
445
+ to: opts.to,
446
+ thisMonth: opts.thisMonth,
447
+ thisFy: opts.thisFy,
448
+ json: opts.json
449
+ });
450
+ });
451
+ const plCmd = dash.command("profit-loss").description("Profit & Loss statement").option("--from <date>", "Start date (YYYY-MM-DD, default: FY start)").option("--to <date>", "End date (YYYY-MM-DD, default: today)").option("--this-month", "Scope to current calendar month").option("--this-fy", "Scope to current financial year").option("--json", "JSON output").action(async (opts) => {
452
+ const { dashboardProfitLossCommand } = await import("./profit-loss-T4RESJ32.js");
453
+ await dashboardProfitLossCommand({
454
+ from: opts.from,
455
+ to: opts.to,
456
+ thisMonth: opts.thisMonth,
457
+ thisFy: opts.thisFy,
458
+ json: opts.json
459
+ });
460
+ });
461
+ plCmd.alias("pl");
462
+ dash.command("receivables-aging").description("Receivables aging buckets (current / 1-30 / 31-60 / 61-90 / 90+)").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
463
+ const { dashboardReceivablesAgingCommand } = await import("./receivables-aging-6XMENEWS.js");
464
+ await dashboardReceivablesAgingCommand({ json: opts.json, format: opts.format });
465
+ });
466
+ dash.command("payment-modes").description("Payment mode breakdown (cash / UPI / bank transfer / etc.)").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
467
+ const { dashboardPaymentModesCommand } = await import("./payment-modes-WOOT22I7.js");
468
+ await dashboardPaymentModesCommand({
469
+ from: opts.from,
470
+ to: opts.to,
471
+ thisMonth: opts.thisMonth,
472
+ thisFy: opts.thisFy,
473
+ json: opts.json,
474
+ format: opts.format
475
+ });
476
+ });
477
+ dash.command("collection-efficiency").description("Collection rate, DSO, and aging breakdown").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
478
+ const { dashboardCollectionEfficiencyCommand } = await import("./collection-efficiency-U56XNVEE.js");
479
+ await dashboardCollectionEfficiencyCommand({
480
+ from: opts.from,
481
+ to: opts.to,
482
+ thisMonth: opts.thisMonth,
483
+ thisFy: opts.thisFy,
484
+ json: opts.json,
485
+ format: opts.format
486
+ });
487
+ });
488
+ dash.command("monthly-comparison").description("Month-over-month comparison of sales, expenses, profit, and collections").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
489
+ const { dashboardMonthlyComparisonCommand } = await import("./monthly-comparison-T34ZFOHL.js");
490
+ await dashboardMonthlyComparisonCommand({ json: opts.json, format: opts.format });
491
+ });
492
+ }
493
+
494
+ // src/commands/invoice/list.ts
1001
495
  async function invoiceListCommand(opts) {
1002
496
  const cfg = requireAuth();
1003
497
  const client = new HisaaboClient(cfg);
@@ -1100,7 +594,7 @@ async function invoiceListCommand(opts) {
1100
594
  }
1101
595
 
1102
596
  // src/commands/invoice/get.ts
1103
- import chalk4 from "chalk";
597
+ import chalk from "chalk";
1104
598
  async function invoiceGetCommand(id, opts) {
1105
599
  const cfg = requireAuth();
1106
600
  const client = new HisaaboClient(cfg);
@@ -1129,12 +623,12 @@ async function invoiceGetCommand(id, opts) {
1129
623
  const w = Math.min(termWidth() - 2, 68);
1130
624
  const inner = w - 2;
1131
625
  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);
626
+ const statusBadge2 = formatStatus(inv.status);
627
+ const topPad = Math.max(1, inner - title.length - statusBadge2.replace(/\x1b\[[0-9;]*m/g, "").length);
1134
628
  process.stdout.write(`
1135
629
  \u250C${"\u2500".repeat(inner + 2)}\u2510
1136
630
  `);
1137
- process.stdout.write(`\u2502 ${hasColor() ? chalk4.bold(title) : title}${" ".repeat(topPad)}${statusBadge} \u2502
631
+ process.stdout.write(`\u2502 ${hasColor() ? chalk.bold(title) : title}${" ".repeat(topPad)}${statusBadge2} \u2502
1138
632
  `);
1139
633
  divider2();
1140
634
  line2(`Party: ${inv.partyName}`);
@@ -1149,13 +643,13 @@ async function invoiceGetCommand(id, opts) {
1149
643
  `);
1150
644
  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
645
  `);
1152
- inv.lineItems.forEach((item2, i) => {
646
+ inv.lineItems.forEach((item, i) => {
1153
647
  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);
648
+ const desc = item.description.slice(0, 18).padEnd(18);
649
+ const qty = item.quantity.padStart(5);
650
+ const rate = formatAmount(item.unitPrice).padStart(10);
651
+ const tax = `${item.taxPercent}%`.padStart(5);
652
+ const amt = formatAmount(item.amount).padStart(12);
1159
653
  process.stdout.write(`\u2502 ${idx} ${desc} ${qty} ${rate} ${tax} ${amt} \u2502
1160
654
  `);
1161
655
  });
@@ -1174,7 +668,7 @@ async function invoiceGetCommand(id, opts) {
1174
668
  line2(`Round Off:`, formatAmount(inv.roundOff).padStart(16));
1175
669
  process.stdout.write(`\u2502 ${"\u2500".repeat(inner - 2)} \u2502
1176
670
  `);
1177
- line2(`Total:`, (hasColor() ? chalk4.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
671
+ line2(`Total:`, (hasColor() ? chalk.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
1178
672
  line2(`Paid:`, formatAmount(inv.amountPaid).padStart(16));
1179
673
  line2(`Balance:`, formatAmount(inv.balanceDue).padStart(16));
1180
674
  if (inv.notes || inv.termsAndConditions) {
@@ -1200,7 +694,7 @@ async function invoiceGetCommand(id, opts) {
1200
694
  }
1201
695
 
1202
696
  // src/commands/invoice/create.ts
1203
- import * as readline from "readline";
697
+ import * as readline2 from "readline";
1204
698
  async function prompt(rl, question) {
1205
699
  return new Promise((resolve2) => rl.question(question, resolve2));
1206
700
  }
@@ -1215,7 +709,7 @@ async function invoiceCreateCommand(opts) {
1215
709
  let partyName = opts.party ?? "";
1216
710
  if (!partyId) {
1217
711
  if (!isNonInteractive) {
1218
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
712
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1219
713
  console.log(`
1220
714
  New ${invoiceType === "sale" ? "Sale Invoice" : "Purchase Bill"}`);
1221
715
  console.log(" " + "\u2500".repeat(40) + "\n");
@@ -1285,7 +779,7 @@ async function invoiceCreateCommand(opts) {
1285
779
  }
1286
780
  }
1287
781
  } else if (!isNonInteractive) {
1288
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
782
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1289
783
  console.log(" Add Line Items (empty description to finish):\n");
1290
784
  let itemNum = 1;
1291
785
  while (true) {
@@ -1336,13 +830,13 @@ async function invoiceCreateCommand(opts) {
1336
830
  } else {
1337
831
  fatalError("No items specified. Use --item flags.", EXIT.USAGE);
1338
832
  }
1339
- const subtotal = lineItems.reduce((s, item2) => {
1340
- const amt = parseFloat(item2.quantity) * parseFloat(item2.unitPrice);
833
+ const subtotal = lineItems.reduce((s, item) => {
834
+ const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
1341
835
  return s + amt;
1342
836
  }, 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;
837
+ const taxTotal = lineItems.reduce((s, item) => {
838
+ const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
839
+ const tax = parseFloat(item.taxPercent ?? "0") / 100;
1346
840
  return s + amt * tax;
1347
841
  }, 0);
1348
842
  let invoiceDate = todayISO();
@@ -1351,7 +845,7 @@ async function invoiceCreateCommand(opts) {
1351
845
  let notes = opts.notes;
1352
846
  let terms = opts.terms;
1353
847
  if (!isNonInteractive) {
1354
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
848
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1355
849
  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
850
  console.log(` Subtotal: ${formatAmount(String(subtotal))}`);
1357
851
  console.log(` Tax: ${formatAmount(String(taxTotal))}`);
@@ -1375,7 +869,7 @@ async function invoiceCreateCommand(opts) {
1375
869
  process.exit(EXIT.SUCCESS);
1376
870
  }
1377
871
  }
1378
- const invoice2 = await client.invoice.create({
872
+ const invoice = await client.invoice.create({
1379
873
  partyId,
1380
874
  type: invoiceType,
1381
875
  invoiceDate,
@@ -1386,12 +880,12 @@ async function invoiceCreateCommand(opts) {
1386
880
  lineItems
1387
881
  });
1388
882
  if (opts.json) {
1389
- outputJSON(invoice2);
883
+ outputJSON(invoice);
1390
884
  return;
1391
885
  }
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}
886
+ success(`Created: ${invoice.invoiceNumber} for ${formatINR(invoice.totalAmount)}`);
887
+ console.log(` View: hisaabo invoice get ${invoice.invoiceNumber}`);
888
+ console.log(` PDF: hisaabo invoice pdf ${invoice.invoiceNumber}
1395
889
  `);
1396
890
  } catch (e) {
1397
891
  if (e instanceof HisaaboApiError) {
@@ -1490,14 +984,14 @@ async function invoicePdfCommand(id, opts) {
1490
984
  }
1491
985
 
1492
986
  // src/commands/invoice/delete.ts
1493
- import * as readline2 from "readline";
987
+ import * as readline3 from "readline";
1494
988
  async function invoiceDeleteCommand(id, opts) {
1495
989
  const cfg = requireAuth();
1496
990
  const client = new HisaaboClient(cfg);
1497
991
  try {
1498
992
  const inv = await client.invoice.get(id);
1499
993
  if (!opts.yes && process.stdin.isTTY) {
1500
- const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
994
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1501
995
  const answer = await new Promise((resolve2) => {
1502
996
  rl.question(` Delete ${inv.invoiceNumber} (${inv.partyName}, ${inv.totalAmount})? (y/N): `, resolve2);
1503
997
  });
@@ -1525,6 +1019,58 @@ async function invoiceDeleteCommand(id, opts) {
1525
1019
  }
1526
1020
  }
1527
1021
 
1022
+ // src/bin/registrars/invoice.ts
1023
+ function registerInvoiceCommands(program2) {
1024
+ const invoice = program2.command("invoice").description("Invoice management");
1025
+ 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) => {
1026
+ await invoiceListCommand({
1027
+ json: opts.json,
1028
+ format: opts.format,
1029
+ type: opts.type,
1030
+ status: opts.status,
1031
+ party: opts.party,
1032
+ partyId: opts.partyId,
1033
+ from: opts.from,
1034
+ to: opts.to,
1035
+ thisMonth: opts.thisMonth,
1036
+ thisQuarter: opts.thisQuarter,
1037
+ thisFy: opts.thisFy,
1038
+ page: opts.page,
1039
+ limit: opts.limit,
1040
+ search: opts.search,
1041
+ sortBy: opts.sortBy,
1042
+ sortDir: opts.sortDir
1043
+ });
1044
+ });
1045
+ invoice.command("get <id>").description("Get invoice details").option("--json", "JSON output").action(async (id, opts) => {
1046
+ await invoiceGetCommand(id, { json: opts.json });
1047
+ });
1048
+ 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) => {
1049
+ await invoiceCreateCommand({
1050
+ json: opts.json,
1051
+ party: opts.party,
1052
+ partyId: opts.partyId,
1053
+ type: opts.type,
1054
+ items: opts.item,
1055
+ qty: opts.qty,
1056
+ rate: opts.rate,
1057
+ delivery: opts.delivery,
1058
+ notes: opts.notes,
1059
+ terms: opts.terms,
1060
+ yes: opts.yes
1061
+ });
1062
+ });
1063
+ invoice.command("status <id> <status>").description("Update invoice status").option("--json", "JSON output").action(async (id, status, opts) => {
1064
+ await invoiceStatusCommand(id, status, { json: opts.json });
1065
+ });
1066
+ 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) => {
1067
+ await invoicePdfCommand(id, { output: opts.output, open: opts.open });
1068
+ });
1069
+ invoice.command("delete <id>").description("Delete an invoice").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1070
+ await invoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
1071
+ });
1072
+ }
1073
+
1528
1074
  // src/commands/party/list.ts
1529
1075
  async function partyListCommand(opts) {
1530
1076
  const cfg = requireAuth();
@@ -1579,25 +1125,25 @@ async function partyGetCommand(id, opts) {
1579
1125
  const cfg = requireAuth();
1580
1126
  const client = new HisaaboClient(cfg);
1581
1127
  try {
1582
- const party2 = await client.party.get(id);
1128
+ const party = await client.party.get(id);
1583
1129
  if (opts.json) {
1584
- outputJSON(party2);
1130
+ outputJSON(party);
1585
1131
  return;
1586
1132
  }
1587
1133
  console.log(`
1588
- ${party2.name} (${party2.type.toUpperCase()})`);
1134
+ ${party.name} (${party.type.toUpperCase()})`);
1589
1135
  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)}`);
1136
+ if (party.phone) console.log(` Phone: ${party.phone}`);
1137
+ if (party.email) console.log(` Email: ${party.email}`);
1138
+ if (party.gstin) console.log(` GSTIN: ${party.gstin}`);
1139
+ if (party.pan) console.log(` PAN: ${party.pan}`);
1140
+ if (party.billingAddress) console.log(` Address: ${party.billingAddress}`);
1141
+ if (party.city) console.log(` City: ${party.city}`);
1142
+ if (party.state) console.log(` State: ${party.state}`);
1143
+ if (party.category) console.log(` Category: ${party.category}`);
1144
+ if (party.creditPeriodDays) console.log(` Credit Period: ${party.creditPeriodDays} days`);
1145
+ if (party.creditLimit && parseFloat(party.creditLimit) > 0) console.log(` Credit Limit: ${formatINR(party.creditLimit)}`);
1146
+ console.log(` Balance: ${formatINR(party.balance)}`);
1601
1147
  console.log();
1602
1148
  } catch (e) {
1603
1149
  if (e instanceof HisaaboApiError) {
@@ -1611,7 +1157,7 @@ async function partyGetCommand(id, opts) {
1611
1157
  }
1612
1158
 
1613
1159
  // src/commands/party/create.ts
1614
- import * as readline3 from "readline";
1160
+ import * as readline4 from "readline";
1615
1161
  async function prompt2(rl, q) {
1616
1162
  return new Promise((resolve2) => rl.question(q, resolve2));
1617
1163
  }
@@ -1627,7 +1173,7 @@ async function partyCreateCommand(opts) {
1627
1173
  let city = opts.city;
1628
1174
  let category = opts.category;
1629
1175
  if (!isNonInteractive) {
1630
- const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1176
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1631
1177
  console.log("\n New Party\n " + "\u2500".repeat(30) + "\n");
1632
1178
  if (!type) {
1633
1179
  const t = await prompt2(rl, " Type (customer/supplier) [customer]: ");
@@ -1657,13 +1203,13 @@ async function partyCreateCommand(opts) {
1657
1203
  if (!name) fatalError("--name is required", EXIT.USAGE);
1658
1204
  if (!type) type = "customer";
1659
1205
  try {
1660
- const party2 = await client.party.create({ type, name, phone, email, gstin, city, category });
1206
+ const party = await client.party.create({ type, name, phone, email, gstin, city, category });
1661
1207
  if (opts.json) {
1662
- outputJSON(party2);
1208
+ outputJSON(party);
1663
1209
  return;
1664
1210
  }
1665
- success(`Created: ${party2.name} (${party2.type})`);
1666
- console.log(` ID: ${party2.id}
1211
+ success(`Created: ${party.name} (${party.type})`);
1212
+ console.log(` ID: ${party.id}
1667
1213
  `);
1668
1214
  } catch (e) {
1669
1215
  if (e instanceof HisaaboApiError) {
@@ -1677,16 +1223,16 @@ async function partyCreateCommand(opts) {
1677
1223
  }
1678
1224
 
1679
1225
  // src/commands/party/delete.ts
1680
- import * as readline4 from "readline";
1226
+ import * as readline5 from "readline";
1681
1227
  async function partyDeleteCommand(id, opts) {
1682
1228
  const cfg = requireAuth();
1683
1229
  const client = new HisaaboClient(cfg);
1684
1230
  try {
1685
- const party2 = await client.party.get(id);
1231
+ const party = await client.party.get(id);
1686
1232
  if (!opts.yes && process.stdin.isTTY) {
1687
- const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1233
+ const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1688
1234
  const answer = await new Promise((resolve2) => {
1689
- rl.question(` Delete ${party2.name}? (y/N): `, resolve2);
1235
+ rl.question(` Delete ${party.name}? (y/N): `, resolve2);
1690
1236
  });
1691
1237
  rl.close();
1692
1238
  if (answer.trim().toLowerCase() !== "y") {
@@ -1699,7 +1245,7 @@ async function partyDeleteCommand(id, opts) {
1699
1245
  outputJSON(result);
1700
1246
  return;
1701
1247
  }
1702
- success(`Deleted: ${party2.name}`);
1248
+ success(`Deleted: ${party.name}`);
1703
1249
  } catch (e) {
1704
1250
  if (e instanceof HisaaboApiError) {
1705
1251
  const err = e.hisaaboError;
@@ -1757,8 +1303,36 @@ async function partyLedgerCommand(partyId, opts) {
1757
1303
  }
1758
1304
  }
1759
1305
 
1306
+ // src/bin/registrars/party.ts
1307
+ function registerPartyCommands(program2) {
1308
+ const party = program2.command("party").description("Party (customer/supplier) management");
1309
+ 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) => {
1310
+ await partyListCommand({
1311
+ json: opts.json,
1312
+ format: opts.format,
1313
+ type: opts.type,
1314
+ search: opts.search,
1315
+ category: opts.category,
1316
+ page: opts.page,
1317
+ limit: opts.limit
1318
+ });
1319
+ });
1320
+ party.command("get <id>").description("Get party details").option("--json", "JSON output").action(async (id, opts) => {
1321
+ await partyGetCommand(id, { json: opts.json });
1322
+ });
1323
+ 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) => {
1324
+ await partyCreateCommand(opts);
1325
+ });
1326
+ party.command("delete <id>").description("Delete a party").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1327
+ await partyDeleteCommand(id, { yes: opts.yes, json: opts.json });
1328
+ });
1329
+ 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) => {
1330
+ await partyLedgerCommand(partyId, opts);
1331
+ });
1332
+ }
1333
+
1760
1334
  // src/commands/item/list.ts
1761
- import chalk5 from "chalk";
1335
+ import chalk2 from "chalk";
1762
1336
  async function itemListCommand(opts) {
1763
1337
  const cfg = requireAuth();
1764
1338
  const client = new HisaaboClient(cfg);
@@ -1799,7 +1373,7 @@ async function itemListCommand(opts) {
1799
1373
  const low = row.lowStockAlert;
1800
1374
  const isLow = low && parseFloat(qty) <= parseFloat(low);
1801
1375
  const str = row.itemType === "service" ? "-" : isLow ? `${qty} !` : qty;
1802
- return isLow && hasColor() ? chalk5.red(str) : str;
1376
+ return isLow && hasColor() ? chalk2.red(str) : str;
1803
1377
  }
1804
1378
  },
1805
1379
  { key: "taxPercent", header: "Tax%", width: 6, format: (v) => `${v ?? 0}%` },
@@ -1826,7 +1400,7 @@ async function itemListCommand(opts) {
1826
1400
  }
1827
1401
 
1828
1402
  // src/commands/item/create.ts
1829
- import * as readline5 from "readline";
1403
+ import * as readline6 from "readline";
1830
1404
  async function prompt3(rl, q) {
1831
1405
  return new Promise((resolve2) => rl.question(q, resolve2));
1832
1406
  }
@@ -1844,7 +1418,7 @@ async function itemCreateCommand(opts) {
1844
1418
  let category = opts.category;
1845
1419
  let itemType = opts.type ?? "product";
1846
1420
  if (!isNonInteractive) {
1847
- const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1421
+ const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1848
1422
  console.log("\n New Item\n " + "\u2500".repeat(30) + "\n");
1849
1423
  if (!name) name = (await prompt3(rl, " Name: ")).trim();
1850
1424
  const typeStr = await prompt3(rl, " Type (product/service) [product]: ");
@@ -1869,7 +1443,7 @@ async function itemCreateCommand(opts) {
1869
1443
  }
1870
1444
  if (!name) fatalError("--name is required", EXIT.USAGE);
1871
1445
  try {
1872
- const item2 = await client.item.create({
1446
+ const item = await client.item.create({
1873
1447
  name,
1874
1448
  unit,
1875
1449
  salePrice,
@@ -1881,11 +1455,11 @@ async function itemCreateCommand(opts) {
1881
1455
  itemType
1882
1456
  });
1883
1457
  if (opts.json) {
1884
- outputJSON(item2);
1458
+ outputJSON(item);
1885
1459
  return;
1886
1460
  }
1887
- success(`Created: ${item2.name} (${item2.itemType})`);
1888
- console.log(` ID: ${item2.id}
1461
+ success(`Created: ${item.name} (${item.itemType})`);
1462
+ console.log(` ID: ${item.id}
1889
1463
  `);
1890
1464
  } catch (e) {
1891
1465
  if (e instanceof HisaaboApiError) {
@@ -1899,16 +1473,16 @@ async function itemCreateCommand(opts) {
1899
1473
  }
1900
1474
 
1901
1475
  // src/commands/item/delete.ts
1902
- import * as readline6 from "readline";
1476
+ import * as readline7 from "readline";
1903
1477
  async function itemDeleteCommand(id, opts) {
1904
1478
  const cfg = requireAuth();
1905
1479
  const client = new HisaaboClient(cfg);
1906
1480
  try {
1907
- const item2 = await client.item.get(id);
1481
+ const item = await client.item.get(id);
1908
1482
  if (!opts.yes && process.stdin.isTTY) {
1909
- const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1483
+ const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
1910
1484
  const answer = await new Promise((resolve2) => {
1911
- rl.question(` Delete ${item2.name}? (y/N): `, resolve2);
1485
+ rl.question(` Delete ${item.name}? (y/N): `, resolve2);
1912
1486
  });
1913
1487
  rl.close();
1914
1488
  if (answer.trim().toLowerCase() !== "y") {
@@ -1921,7 +1495,7 @@ async function itemDeleteCommand(id, opts) {
1921
1495
  outputJSON(result);
1922
1496
  return;
1923
1497
  }
1924
- success(`Deleted: ${item2.name}`);
1498
+ success(`Deleted: ${item.name}`);
1925
1499
  } catch (e) {
1926
1500
  if (e instanceof HisaaboApiError) {
1927
1501
  const err = e.hisaaboError;
@@ -1966,6 +1540,69 @@ async function itemStockCommand(id, adjustment, opts) {
1966
1540
  }
1967
1541
  }
1968
1542
 
1543
+ // src/bin/registrars/item.ts
1544
+ function registerItemCommands(program2) {
1545
+ const item = program2.command("item").description("Item / product management");
1546
+ 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) => {
1547
+ await itemListCommand({
1548
+ json: opts.json,
1549
+ format: opts.format,
1550
+ search: opts.search,
1551
+ category: opts.category,
1552
+ type: opts.type,
1553
+ lowStock: opts.lowStock,
1554
+ page: opts.page,
1555
+ limit: opts.limit
1556
+ });
1557
+ });
1558
+ item.command("get <id>").description("Get item details").option("--json", "JSON output").action(async (id, opts) => {
1559
+ const cfg = requireAuth();
1560
+ const client = new HisaaboClient(cfg);
1561
+ try {
1562
+ const it = await client.item.get(id);
1563
+ if (opts.json) {
1564
+ outputJSON(it);
1565
+ return;
1566
+ }
1567
+ console.log(`
1568
+ ${it.name} (${it.itemType})`);
1569
+ console.log(" " + "\u2500".repeat(40));
1570
+ if (it.sku) console.log(` SKU: ${it.sku}`);
1571
+ if (it.hsn) console.log(` HSN: ${it.hsn}`);
1572
+ console.log(` Unit: ${it.unit}`);
1573
+ if (it.salePrice) console.log(` Sale: \u20B9${it.salePrice}`);
1574
+ if (it.purchasePrice) console.log(` Purchase: \u20B9${it.purchasePrice}`);
1575
+ console.log(` Tax: ${it.taxPercent}%`);
1576
+ if (it.itemType === "product") console.log(` Stock: ${it.stockQuantity}`);
1577
+ console.log();
1578
+ } catch (e) {
1579
+ if (e instanceof HisaaboApiError && e.hisaaboError.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1580
+ fatalError(String(e instanceof Error ? e.message : e));
1581
+ }
1582
+ });
1583
+ 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) => {
1584
+ await itemCreateCommand({
1585
+ json: opts.json,
1586
+ name: opts.name,
1587
+ unit: opts.unit,
1588
+ salePrice: opts.salePrice,
1589
+ purchasePrice: opts.purchasePrice,
1590
+ taxPercent: opts.tax,
1591
+ stock: opts.stock,
1592
+ hsn: opts.hsn,
1593
+ category: opts.category,
1594
+ type: opts.type,
1595
+ yes: opts.yes
1596
+ });
1597
+ });
1598
+ item.command("delete <id>").description("Delete an item").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1599
+ await itemDeleteCommand(id, { yes: opts.yes, json: opts.json });
1600
+ });
1601
+ 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) => {
1602
+ await itemStockCommand(id, adjustment, { json: opts.json, reason: opts.reason });
1603
+ });
1604
+ }
1605
+
1969
1606
  // src/commands/payment/list.ts
1970
1607
  async function paymentListCommand(opts) {
1971
1608
  const cfg = requireAuth();
@@ -2013,7 +1650,7 @@ async function paymentListCommand(opts) {
2013
1650
  }
2014
1651
 
2015
1652
  // src/commands/payment/create.ts
2016
- import * as readline7 from "readline";
1653
+ import * as readline8 from "readline";
2017
1654
  async function prompt4(rl, q) {
2018
1655
  return new Promise((resolve2) => rl.question(q, resolve2));
2019
1656
  }
@@ -2029,7 +1666,7 @@ async function paymentCreateCommand(opts) {
2029
1666
  let notes = opts.notes;
2030
1667
  try {
2031
1668
  if (!isNonInteractive) {
2032
- const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
1669
+ const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
2033
1670
  console.log("\n Record Payment\n " + "\u2500".repeat(30) + "\n");
2034
1671
  if (!partyId) {
2035
1672
  const search = await prompt4(rl, " Select Party:\n > Search: ");
@@ -2092,7 +1729,7 @@ async function paymentCreateCommand(opts) {
2092
1729
  if (!partyId) fatalError("--party-id is required", EXIT.USAGE);
2093
1730
  if (!amount) fatalError("--amount is required", EXIT.USAGE);
2094
1731
  if (!mode) mode = "cash";
2095
- const payment2 = await client.payment.create({
1732
+ const payment = await client.payment.create({
2096
1733
  partyId,
2097
1734
  amount,
2098
1735
  mode,
@@ -2102,10 +1739,10 @@ async function paymentCreateCommand(opts) {
2102
1739
  invoiceId: opts.invoiceId
2103
1740
  });
2104
1741
  if (opts.json) {
2105
- outputJSON(payment2);
1742
+ outputJSON(payment);
2106
1743
  return;
2107
1744
  }
2108
- success(`Recorded: ${payment2.paymentNumber} for ${formatINR(payment2.amount)}`);
1745
+ success(`Recorded: ${payment.paymentNumber} for ${formatINR(payment.amount)}`);
2109
1746
  } catch (e) {
2110
1747
  if (e instanceof HisaaboApiError) {
2111
1748
  const err = e.hisaaboError;
@@ -2118,17 +1755,17 @@ async function paymentCreateCommand(opts) {
2118
1755
  }
2119
1756
 
2120
1757
  // src/commands/payment/delete.ts
2121
- import * as readline8 from "readline";
1758
+ import * as readline9 from "readline";
2122
1759
  async function paymentDeleteCommand(id, opts) {
2123
1760
  const cfg = requireAuth();
2124
1761
  const client = new HisaaboClient(cfg);
2125
1762
  try {
2126
- const payment2 = await client.payment.getById(id);
2127
- if (!payment2) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
1763
+ const payment = await client.payment.getById(id);
1764
+ if (!payment) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
2128
1765
  if (!opts.yes && process.stdin.isTTY) {
2129
- const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
1766
+ const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
2130
1767
  const answer = await new Promise((resolve2) => {
2131
- rl.question(` Delete ${payment2.paymentNumber} (${formatINR(payment2.amount)})? (y/N): `, resolve2);
1768
+ rl.question(` Delete ${payment.paymentNumber} (${formatINR(payment.amount)})? (y/N): `, resolve2);
2132
1769
  });
2133
1770
  rl.close();
2134
1771
  if (answer.trim().toLowerCase() !== "y") {
@@ -2141,7 +1778,7 @@ async function paymentDeleteCommand(id, opts) {
2141
1778
  outputJSON(result);
2142
1779
  return;
2143
1780
  }
2144
- success(`Deleted: ${payment2.paymentNumber}`);
1781
+ success(`Deleted: ${payment.paymentNumber}`);
2145
1782
  } catch (e) {
2146
1783
  if (e instanceof HisaaboApiError) {
2147
1784
  const err = e.hisaaboError;
@@ -2154,6 +1791,63 @@ async function paymentDeleteCommand(id, opts) {
2154
1791
  }
2155
1792
  }
2156
1793
 
1794
+ // src/bin/registrars/payment.ts
1795
+ function registerPaymentCommands(program2) {
1796
+ const payment = program2.command("payment").description("Payment recording");
1797
+ 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) => {
1798
+ await paymentListCommand(opts);
1799
+ });
1800
+ 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) => {
1801
+ await paymentCreateCommand({
1802
+ json: opts.json,
1803
+ partyId: opts.partyId,
1804
+ party: opts.party,
1805
+ amount: opts.amount,
1806
+ mode: opts.mode,
1807
+ invoiceId: opts.invoiceId,
1808
+ reference: opts.reference,
1809
+ date: opts.date,
1810
+ notes: opts.notes,
1811
+ yes: opts.yes
1812
+ });
1813
+ });
1814
+ payment.command("delete <id>").description("Delete a payment").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1815
+ await paymentDeleteCommand(id, { yes: opts.yes, json: opts.json });
1816
+ });
1817
+ payment.command("get <id>").description("Get payment details").option("--json", "JSON output").action(async (id, opts) => {
1818
+ const { paymentGetCommand } = await import("./get-GWH6S5SJ.js");
1819
+ await paymentGetCommand(id, { json: opts.json });
1820
+ });
1821
+ payment.command("update <id>").description("Update a payment").option("--amount <amount>", "New amount").option("--mode <mode>", "Payment mode: cash, upi, bank, cheque, other").option("--date <YYYY-MM-DD>", "Payment date").option("--reference <ref>", "Reference number (empty string to clear)").option("--notes <text>", "Notes (empty string to clear)").option("--json", "JSON output").action(async (id, opts) => {
1822
+ const { paymentUpdateCommand } = await import("./update-JU2X3XU5.js");
1823
+ await paymentUpdateCommand(id, {
1824
+ json: opts.json,
1825
+ amount: opts.amount,
1826
+ mode: opts.mode,
1827
+ date: opts.date,
1828
+ reference: opts.reference,
1829
+ notes: opts.notes
1830
+ });
1831
+ });
1832
+ payment.command("unpaid-invoices <partyId>").description("List unpaid invoices for a party").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (partyId, opts) => {
1833
+ const { paymentUnpaidInvoicesCommand } = await import("./unpaid-invoices-WB3TK5B4.js");
1834
+ await paymentUnpaidInvoicesCommand(partyId, { json: opts.json, format: opts.format });
1835
+ });
1836
+ payment.command("untracked").description("List payments not linked to a bank account").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (opts) => {
1837
+ const { paymentUntrackedCommand } = await import("./untracked-H733MYJL.js");
1838
+ await paymentUntrackedCommand({
1839
+ json: opts.json,
1840
+ format: opts.format,
1841
+ page: opts.page,
1842
+ limit: opts.limit
1843
+ });
1844
+ });
1845
+ payment.command("default-account").description("Show recommended bank account for payments").option("--party-id <id>", "Party UUID to scope recommendation").option("--json", "JSON output").action(async (opts) => {
1846
+ const { paymentDefaultAccountCommand } = await import("./default-account-AE6EXZZR.js");
1847
+ await paymentDefaultAccountCommand({ json: opts.json, partyId: opts.partyId });
1848
+ });
1849
+ }
1850
+
2157
1851
  // src/commands/expense/list.ts
2158
1852
  async function expenseListCommand(opts) {
2159
1853
  const cfg = requireAuth();
@@ -2207,7 +1901,7 @@ async function expenseCreateCommand(opts) {
2207
1901
  if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2208
1902
  const mode = opts.mode ?? "cash";
2209
1903
  try {
2210
- const expense2 = await client.expense.create({
1904
+ const expense = await client.expense.create({
2211
1905
  category: opts.category,
2212
1906
  amount: opts.amount,
2213
1907
  mode,
@@ -2216,10 +1910,10 @@ async function expenseCreateCommand(opts) {
2216
1910
  referenceNumber: opts.reference
2217
1911
  });
2218
1912
  if (opts.json) {
2219
- outputJSON(expense2);
1913
+ outputJSON(expense);
2220
1914
  return;
2221
1915
  }
2222
- success(`Created: ${expense2.category} ${formatINR(expense2.amount)}`);
1916
+ success(`Created: ${expense.category} ${formatINR(expense.amount)}`);
2223
1917
  } catch (e) {
2224
1918
  if (e instanceof HisaaboApiError) {
2225
1919
  const err = e.hisaaboError;
@@ -2232,14 +1926,14 @@ async function expenseCreateCommand(opts) {
2232
1926
  }
2233
1927
 
2234
1928
  // src/commands/expense/delete.ts
2235
- import * as readline9 from "readline";
1929
+ import * as readline10 from "readline";
2236
1930
  async function expenseDeleteCommand(id, opts) {
2237
1931
  const cfg = requireAuth();
2238
1932
  const client = new HisaaboClient(cfg);
2239
1933
  try {
2240
1934
  const _list = await client.expense.list({ page: 1, limit: 1 });
2241
1935
  if (!opts.yes && process.stdin.isTTY) {
2242
- const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
1936
+ const rl = readline10.createInterface({ input: process.stdin, output: process.stdout });
2243
1937
  const answer = await new Promise((resolve2) => {
2244
1938
  rl.question(` Delete expense ${id}? (y/N): `, resolve2);
2245
1939
  });
@@ -2267,6 +1961,44 @@ async function expenseDeleteCommand(id, opts) {
2267
1961
  }
2268
1962
  }
2269
1963
 
1964
+ // src/bin/registrars/expense.ts
1965
+ function registerExpenseCommands(program2) {
1966
+ const expense = program2.command("expense").description("Expense tracking");
1967
+ 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) => {
1968
+ await expenseListCommand(opts);
1969
+ });
1970
+ 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) => {
1971
+ await expenseCreateCommand({
1972
+ json: opts.json,
1973
+ category: opts.category,
1974
+ amount: opts.amount,
1975
+ mode: opts.mode,
1976
+ description: opts.description,
1977
+ date: opts.date,
1978
+ reference: opts.reference
1979
+ });
1980
+ });
1981
+ expense.command("delete <id>").description("Delete an expense").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1982
+ await expenseDeleteCommand(id, { yes: opts.yes, json: opts.json });
1983
+ });
1984
+ expense.command("update <id>").description("Update an expense").option("--amount <amount>", "New amount").option("--category <cat>", "Expense category").option("--date <YYYY-MM-DD>", "Expense date").option("--description <text>", "Description").option("--payment-mode <mode>", "Payment mode: cash, upi, bank, cheque, other").option("--reference <ref>", "Reference number").option("--json", "JSON output").action(async (id, opts) => {
1985
+ const { expenseUpdateCommand } = await import("./update-TLBUIC5J.js");
1986
+ await expenseUpdateCommand(id, {
1987
+ json: opts.json,
1988
+ amount: opts.amount,
1989
+ category: opts.category,
1990
+ date: opts.date,
1991
+ description: opts.description,
1992
+ paymentMode: opts.paymentMode,
1993
+ reference: opts.reference
1994
+ });
1995
+ });
1996
+ expense.command("categories").description("List all expense categories").option("--json", "JSON output").action(async (opts) => {
1997
+ const { expenseCategoriesCommand } = await import("./categories-64WWZTND.js");
1998
+ await expenseCategoriesCommand({ json: opts.json });
1999
+ });
2000
+ }
2001
+
2270
2002
  // src/commands/gst/index.ts
2271
2003
  import * as fs2 from "fs";
2272
2004
  function resolveMonthYear(opts) {
@@ -2285,9 +2017,9 @@ async function gstR1Command(opts) {
2285
2017
  const client = new HisaaboClient(cfg);
2286
2018
  const { month, year } = resolveMonthYear(opts);
2287
2019
  try {
2288
- const report2 = await client.gst.gstr1({ month, year });
2020
+ const report = await client.gst.gstr1({ month, year });
2289
2021
  if (opts.json) {
2290
- outputJSON(report2);
2022
+ outputJSON(report);
2291
2023
  return;
2292
2024
  }
2293
2025
  const quarterLabel = opts.quarter ? `${opts.quarter} ` : "";
@@ -2295,8 +2027,8 @@ async function gstR1Command(opts) {
2295
2027
  GSTR-1 Summary ${quarterLabel}FY ${year}-${String(year + 1).slice(2)}`);
2296
2028
  console.log(` ${"\u2550".repeat(60)}
2297
2029
  `);
2298
- if (report2.summary && typeof report2.summary === "object") {
2299
- const s = report2.summary;
2030
+ if (report.summary && typeof report.summary === "object") {
2031
+ const s = report.summary;
2300
2032
  if (s["totalTaxableValue"]) console.log(` Total Taxable: ${formatAmount(String(s["totalTaxableValue"]))}`);
2301
2033
  if (s["totalTax"]) console.log(` Total Tax: ${formatAmount(String(s["totalTax"]))}`);
2302
2034
  if (s["totalInvoices"]) console.log(` Total Invoices: ${s["totalInvoices"]}`);
@@ -2318,17 +2050,17 @@ async function gstR3bCommand(opts) {
2318
2050
  const client = new HisaaboClient(cfg);
2319
2051
  const { month, year } = resolveMonthYear(opts);
2320
2052
  try {
2321
- const report2 = await client.gst.gstr3b({ month, year });
2053
+ const report = await client.gst.gstr3b({ month, year });
2322
2054
  if (opts.json) {
2323
- outputJSON(report2);
2055
+ outputJSON(report);
2324
2056
  return;
2325
2057
  }
2326
2058
  console.log(`
2327
2059
  GSTR-3B Summary ${month}/${year}`);
2328
2060
  console.log(` ${"\u2550".repeat(60)}
2329
2061
  `);
2330
- if (report2.summary && typeof report2.summary === "object") {
2331
- const s = report2.summary;
2062
+ if (report.summary && typeof report.summary === "object") {
2063
+ const s = report.summary;
2332
2064
  Object.entries(s).forEach(([k, v]) => {
2333
2065
  console.log(` ${k.padEnd(28)}: ${String(v ?? "-")}`);
2334
2066
  });
@@ -2362,6 +2094,20 @@ async function gstR1CsvCommand(opts) {
2362
2094
  }
2363
2095
  }
2364
2096
 
2097
+ // src/bin/registrars/gst.ts
2098
+ function registerGstCommands(program2) {
2099
+ const gst = program2.command("gst").description("GST reports");
2100
+ 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) => {
2101
+ await gstR1Command({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
2102
+ });
2103
+ 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) => {
2104
+ await gstR3bCommand({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
2105
+ });
2106
+ 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) => {
2107
+ await gstR1CsvCommand({ quarter: opts.quarter, month: opts.month, year: opts.year, output: opts.output });
2108
+ });
2109
+ }
2110
+
2365
2111
  // src/commands/report/index.ts
2366
2112
  function resolveRange(opts) {
2367
2113
  if (opts.thisFy) return { from: fyStart(), to: todayISO() };
@@ -2542,41 +2288,40 @@ async function reportStockSummaryCommand(opts) {
2542
2288
  fatalError(String(e instanceof Error ? e.message : e));
2543
2289
  }
2544
2290
  }
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) {
2291
+ async function reportSalesRegisterCommand(opts) {
2552
2292
  const cfg = requireAuth();
2553
2293
  const client = new HisaaboClient(cfg);
2294
+ const { from, to } = resolveRange(opts);
2554
2295
  try {
2555
- const [accounts, summary] = await Promise.all([
2556
- client.bankAccount.list(),
2557
- client.bankAccount.summary()
2558
- ]);
2296
+ const result = await client.reports.salesRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
2559
2297
  if (opts.json) {
2560
- outputJSON({ accounts, summary });
2298
+ outputJSON(result);
2561
2299
  return;
2562
2300
  }
2563
- console.log("\n Bank Accounts\n");
2564
- console.log(` ${"\u2550".repeat(60)}
2301
+ console.log(`
2302
+ Sales Register ${from} \u2192 ${to}
2303
+ `);
2304
+ console.log(` ${"\u2550".repeat(80)}
2565
2305
  `);
2306
+ const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
2566
2307
  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" : "" }
2308
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2309
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2310
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2311
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2312
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2313
+ { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2314
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
2573
2315
  ];
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)}
2316
+ if (opts.format === "tsv") outputTSV(rows, cols);
2317
+ else if (opts.format === "csv") outputCSV(rows, cols);
2318
+ else outputTable(rows, cols);
2319
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2320
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2321
+ console.log(`
2322
+ Total: ${formatAmount(String(total)).padStart(14)}
2579
2323
  `);
2324
+ }
2580
2325
  } catch (e) {
2581
2326
  if (e instanceof HisaaboApiError) {
2582
2327
  const err = e.hisaaboError;
@@ -2586,24 +2331,40 @@ async function bankListCommand(opts) {
2586
2331
  fatalError(String(e instanceof Error ? e.message : e));
2587
2332
  }
2588
2333
  }
2589
- async function bankGetCommand(id, opts) {
2334
+ async function reportPurchaseRegisterCommand(opts) {
2590
2335
  const cfg = requireAuth();
2591
2336
  const client = new HisaaboClient(cfg);
2337
+ const { from, to } = resolveRange(opts);
2592
2338
  try {
2593
- const account = await client.bankAccount.get(id);
2594
- if (!account) fatalError(`Bank account not found: ${id}`, EXIT.NOT_FOUND);
2339
+ const result = await client.reports.purchaseRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
2595
2340
  if (opts.json) {
2596
- outputJSON(account);
2341
+ outputJSON(result);
2597
2342
  return;
2598
2343
  }
2599
2344
  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();
2345
+ Purchase Register ${from} \u2192 ${to}
2346
+ `);
2347
+ console.log(` ${"\u2550".repeat(80)}
2348
+ `);
2349
+ const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
2350
+ const cols = [
2351
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2352
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2353
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2354
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2355
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2356
+ { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2357
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
2358
+ ];
2359
+ if (opts.format === "tsv") outputTSV(rows, cols);
2360
+ else if (opts.format === "csv") outputCSV(rows, cols);
2361
+ else outputTable(rows, cols);
2362
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2363
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2364
+ console.log(`
2365
+ Total: ${formatAmount(String(total)).padStart(14)}
2366
+ `);
2367
+ }
2607
2368
  } catch (e) {
2608
2369
  if (e instanceof HisaaboApiError) {
2609
2370
  const err = e.hisaaboError;
@@ -2613,117 +2374,174 @@ async function bankGetCommand(id, opts) {
2613
2374
  fatalError(String(e instanceof Error ? e.message : e));
2614
2375
  }
2615
2376
  }
2616
- async function bankCreateCommand(opts) {
2377
+ async function reportPartyStatementCommand(partyId, opts) {
2617
2378
  const cfg = requireAuth();
2618
2379
  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);
2380
+ const { from, to } = resolveRange(opts);
2642
2381
  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
- });
2382
+ const result = await client.reports.partyStatement({ partyId, fromDate: from, toDate: to });
2652
2383
  if (opts.json) {
2653
- outputJSON(account);
2384
+ outputJSON(result);
2654
2385
  return;
2655
2386
  }
2656
- success(`Created: ${account.accountName}`);
2657
- console.log(` ID: ${account.id}
2387
+ const res = result;
2388
+ const partyName = String(res["partyName"] ?? res["party"] ?? partyId);
2389
+ console.log(`
2390
+ Party Statement \u2014 ${partyName} ${from} \u2192 ${to}
2391
+ `);
2392
+ console.log(` ${"\u2550".repeat(75)}
2393
+ `);
2394
+ const openingBalance = String(res["openingBalance"] ?? "0");
2395
+ console.log(` Opening Balance: ${formatAmount(openingBalance).padStart(14)}
2396
+ `);
2397
+ const rows = Array.isArray(res["entries"]) ? res["entries"] : Array.isArray(res["rows"]) ? res["rows"] : [];
2398
+ const cols = [
2399
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? v ?? "")) },
2400
+ { key: "type", header: "Type", width: 12, format: (v, r) => String(r.type ?? r.entryType ?? v ?? "-") },
2401
+ { key: "number", header: "Number", width: 14, format: (v, r) => String(r.number ?? r.invoiceNumber ?? v ?? "-") },
2402
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.debit ?? v ?? "0")) !== 0 ? formatAmount(String(r.debit ?? v)) : "-" },
2403
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.credit ?? v ?? "0")) !== 0 ? formatAmount(String(r.credit ?? v)) : "-" },
2404
+ { key: "balance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.balance ?? r.runningBalance ?? v ?? "0")) }
2405
+ ];
2406
+ if (opts.format === "tsv") outputTSV(rows, cols);
2407
+ else if (opts.format === "csv") outputCSV(rows, cols);
2408
+ else outputTable(rows, cols);
2409
+ if (opts.format !== "tsv" && opts.format !== "csv") {
2410
+ const closingBalance = String(res["closingBalance"] ?? res["balance"] ?? "0");
2411
+ console.log(`
2412
+ Closing Balance: ${formatAmount(closingBalance).padStart(14)}
2658
2413
  `);
2414
+ }
2659
2415
  } catch (e) {
2660
2416
  if (e instanceof HisaaboApiError) {
2661
2417
  const err = e.hisaaboError;
2662
2418
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2663
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2664
2419
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2665
2420
  }
2666
2421
  fatalError(String(e instanceof Error ? e.message : e));
2667
2422
  }
2668
2423
  }
2669
- async function bankTransferCommand(opts) {
2424
+ async function reportPaymentSummaryCommand(opts) {
2670
2425
  const cfg = requireAuth();
2671
2426
  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);
2427
+ const { from, to } = resolveRange(opts);
2675
2428
  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
2429
+ const result = await client.reports.paymentSummary({
2430
+ fromDate: from,
2431
+ toDate: to,
2432
+ type: opts.type ?? "both"
2682
2433
  });
2683
2434
  if (opts.json) {
2684
2435
  outputJSON(result);
2685
2436
  return;
2686
2437
  }
2687
- success(`Transfer recorded: ${formatINR(opts.amount)}`);
2688
- } catch (e) {
2689
- if (e instanceof HisaaboApiError) {
2438
+ const res = result;
2439
+ console.log(`
2440
+ Payment Summary ${from} \u2192 ${to}
2441
+ `);
2442
+ console.log(" " + "\u2550".repeat(60) + "\n");
2443
+ const received = String(res["totalReceived"] ?? res["received"] ?? "0");
2444
+ const made = String(res["totalMade"] ?? res["made"] ?? "0");
2445
+ const net = String(res["net"] ?? res["netCash"] ?? "0");
2446
+ console.log(` Total Received: ${formatAmount(received).padStart(14)}`);
2447
+ console.log(` Total Made: ${formatAmount(made).padStart(14)}`);
2448
+ console.log(` Net: ${formatAmount(net).padStart(14)}`);
2449
+ const breakdown = res["breakdown"] ?? res["byMode"] ?? res["modes"];
2450
+ if (breakdown && Array.isArray(breakdown)) {
2451
+ console.log(`
2452
+ By Payment Mode:
2453
+ `);
2454
+ breakdown.forEach((row) => {
2455
+ const mode = String(row["mode"] ?? row["paymentMode"] ?? "-").padEnd(18);
2456
+ const amount = formatAmount(String(row["amount"] ?? row["total"] ?? "0")).padStart(14);
2457
+ console.log(` ${mode} ${amount}`);
2458
+ });
2459
+ }
2460
+ console.log();
2461
+ } catch (e) {
2462
+ if (e instanceof HisaaboApiError) {
2690
2463
  const err = e.hisaaboError;
2691
2464
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2692
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2693
2465
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2694
2466
  }
2695
2467
  fatalError(String(e instanceof Error ? e.message : e));
2696
2468
  }
2697
2469
  }
2698
- async function bankTransactionsCommand(accountId, opts) {
2470
+ async function reportCashFlowCommand(opts) {
2699
2471
  const cfg = requireAuth();
2700
2472
  const client = new HisaaboClient(cfg);
2701
- const page = opts.page ?? 1;
2702
- const limit = opts.limit ?? 20;
2703
2473
  try {
2704
- const result = await client.bankAccount.listTransactions({
2705
- bankAccountId: accountId,
2706
- fromDate: opts.from,
2707
- toDate: opts.to,
2708
- page,
2709
- limit
2710
- });
2474
+ const result = await client.reports.cashFlowForecast();
2711
2475
  if (opts.json) {
2712
2476
  outputJSON(result);
2713
2477
  return;
2714
2478
  }
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
- ];
2479
+ const res = result;
2480
+ console.log("\n Cash Flow Forecast\n");
2481
+ console.log(" " + "\u2550".repeat(60) + "\n");
2482
+ const currentBalance = String(res["currentBalance"] ?? res["balance"] ?? "0");
2483
+ const avgDailyExpenses = String(res["avgDailyExpenses"] ?? res["dailyBurn"] ?? "0");
2484
+ console.log(` Current Balance: ${formatAmount(currentBalance).padStart(14)}`);
2485
+ console.log(` Avg Daily Expenses: ${formatAmount(avgDailyExpenses).padStart(14)}`);
2486
+ const forecasts = res["forecasts"] ?? res["forecast"];
2487
+ if (forecasts && Array.isArray(forecasts)) {
2488
+ console.log(`
2489
+ Forecast:
2490
+ `);
2491
+ forecasts.forEach((f) => {
2492
+ const days = String(f["days"] ?? f["day"] ?? "-");
2493
+ const balance = formatAmount(String(f["balance"] ?? f["amount"] ?? "0")).padStart(14);
2494
+ console.log(` ${`${days}d`.padEnd(6)} ${balance}`);
2495
+ });
2496
+ } else {
2497
+ const current = parseFloat(currentBalance);
2498
+ const daily = parseFloat(avgDailyExpenses);
2499
+ if (!isNaN(current) && !isNaN(daily)) {
2500
+ console.log(`
2501
+ Forecast:
2502
+ `);
2503
+ for (const days of [7, 14, 30]) {
2504
+ const projected = current - daily * days;
2505
+ console.log(` ${`${days}d`.padEnd(6)} ${formatAmount(String(projected)).padStart(14)}`);
2506
+ }
2507
+ }
2508
+ }
2509
+ console.log();
2510
+ } catch (e) {
2511
+ if (e instanceof HisaaboApiError) {
2512
+ const err = e.hisaaboError;
2513
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2514
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2515
+ }
2516
+ fatalError(String(e instanceof Error ? e.message : e));
2517
+ }
2518
+ }
2519
+ async function reportCollectionEfficiencyCommand(opts) {
2520
+ const cfg = requireAuth();
2521
+ const client = new HisaaboClient(cfg);
2522
+ const { from, to } = resolveRange(opts);
2523
+ try {
2524
+ const result = await client.reports.collectionEfficiency({ fromDate: from, toDate: to });
2525
+ if (opts.json) {
2526
+ outputJSON(result);
2527
+ return;
2528
+ }
2529
+ const res = result;
2722
2530
  console.log(`
2723
- Transactions for ${accountId}
2531
+ Collection Efficiency ${from} \u2192 ${to}
2724
2532
  `);
2725
- outputTable(result.data, cols);
2726
- paginationFooter(result.page, result.limit, result.total);
2533
+ console.log(" " + "\u2550".repeat(60) + "\n");
2534
+ const rate = String(res["collectionRate"] ?? res["rate"] ?? "0");
2535
+ const dso = String(res["dso"] ?? res["daysSalesOutstanding"] ?? "-");
2536
+ const paidOnTime = String(res["paidOnTime"] ?? res["onTimeCount"] ?? "-");
2537
+ const totalInvoiced = String(res["totalInvoiced"] ?? res["invoiced"] ?? "-");
2538
+ console.log(` Collection Rate: ${parseFloat(rate).toFixed(1).padStart(8)}%`);
2539
+ console.log(` DSO (Days): ${dso.padStart(8)}`);
2540
+ console.log(` Paid On Time: ${paidOnTime.padStart(8)}`);
2541
+ if (totalInvoiced !== "-") {
2542
+ console.log(` Total Invoiced: ${formatAmount(totalInvoiced).padStart(14)}`);
2543
+ }
2544
+ console.log();
2727
2545
  } catch (e) {
2728
2546
  if (e instanceof HisaaboApiError) {
2729
2547
  const err = e.hisaaboError;
@@ -2734,36 +2552,78 @@ async function bankTransactionsCommand(accountId, opts) {
2734
2552
  }
2735
2553
  }
2736
2554
 
2737
- // src/commands/shipment/index.ts
2738
- async function shipmentListCommand(opts) {
2555
+ // src/bin/registrars/report.ts
2556
+ function registerReportCommands(program2) {
2557
+ const report = program2.command("report").description("Business reports");
2558
+ 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) => {
2559
+ await reportDaybookCommand(opts);
2560
+ });
2561
+ report.command("outstanding").description("Outstanding receivables and payables").option("--json", "JSON output").option("--type <type>", "receivable, payable, or both").action(async (opts) => {
2562
+ await reportOutstandingCommand({ json: opts.json, type: opts.type });
2563
+ });
2564
+ 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) => {
2565
+ await reportTaxSummaryCommand(opts);
2566
+ });
2567
+ 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) => {
2568
+ await reportItemSalesCommand(opts);
2569
+ });
2570
+ report.command("stock").description("Stock summary report").option("--json", "JSON output").option("--category <cat>", "Filter by category").action(async (opts) => {
2571
+ await reportStockSummaryCommand({ json: opts.json, category: opts.category });
2572
+ });
2573
+ report.command("sales-register").description("Sales invoice listing").option("--json", "JSON output").option("--format <format>", "table, tsv or csv").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-month", "Current month").option("--this-fy", "Current financial year").option("--party-id <id>", "Filter by party ID").action(async (opts) => {
2574
+ await reportSalesRegisterCommand(opts);
2575
+ });
2576
+ report.command("purchase-register").description("Purchase invoice listing").option("--json", "JSON output").option("--format <format>", "table, tsv or csv").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-month", "Current month").option("--this-fy", "Current financial year").option("--party-id <id>", "Filter by party ID").action(async (opts) => {
2577
+ await reportPurchaseRegisterCommand(opts);
2578
+ });
2579
+ report.command("party-statement <partyId>").description("Party transaction statement").option("--json", "JSON output").option("--format <format>", "table, 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 (partyId, opts) => {
2580
+ await reportPartyStatementCommand(partyId, opts);
2581
+ });
2582
+ report.command("payment-summary").description("Payment summary by mode").option("--json", "JSON output").option("--format <format>", "table, tsv or csv").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-month", "Current month").option("--this-fy", "Current financial year").option("--type <type>", "received, made, or both").action(async (opts) => {
2583
+ await reportPaymentSummaryCommand(opts);
2584
+ });
2585
+ report.command("cash-flow").description("Cash flow forecast").option("--json", "JSON output").action(async (opts) => {
2586
+ await reportCashFlowCommand({ json: opts.json });
2587
+ });
2588
+ report.command("collection-efficiency").description("Collection efficiency metrics").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").option("--this-month", "Current month").option("--this-fy", "Current financial year").action(async (opts) => {
2589
+ await reportCollectionEfficiencyCommand(opts);
2590
+ });
2591
+ }
2592
+
2593
+ // src/commands/bank/index.ts
2594
+ import * as readline11 from "readline";
2595
+ async function prompt5(rl, q) {
2596
+ return new Promise((resolve2) => rl.question(q, resolve2));
2597
+ }
2598
+ async function bankListCommand(opts) {
2739
2599
  const cfg = requireAuth();
2740
2600
  const client = new HisaaboClient(cfg);
2741
- const page = opts.page ?? 1;
2742
- const limit = opts.limit ?? 20;
2743
2601
  try {
2744
- const result = await client.shipment.list({
2745
- status: opts.status ?? null,
2746
- invoiceId: opts.invoiceId ?? null,
2747
- page,
2748
- limit
2749
- });
2602
+ const [accounts, summary] = await Promise.all([
2603
+ client.bankAccount.list(),
2604
+ client.bankAccount.summary()
2605
+ ]);
2750
2606
  if (opts.json) {
2751
- outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2607
+ outputJSON({ accounts, summary });
2752
2608
  return;
2753
2609
  }
2754
- console.log(`
2755
- Shipments ${result.total} total
2610
+ console.log("\n Bank Accounts\n");
2611
+ console.log(` ${"\u2550".repeat(60)}
2756
2612
  `);
2757
2613
  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) }
2614
+ { key: "accountName", header: "Name", width: 22 },
2615
+ { key: "bankName", header: "Bank", width: 16, format: (v) => String(v ?? "-") },
2616
+ { key: "accountType", header: "Type", width: 10 },
2617
+ { key: "accountNumber", header: "Account #", width: 16, format: (v) => String(v ?? "-") },
2618
+ { key: "currentBalance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
2619
+ { key: "isDefault", header: "Default", width: 8, format: (v) => v ? "Yes" : "" }
2764
2620
  ];
2765
- outputTable(result.data, cols);
2766
- paginationFooter(result.page, result.limit, result.total);
2621
+ outputTable(accounts, cols);
2622
+ console.log(`
2623
+ Total Balance: ${formatINR(summary.totalBalance)}`);
2624
+ console.log(` Cash in Hand: ${formatINR(summary.cashInHand)}`);
2625
+ console.log(` Bank Balance: ${formatINR(summary.bankBalance)}
2626
+ `);
2767
2627
  } catch (e) {
2768
2628
  if (e instanceof HisaaboApiError) {
2769
2629
  const err = e.hisaaboError;
@@ -2773,28 +2633,23 @@ async function shipmentListCommand(opts) {
2773
2633
  fatalError(String(e instanceof Error ? e.message : e));
2774
2634
  }
2775
2635
  }
2776
- async function shipmentGetCommand(id, opts) {
2636
+ async function bankGetCommand(id, opts) {
2777
2637
  const cfg = requireAuth();
2778
2638
  const client = new HisaaboClient(cfg);
2779
2639
  try {
2780
- const shipment2 = await client.shipment.get(id);
2781
- if (!shipment2) fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2640
+ const account = await client.bankAccount.get(id);
2641
+ if (!account) fatalError(`Bank account not found: ${id}`, EXIT.NOT_FOUND);
2782
2642
  if (opts.json) {
2783
- outputJSON(shipment2);
2643
+ outputJSON(account);
2784
2644
  return;
2785
2645
  }
2786
2646
  console.log(`
2787
- Shipment ${id}`);
2647
+ ${account.accountName} (${account.accountType})`);
2788
2648
  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)}`);
2649
+ if (account.bankName) console.log(` Bank: ${account.bankName}`);
2650
+ if (account.accountNumber) console.log(` Account: ${account.accountNumber}`);
2651
+ if (account.ifsc) console.log(` IFSC: ${account.ifsc}`);
2652
+ console.log(` Balance: ${formatINR(account.currentBalance)}`);
2798
2653
  console.log();
2799
2654
  } catch (e) {
2800
2655
  if (e instanceof HisaaboApiError) {
@@ -2805,25 +2660,49 @@ async function shipmentGetCommand(id, opts) {
2805
2660
  fatalError(String(e instanceof Error ? e.message : e));
2806
2661
  }
2807
2662
  }
2808
- async function shipmentCreateCommand(opts) {
2663
+ async function bankCreateCommand(opts) {
2809
2664
  const cfg = requireAuth();
2810
2665
  const client = new HisaaboClient(cfg);
2666
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
2667
+ let name = opts.name;
2668
+ let accountType = opts.type ?? "current";
2669
+ let bankName = opts.bank;
2670
+ let accountNumber = opts.accountNumber;
2671
+ let ifsc = opts.ifsc;
2672
+ let openingBalance = opts.openingBalance;
2673
+ if (!isNonInteractive) {
2674
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
2675
+ if (!name) name = (await prompt5(rl, " Account Name: ")).trim();
2676
+ const typeStr = await prompt5(rl, " Type (savings/current/cash/credit/other) [current]: ");
2677
+ accountType = typeStr.trim() || "current";
2678
+ const bankStr = await prompt5(rl, " Bank Name: ");
2679
+ if (bankStr.trim()) bankName = bankStr.trim();
2680
+ const numStr = await prompt5(rl, " Account Number: ");
2681
+ if (numStr.trim()) accountNumber = numStr.trim();
2682
+ const ifscStr = await prompt5(rl, " IFSC: ");
2683
+ if (ifscStr.trim()) ifsc = ifscStr.trim();
2684
+ const balStr = await prompt5(rl, " Opening Balance [0]: ");
2685
+ openingBalance = balStr.trim() || "0";
2686
+ rl.close();
2687
+ }
2688
+ if (!name) fatalError("--name is required", EXIT.USAGE);
2811
2689
  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
2690
+ const account = await client.bankAccount.create({
2691
+ accountName: name,
2692
+ accountType,
2693
+ bankName,
2694
+ accountNumber,
2695
+ ifsc,
2696
+ openingBalance,
2697
+ isDefault: opts.default
2819
2698
  });
2820
2699
  if (opts.json) {
2821
- outputJSON(shipment2);
2700
+ outputJSON(account);
2822
2701
  return;
2823
2702
  }
2824
- success(`Shipment created: ${shipment2.id}`);
2825
- if (shipment2.trackingNumber) console.log(` Tracking: ${shipment2.trackingNumber}`);
2826
- console.log();
2703
+ success(`Created: ${account.accountName}`);
2704
+ console.log(` ID: ${account.id}
2705
+ `);
2827
2706
  } catch (e) {
2828
2707
  if (e instanceof HisaaboApiError) {
2829
2708
  const err = e.hisaaboError;
@@ -2834,52 +2713,64 @@ async function shipmentCreateCommand(opts) {
2834
2713
  fatalError(String(e instanceof Error ? e.message : e));
2835
2714
  }
2836
2715
  }
2837
- async function shipmentUpdateCommand(id, opts) {
2716
+ async function bankTransferCommand(opts) {
2838
2717
  const cfg = requireAuth();
2839
2718
  const client = new HisaaboClient(cfg);
2719
+ if (!opts.from) fatalError("--from account ID is required", EXIT.USAGE);
2720
+ if (!opts.to) fatalError("--to account ID is required", EXIT.USAGE);
2721
+ if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2840
2722
  try {
2841
- const shipment2 = await client.shipment.update({
2842
- id,
2843
- status: opts.status,
2844
- trackingNumber: opts.tracking,
2845
- carrier: opts.carrier
2723
+ const result = await client.bankAccount.transfer({
2724
+ fromAccountId: opts.from,
2725
+ toAccountId: opts.to,
2726
+ amount: opts.amount,
2727
+ description: opts.description,
2728
+ transactionDate: opts.date
2846
2729
  });
2847
2730
  if (opts.json) {
2848
- outputJSON(shipment2);
2731
+ outputJSON(result);
2849
2732
  return;
2850
2733
  }
2851
- success(`Shipment updated: ${formatStatus(shipment2.status)}`);
2734
+ success(`Transfer recorded: ${formatINR(opts.amount)}`);
2852
2735
  } catch (e) {
2853
2736
  if (e instanceof HisaaboApiError) {
2854
2737
  const err = e.hisaaboError;
2855
- if (err.code === "not_found") fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2856
2738
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2739
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2857
2740
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2858
2741
  }
2859
2742
  fatalError(String(e instanceof Error ? e.message : e));
2860
2743
  }
2861
2744
  }
2862
-
2863
- // src/commands/target/index.ts
2864
- async function targetListCommand(opts) {
2745
+ async function bankTransactionsCommand(accountId, opts) {
2865
2746
  const cfg = requireAuth();
2866
2747
  const client = new HisaaboClient(cfg);
2748
+ const page = opts.page ?? 1;
2749
+ const limit = opts.limit ?? 20;
2867
2750
  try {
2868
- const targets = await client.target.list({});
2751
+ const result = await client.bankAccount.listTransactions({
2752
+ bankAccountId: accountId,
2753
+ fromDate: opts.from,
2754
+ toDate: opts.to,
2755
+ page,
2756
+ limit
2757
+ });
2869
2758
  if (opts.json) {
2870
- outputJSON(targets);
2759
+ outputJSON(result);
2871
2760
  return;
2872
2761
  }
2873
- console.log("\n Sales Targets\n");
2874
2762
  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) }
2763
+ { key: "transactionDate", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
2764
+ { key: "type", header: "Type", width: 12 },
2765
+ { key: "description", header: "Description", width: 25, format: (v) => String(v ?? "-") },
2766
+ { key: "amount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
2767
+ { key: "balanceAfter", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) }
2881
2768
  ];
2882
- outputTable(targets, cols);
2769
+ console.log(`
2770
+ Transactions for ${accountId}
2771
+ `);
2772
+ outputTable(result.data, cols);
2773
+ paginationFooter(result.page, result.limit, result.total);
2883
2774
  } catch (e) {
2884
2775
  if (e instanceof HisaaboApiError) {
2885
2776
  const err = e.hisaaboError;
@@ -2889,81 +2780,203 @@ async function targetListCommand(opts) {
2889
2780
  fatalError(String(e instanceof Error ? e.message : e));
2890
2781
  }
2891
2782
  }
2892
- async function targetMyCommand(opts) {
2783
+
2784
+ // src/commands/bank/gateway-config.ts
2785
+ function formatChargeRate(rate) {
2786
+ if (!rate) return "-";
2787
+ return rate.type === "percentage" ? `${rate.value}%` : `Flat ${rate.value}`;
2788
+ }
2789
+ async function bankGatewayConfigCommand(accountId, opts) {
2893
2790
  const cfg = requireAuth();
2894
2791
  const client = new HisaaboClient(cfg);
2895
2792
  try {
2896
- const targets = await client.target.myTargets();
2793
+ const config = await client.bankAccount.getGatewayConfig(accountId);
2794
+ if (!config) {
2795
+ fatalError(`No gateway configuration found for account: ${accountId}`, EXIT.NOT_FOUND);
2796
+ }
2897
2797
  if (opts.json) {
2898
- outputJSON(targets);
2798
+ outputJSON(config);
2899
2799
  return;
2900
2800
  }
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
- });
2801
+ console.log(`
2802
+ Gateway Configuration`);
2803
+ console.log(" " + "\u2500".repeat(45));
2804
+ console.log(` Account: ${accountId}`);
2805
+ console.log(` Settlement Account: ${config.settlementAccountId}`);
2806
+ console.log(` Expense Category: ${config.expenseCategory}`);
2807
+ console.log(` Auto Settle: ${config.autoSettle ? "Yes" : "No"}`);
2808
+ console.log(` Active: ${config.isActive ? "Yes" : "No"}`);
2809
+ console.log();
2810
+ const modes = ["credit_card", "debit_card", "upi", "net_banking", "wallet", "default"];
2811
+ const rows = modes.map((mode) => ({
2812
+ mode,
2813
+ rate: formatChargeRate(config.chargeConfig[mode])
2814
+ }));
2815
+ const cols = [
2816
+ { key: "mode", header: "Payment Mode", width: 18 },
2817
+ { key: "rate", header: "Charge Rate", width: 16 }
2818
+ ];
2819
+ console.log(" Charge Rates:\n");
2820
+ outputTable(rows, cols);
2821
+ console.log();
2911
2822
  } catch (e) {
2912
2823
  if (e instanceof HisaaboApiError) {
2913
2824
  const err = e.hisaaboError;
2914
2825
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2826
+ if (err.code === "not_found") fatalError(`Bank account not found: ${accountId}`, EXIT.NOT_FOUND);
2915
2827
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2916
2828
  }
2917
2829
  fatalError(String(e instanceof Error ? e.message : e));
2918
2830
  }
2919
2831
  }
2920
- async function targetCreateCommand(opts) {
2832
+
2833
+ // src/commands/bank/update-gateway.ts
2834
+ function parseChargeRate(value) {
2835
+ if (value.toLowerCase().startsWith("flat:")) {
2836
+ return { type: "flat", value: value.slice(5) };
2837
+ }
2838
+ return { type: "percentage", value };
2839
+ }
2840
+ async function bankUpdateGatewayCommand(accountId, opts) {
2921
2841
  const cfg = requireAuth();
2922
2842
  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
2843
  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
2844
+ const existing = await client.bankAccount.getGatewayConfig(accountId);
2845
+ const chargeConfig = existing?.chargeConfig ?? {};
2846
+ if (opts.chargeCreditCard !== void 0) {
2847
+ chargeConfig.credit_card = parseChargeRate(opts.chargeCreditCard);
2848
+ }
2849
+ if (opts.chargeDebitCard !== void 0) {
2850
+ chargeConfig.debit_card = parseChargeRate(opts.chargeDebitCard);
2851
+ }
2852
+ if (opts.chargeUpi !== void 0) {
2853
+ chargeConfig.upi = parseChargeRate(opts.chargeUpi);
2854
+ }
2855
+ if (opts.chargeNetBanking !== void 0) {
2856
+ chargeConfig.net_banking = parseChargeRate(opts.chargeNetBanking);
2857
+ }
2858
+ if (opts.chargeWallet !== void 0) {
2859
+ chargeConfig.wallet = parseChargeRate(opts.chargeWallet);
2860
+ }
2861
+ if (opts.chargeDefault !== void 0) {
2862
+ chargeConfig.default = parseChargeRate(opts.chargeDefault);
2863
+ }
2864
+ const settlementAccountId = opts.settlementAccount ?? existing?.settlementAccountId;
2865
+ if (!settlementAccountId) {
2866
+ fatalError("--settlement-account is required when creating a new gateway config", EXIT.USAGE);
2867
+ }
2868
+ const result = await client.bankAccount.upsertGatewayConfig({
2869
+ bankAccountId: accountId,
2870
+ settlementAccountId,
2871
+ chargeConfig
2934
2872
  });
2935
2873
  if (opts.json) {
2936
- outputJSON(target2);
2874
+ outputJSON(result);
2937
2875
  return;
2938
2876
  }
2939
- success(`Target created: ${target2.type} ${target2.period} ${formatAmount(target2.targetValue)}`);
2877
+ success(`Gateway configuration updated for account: ${accountId}`);
2878
+ console.log(` Settlement Account: ${result.settlementAccountId}
2879
+ `);
2940
2880
  } catch (e) {
2941
2881
  if (e instanceof HisaaboApiError) {
2942
2882
  const err = e.hisaaboError;
2943
2883
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2944
2884
  if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2885
+ if (err.code === "not_found") fatalError(`Bank account not found: ${accountId}`, EXIT.NOT_FOUND);
2945
2886
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2946
2887
  }
2947
2888
  fatalError(String(e instanceof Error ? e.message : e));
2948
2889
  }
2949
2890
  }
2950
2891
 
2951
- // src/commands/store/index.ts
2952
- async function storeSettingsCommand(opts) {
2892
+ // src/bin/registrars/bank.ts
2893
+ function registerBankCommands(program2) {
2894
+ const bank = program2.command("bank").description("Bank account management");
2895
+ bank.command("list").description("List bank accounts with balances").option("--json", "JSON output").action(async (opts) => {
2896
+ await bankListCommand({ json: opts.json });
2897
+ });
2898
+ bank.command("get <id>").description("Get bank account details").option("--json", "JSON output").action(async (id, opts) => {
2899
+ await bankGetCommand(id, { json: opts.json });
2900
+ });
2901
+ 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) => {
2902
+ await bankCreateCommand({
2903
+ json: opts.json,
2904
+ name: opts.name,
2905
+ type: opts.type,
2906
+ bank: opts.bank,
2907
+ accountNumber: opts.accountNumber,
2908
+ ifsc: opts.ifsc,
2909
+ openingBalance: opts.openingBalance,
2910
+ default: opts.default,
2911
+ yes: opts.yes
2912
+ });
2913
+ });
2914
+ 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) => {
2915
+ await bankTransferCommand({
2916
+ json: opts.json,
2917
+ from: opts.from,
2918
+ to: opts.to,
2919
+ amount: opts.amount,
2920
+ description: opts.description,
2921
+ date: opts.date
2922
+ });
2923
+ });
2924
+ 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) => {
2925
+ await bankTransactionsCommand(accountId, {
2926
+ json: opts.json,
2927
+ from: opts.from,
2928
+ to: opts.to,
2929
+ page: opts.page,
2930
+ limit: opts.limit
2931
+ });
2932
+ });
2933
+ bank.command("gateway-config <accountId>").description("Display gateway configuration (charge rates, settlement account)").option("--json", "JSON output").action(async (accountId, opts) => {
2934
+ await bankGatewayConfigCommand(accountId, { json: opts.json });
2935
+ });
2936
+ bank.command("update-gateway <accountId>").description("Update gateway charge configuration").option("--json", "JSON output").option("--charge-credit-card <rate>", "Credit card charge rate (e.g. 2 for 2%, flat:20 for flat)").option("--charge-debit-card <rate>", "Debit card charge rate").option("--charge-upi <rate>", "UPI charge rate").option("--charge-net-banking <rate>", "Net banking charge rate").option("--charge-wallet <rate>", "Wallet charge rate").option("--charge-default <rate>", "Default charge rate for unlisted modes").option("--settlement-account <id>", "Settlement bank account ID").action(async (accountId, opts) => {
2937
+ await bankUpdateGatewayCommand(accountId, {
2938
+ json: opts.json,
2939
+ chargeCreditCard: opts.chargeCreditCard,
2940
+ chargeDebitCard: opts.chargeDebitCard,
2941
+ chargeUpi: opts.chargeUpi,
2942
+ chargeNetBanking: opts.chargeNetBanking,
2943
+ chargeWallet: opts.chargeWallet,
2944
+ chargeDefault: opts.chargeDefault,
2945
+ settlementAccount: opts.settlementAccount
2946
+ });
2947
+ });
2948
+ }
2949
+
2950
+ // src/commands/shipment/index.ts
2951
+ async function shipmentListCommand(opts) {
2953
2952
  const cfg = requireAuth();
2954
2953
  const client = new HisaaboClient(cfg);
2954
+ const page = opts.page ?? 1;
2955
+ const limit = opts.limit ?? 20;
2955
2956
  try {
2956
- const settings = await client.store.getSettings();
2957
+ const result = await client.shipment.list({
2958
+ status: opts.status ?? null,
2959
+ invoiceId: opts.invoiceId ?? null,
2960
+ page,
2961
+ limit
2962
+ });
2957
2963
  if (opts.json) {
2958
- outputJSON(settings);
2964
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2959
2965
  return;
2960
2966
  }
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
+ console.log(`
2968
+ Shipments ${result.total} total
2969
+ `);
2970
+ const cols = [
2971
+ { key: "invoiceNumber", header: "Invoice", width: 12, format: (v) => String(v ?? "-") },
2972
+ { key: "partyName", header: "Party", width: 18, format: (v) => String(v ?? "-") },
2973
+ { key: "carrier", header: "Carrier", width: 12, format: (v) => String(v ?? "-") },
2974
+ { key: "trackingNumber", header: "Tracking", width: 16, format: (v) => String(v ?? "-") },
2975
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) },
2976
+ { key: "shipmentDate", header: "Shipped", width: 12, format: (v) => formatDate(v ? String(v) : null) }
2977
+ ];
2978
+ outputTable(result.data, cols);
2979
+ paginationFooter(result.page, result.limit, result.total);
2967
2980
  } catch (e) {
2968
2981
  if (e instanceof HisaaboApiError) {
2969
2982
  const err = e.hisaaboError;
@@ -2973,29 +2986,177 @@ async function storeSettingsCommand(opts) {
2973
2986
  fatalError(String(e instanceof Error ? e.message : e));
2974
2987
  }
2975
2988
  }
2976
- async function storeOrdersCommand(opts) {
2989
+ async function shipmentGetCommand(id, opts) {
2977
2990
  const cfg = requireAuth();
2978
2991
  const client = new HisaaboClient(cfg);
2979
- const page = opts.page ?? 1;
2980
- const limit = opts.limit ?? 20;
2981
2992
  try {
2982
- const result = await client.store.listOrders({ status: opts.status ?? null, page, limit });
2993
+ const shipment = await client.shipment.get(id);
2994
+ if (!shipment) fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2983
2995
  if (opts.json) {
2984
- outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2996
+ outputJSON(shipment);
2985
2997
  return;
2986
2998
  }
2987
2999
  console.log(`
2988
- Store Orders ${result.total} total
2989
- `);
3000
+ Shipment ${id}`);
3001
+ console.log(" " + "\u2500".repeat(45));
3002
+ if (shipment.invoiceNumber) console.log(` Invoice: ${shipment.invoiceNumber}`);
3003
+ if (shipment.partyName) console.log(` Party: ${shipment.partyName}`);
3004
+ if (shipment.carrier) console.log(` Carrier: ${shipment.carrier}`);
3005
+ if (shipment.trackingNumber) console.log(` Tracking: ${shipment.trackingNumber}`);
3006
+ if (shipment.trackingUrl) console.log(` URL: ${shipment.trackingUrl}`);
3007
+ console.log(` Status: ${formatStatus(shipment.status)}`);
3008
+ if (shipment.shipmentDate) console.log(` Shipped: ${formatDate(shipment.shipmentDate)}`);
3009
+ if (shipment.estimatedDelivery) console.log(` Est. Del: ${formatDate(shipment.estimatedDelivery)}`);
3010
+ if (shipment.actualDelivery) console.log(` Delivered:${formatDate(shipment.actualDelivery)}`);
3011
+ console.log();
3012
+ } catch (e) {
3013
+ if (e instanceof HisaaboApiError) {
3014
+ const err = e.hisaaboError;
3015
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3016
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3017
+ }
3018
+ fatalError(String(e instanceof Error ? e.message : e));
3019
+ }
3020
+ }
3021
+ async function shipmentCreateCommand(opts) {
3022
+ const cfg = requireAuth();
3023
+ const client = new HisaaboClient(cfg);
3024
+ try {
3025
+ const shipment = await client.shipment.create({
3026
+ invoiceId: opts.invoiceId,
3027
+ partyId: opts.partyId,
3028
+ carrier: opts.carrier,
3029
+ trackingNumber: opts.tracking,
3030
+ mode: opts.mode,
3031
+ shipmentDate: opts.date
3032
+ });
3033
+ if (opts.json) {
3034
+ outputJSON(shipment);
3035
+ return;
3036
+ }
3037
+ success(`Shipment created: ${shipment.id}`);
3038
+ if (shipment.trackingNumber) console.log(` Tracking: ${shipment.trackingNumber}`);
3039
+ console.log();
3040
+ } catch (e) {
3041
+ if (e instanceof HisaaboApiError) {
3042
+ const err = e.hisaaboError;
3043
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3044
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3045
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3046
+ }
3047
+ fatalError(String(e instanceof Error ? e.message : e));
3048
+ }
3049
+ }
3050
+ async function shipmentUpdateCommand(id, opts) {
3051
+ const cfg = requireAuth();
3052
+ const client = new HisaaboClient(cfg);
3053
+ try {
3054
+ const shipment = await client.shipment.update({
3055
+ id,
3056
+ status: opts.status,
3057
+ trackingNumber: opts.tracking,
3058
+ carrier: opts.carrier
3059
+ });
3060
+ if (opts.json) {
3061
+ outputJSON(shipment);
3062
+ return;
3063
+ }
3064
+ success(`Shipment updated: ${formatStatus(shipment.status)}`);
3065
+ } catch (e) {
3066
+ if (e instanceof HisaaboApiError) {
3067
+ const err = e.hisaaboError;
3068
+ if (err.code === "not_found") fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
3069
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3070
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3071
+ }
3072
+ fatalError(String(e instanceof Error ? e.message : e));
3073
+ }
3074
+ }
3075
+
3076
+ // src/bin/registrars/shipment.ts
3077
+ function registerShipmentCommands(program2) {
3078
+ const shipment = program2.command("shipment").description("Shipment tracking");
3079
+ 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) => {
3080
+ await shipmentListCommand({
3081
+ json: opts.json,
3082
+ status: opts.status,
3083
+ invoiceId: opts.invoiceId,
3084
+ page: opts.page,
3085
+ limit: opts.limit
3086
+ });
3087
+ });
3088
+ shipment.command("get <id>").description("Get shipment details").option("--json", "JSON output").action(async (id, opts) => {
3089
+ await shipmentGetCommand(id, { json: opts.json });
3090
+ });
3091
+ 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) => {
3092
+ await shipmentCreateCommand({
3093
+ json: opts.json,
3094
+ invoiceId: opts.invoiceId,
3095
+ partyId: opts.partyId,
3096
+ carrier: opts.carrier,
3097
+ tracking: opts.tracking,
3098
+ mode: opts.mode,
3099
+ date: opts.date
3100
+ });
3101
+ });
3102
+ 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) => {
3103
+ await shipmentUpdateCommand(id, {
3104
+ json: opts.json,
3105
+ status: opts.status,
3106
+ tracking: opts.tracking,
3107
+ carrier: opts.carrier
3108
+ });
3109
+ });
3110
+ }
3111
+
3112
+ // src/commands/target/index.ts
3113
+ async function targetListCommand(opts) {
3114
+ const cfg = requireAuth();
3115
+ const client = new HisaaboClient(cfg);
3116
+ try {
3117
+ const targets = await client.target.list({});
3118
+ if (opts.json) {
3119
+ outputJSON(targets);
3120
+ return;
3121
+ }
3122
+ console.log("\n Sales Targets\n");
2990
3123
  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 ?? "")) }
3124
+ { key: "id", header: "ID", width: 10, format: (v) => String(v ?? "").slice(0, 8) + "..." },
3125
+ { key: "type", header: "Type", width: 14 },
3126
+ { key: "period", header: "Period", width: 12 },
3127
+ { key: "targetValue", header: "Target", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
3128
+ { key: "startDate", header: "Start", width: 13, format: (v) => formatDate(String(v ?? "")) },
3129
+ { key: "endDate", header: "End", width: 13, format: (v) => formatDate(v ? String(v) : null) }
2996
3130
  ];
2997
- outputTable(result.data, cols);
2998
- paginationFooter(result.page, result.limit, result.total);
3131
+ outputTable(targets, cols);
3132
+ } catch (e) {
3133
+ if (e instanceof HisaaboApiError) {
3134
+ const err = e.hisaaboError;
3135
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3136
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3137
+ }
3138
+ fatalError(String(e instanceof Error ? e.message : e));
3139
+ }
3140
+ }
3141
+ async function targetMyCommand(opts) {
3142
+ const cfg = requireAuth();
3143
+ const client = new HisaaboClient(cfg);
3144
+ try {
3145
+ const targets = await client.target.myTargets();
3146
+ if (opts.json) {
3147
+ outputJSON(targets);
3148
+ return;
3149
+ }
3150
+ console.log("\n My Targets\n");
3151
+ console.log(" " + "\u2550".repeat(60) + "\n");
3152
+ targets.forEach((t) => {
3153
+ const pct = Math.round(t.percentComplete);
3154
+ const bar = "\u2588".repeat(Math.floor(pct / 5)) + "\u2591".repeat(20 - Math.floor(pct / 5));
3155
+ console.log(` ${t.type} (${t.period})`);
3156
+ console.log(` Target: ${formatAmount(t.targetValue)} Current: ${formatAmount(t.currentValue)} ${pct}%`);
3157
+ console.log(` [${bar}]
3158
+ `);
3159
+ });
2999
3160
  } catch (e) {
3000
3161
  if (e instanceof HisaaboApiError) {
3001
3162
  const err = e.hisaaboError;
@@ -3005,6 +3166,121 @@ async function storeOrdersCommand(opts) {
3005
3166
  fatalError(String(e instanceof Error ? e.message : e));
3006
3167
  }
3007
3168
  }
3169
+ async function targetCreateCommand(opts) {
3170
+ const cfg = requireAuth();
3171
+ const client = new HisaaboClient(cfg);
3172
+ if (!opts.type) fatalError("--type is required (order_count/order_value/item_quantity)", EXIT.USAGE);
3173
+ if (!opts.value) fatalError("--value is required", EXIT.USAGE);
3174
+ if (!opts.startDate) fatalError("--start-date is required", EXIT.USAGE);
3175
+ try {
3176
+ const target = await client.target.create({
3177
+ type: opts.type,
3178
+ period: opts.period ?? "monthly",
3179
+ targetValue: opts.value,
3180
+ startDate: opts.startDate,
3181
+ endDate: opts.endDate,
3182
+ notes: opts.notes
3183
+ });
3184
+ if (opts.json) {
3185
+ outputJSON(target);
3186
+ return;
3187
+ }
3188
+ success(`Target created: ${target.type} ${target.period} ${formatAmount(target.targetValue)}`);
3189
+ } catch (e) {
3190
+ if (e instanceof HisaaboApiError) {
3191
+ const err = e.hisaaboError;
3192
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3193
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3194
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3195
+ }
3196
+ fatalError(String(e instanceof Error ? e.message : e));
3197
+ }
3198
+ }
3199
+
3200
+ // src/bin/registrars/target.ts
3201
+ function registerTargetCommands(program2) {
3202
+ const target = program2.command("target").description("Sales target management");
3203
+ target.command("list").description("List sales targets").option("--json", "JSON output").action(async (opts) => {
3204
+ await targetListCommand({ json: opts.json });
3205
+ });
3206
+ target.command("my").description("Show my target progress").option("--json", "JSON output").action(async (opts) => {
3207
+ await targetMyCommand({ json: opts.json });
3208
+ });
3209
+ 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) => {
3210
+ await targetCreateCommand({
3211
+ json: opts.json,
3212
+ type: opts.type,
3213
+ period: opts.period,
3214
+ value: opts.value,
3215
+ startDate: opts.startDate,
3216
+ endDate: opts.endDate,
3217
+ notes: opts.notes
3218
+ });
3219
+ });
3220
+ }
3221
+
3222
+ // src/bin/registrars/store.ts
3223
+ function registerStoreCommands(program2) {
3224
+ const store = program2.command("store").description("Online store management");
3225
+ store.command("settings").description("Show store settings").option("--json", "JSON output").action(async (opts) => {
3226
+ const { storeSettingsCommand } = await import("./store-IOB4Y67C.js");
3227
+ await storeSettingsCommand({ json: opts.json });
3228
+ });
3229
+ store.command("update-settings").description("Update store settings").option("--slug <slug>", "Store URL slug").option("--tagline <text>", "Store tagline / description").option("--enabled <bool>", "Enable or disable store (true/false)").option("--json", "JSON output").action(async (opts) => {
3230
+ const { storeUpdateSettingsCommand } = await import("./update-settings-Q2EGRLKZ.js");
3231
+ await storeUpdateSettingsCommand({
3232
+ slug: opts.slug,
3233
+ tagline: opts.tagline,
3234
+ enabled: opts.enabled,
3235
+ json: opts.json
3236
+ });
3237
+ });
3238
+ store.command("items").description("List items available in the store").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (opts) => {
3239
+ const { storeItemsCommand } = await import("./items-2OOCQKVF.js");
3240
+ await storeItemsCommand({ json: opts.json, format: opts.format });
3241
+ });
3242
+ store.command("items-toggle").description("Bulk enable / disable store items").option("--enable <ids>", "Comma-separated item IDs to enable").option("--disable <ids>", "Comma-separated item IDs to disable").option("--json", "JSON output").action(async (opts) => {
3243
+ const { storeItemsToggleCommand } = await import("./items-toggle-SKZWCGJH.js");
3244
+ await storeItemsToggleCommand({
3245
+ enable: opts.enable,
3246
+ disable: opts.disable,
3247
+ json: opts.json
3248
+ });
3249
+ });
3250
+ 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) => {
3251
+ const { storeOrdersCommand } = await import("./store-IOB4Y67C.js");
3252
+ await storeOrdersCommand({
3253
+ json: opts.json,
3254
+ status: opts.status,
3255
+ page: opts.page,
3256
+ limit: opts.limit
3257
+ });
3258
+ });
3259
+ store.command("order-get <id>").description("Get order details").option("--json", "JSON output").action(async (id, opts) => {
3260
+ const { storeOrderGetCommand } = await import("./order-get-C2RBUR4O.js");
3261
+ await storeOrderGetCommand(id, { json: opts.json });
3262
+ });
3263
+ store.command("order-confirm <id>").description("Confirm a pending order").option("-y, --yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
3264
+ const { storeOrderConfirmCommand } = await import("./order-confirm-VMRAMNTD.js");
3265
+ await storeOrderConfirmCommand(id, { json: opts.json, yes: opts.yes });
3266
+ });
3267
+ store.command("order-cancel <id>").description("Cancel an order").option("-y, --yes", "Skip confirmation prompt").option("--reason <text>", "Cancellation reason").option("--json", "JSON output").action(async (id, opts) => {
3268
+ const { storeOrderCancelCommand } = await import("./order-cancel-TI27JYYD.js");
3269
+ await storeOrderCancelCommand(id, {
3270
+ json: opts.json,
3271
+ yes: opts.yes,
3272
+ reason: opts.reason
3273
+ });
3274
+ });
3275
+ store.command("order-update <id>").description("Update order status").option("--status <status>", "New status: preparing, ready, delivered").option("--json", "JSON output").action(async (id, opts) => {
3276
+ const { storeOrderUpdateCommand } = await import("./order-update-RE3HATNF.js");
3277
+ await storeOrderUpdateCommand(id, { json: opts.json, status: opts.status });
3278
+ });
3279
+ store.command("check-slug <slug>").description("Check store slug availability").option("--json", "JSON output").action(async (slug, opts) => {
3280
+ const { storeCheckSlugCommand } = await import("./check-slug-FLHHUDYS.js");
3281
+ await storeCheckSlugCommand(slug, { json: opts.json });
3282
+ });
3283
+ }
3008
3284
 
3009
3285
  // src/commands/import/index.ts
3010
3286
  import * as fs3 from "fs";
@@ -3086,431 +3362,947 @@ async function importItemsCommand(filePath, opts) {
3086
3362
  fatalError(String(e instanceof Error ? e.message : e));
3087
3363
  }
3088
3364
  }
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";
3365
+ async function importInvoicesCommand(filePath, opts) {
3366
+ const cfg = requireAuth();
3367
+ const client = new HisaaboClient(cfg);
3368
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3369
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3370
+ console.log(` Importing ${data.length} invoices...`);
3371
+ try {
3372
+ const result = await client.import.importInvoices({ invoices: data });
3373
+ if (opts.json) {
3374
+ outputJSON(result);
3375
+ return;
3116
3376
  }
3117
- if (!email) email = (await ask(" Email: ")).trim();
3118
- if (!password) {
3119
- password = (await ask(" Password: ")).trim();
3377
+ success(`Imported: ${result.imported} invoices`);
3378
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3379
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3380
+ } catch (e) {
3381
+ if (e instanceof HisaaboApiError) {
3382
+ const err = e.hisaaboError;
3383
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3384
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3385
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3120
3386
  }
3121
- rl.close();
3122
- console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
3387
+ fatalError(String(e instanceof Error ? e.message : e));
3123
3388
  }
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) => {
3389
+ }
3390
+ async function importPaymentsCommand(filePath, opts) {
3133
3391
  const cfg = requireAuth();
3134
3392
  const client = new HisaaboClient(cfg);
3393
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3394
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3395
+ console.log(` Importing ${data.length} payments...`);
3135
3396
  try {
3136
- const businesses = await client.business.list();
3397
+ const result = await client.import.importPayments({ payments: data });
3137
3398
  if (opts.json) {
3138
- outputJSON(businesses);
3399
+ outputJSON(result);
3139
3400
  return;
3140
3401
  }
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}`);
3402
+ success(`Imported: ${result.imported} payments`);
3403
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3404
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3153
3405
  } catch (e) {
3154
3406
  if (e instanceof HisaaboApiError) {
3155
- if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3407
+ const err = e.hisaaboError;
3408
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3409
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3410
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3156
3411
  }
3157
3412
  fatalError(String(e instanceof Error ? e.message : e));
3158
3413
  }
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
3414
+ }
3415
+
3416
+ // src/bin/registrars/import.ts
3417
+ function registerImportCommands(program2) {
3418
+ const importCmd = program2.command("import").description("Bulk import data");
3419
+ 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) => {
3420
+ await importPartiesCommand(file, { json: opts.json, format: opts.format });
3182
3421
  });
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
3422
+ 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) => {
3423
+ await importItemsCommand(file, { json: opts.json, format: opts.format });
3200
3424
  });
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
3425
+ importCmd.command("invoices <file>").description("Import invoices from JSON or CSV file").option("--json", "JSON output").option("--format <format>", "json or csv (auto-detected from extension)").action(async (file, opts) => {
3426
+ await importInvoicesCommand(file, { json: opts.json, format: opts.format });
3221
3427
  });
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
3428
+ importCmd.command("payments <file>").description("Import payments from JSON or CSV file").option("--json", "JSON output").option("--format <format>", "json or csv (auto-detected from extension)").action(async (file, opts) => {
3429
+ await importPaymentsCommand(file, { json: opts.json, format: opts.format });
3246
3430
  });
3247
- });
3248
- item.command("get <id>").description("Get item details").option("--json", "JSON output").action(async (id, opts) => {
3431
+ }
3432
+
3433
+ // src/commands/automated-invoice/list.ts
3434
+ var FREQUENCY_LABELS = {
3435
+ weekly: "Weekly",
3436
+ biweekly: "Every 2 Weeks",
3437
+ monthly: "Monthly",
3438
+ quarterly: "Quarterly",
3439
+ half_yearly: "Every 6 Months",
3440
+ yearly: "Yearly",
3441
+ custom: "Custom"
3442
+ };
3443
+ function formatFrequency(freq) {
3444
+ return FREQUENCY_LABELS[freq] ?? freq;
3445
+ }
3446
+ function formatTemplateStatus(status) {
3447
+ const map = {
3448
+ active: "Active",
3449
+ paused: "Paused",
3450
+ completed: "Completed",
3451
+ expired: "Expired"
3452
+ };
3453
+ return map[status] ?? status;
3454
+ }
3455
+ function formatRuns(totalRuns, maxRuns) {
3456
+ if (maxRuns) return `${totalRuns}/${maxRuns}`;
3457
+ return String(totalRuns);
3458
+ }
3459
+ async function automatedInvoiceListCommand(opts) {
3249
3460
  const cfg = requireAuth();
3250
3461
  const client = new HisaaboClient(cfg);
3462
+ const page = opts.page ?? 1;
3463
+ const limit = opts.limit ?? 20;
3251
3464
  try {
3252
- const it = await client.item.get(id);
3465
+ const result = await client.recurringInvoice.list({
3466
+ status: opts.status,
3467
+ page,
3468
+ limit
3469
+ });
3253
3470
  if (opts.json) {
3254
- outputJSON(it);
3471
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
3255
3472
  return;
3256
3473
  }
3257
3474
  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();
3475
+ Recurring Invoices ${result.total} total
3476
+ `);
3477
+ const cols = [
3478
+ { key: "name", header: "Name", width: 20 },
3479
+ { key: "partyName", header: "Party", width: 18 },
3480
+ { key: "frequency", header: "Frequency", width: 14, format: (v) => formatFrequency(String(v ?? "")) },
3481
+ { key: "status", header: "Status", width: 10, format: (v) => formatTemplateStatus(String(v ?? "")) },
3482
+ { key: "nextRunDate", header: "Next Run", width: 13, format: (v) => formatDate(String(v ?? "")) },
3483
+ { key: "totalRuns", header: "Runs", width: 8, align: "right", format: (v, row) => formatRuns(Number(v ?? 0), row.maxRuns) }
3484
+ ];
3485
+ if (opts.format === "tsv") outputTSV(result.data, cols);
3486
+ else if (opts.format === "csv") outputCSV(result.data, cols);
3487
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
3488
+ else {
3489
+ outputTable(result.data, cols);
3490
+ paginationFooter(result.page, result.limit, result.total);
3491
+ }
3268
3492
  } catch (e) {
3269
- if (e instanceof HisaaboApiError && e.hisaaboError.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
3493
+ if (e instanceof HisaaboApiError) {
3494
+ const err = e.hisaaboError;
3495
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3496
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3497
+ }
3270
3498
  fatalError(String(e instanceof Error ? e.message : e));
3271
3499
  }
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) => {
3500
+ }
3501
+
3502
+ // src/commands/automated-invoice/get.ts
3503
+ import chalk3 from "chalk";
3504
+ var FREQUENCY_LABELS2 = {
3505
+ weekly: "Weekly",
3506
+ biweekly: "Every 2 Weeks",
3507
+ monthly: "Monthly",
3508
+ quarterly: "Quarterly",
3509
+ half_yearly: "Every 6 Months",
3510
+ yearly: "Yearly",
3511
+ custom: "Custom"
3512
+ };
3513
+ function statusBadge(status) {
3514
+ const map = {
3515
+ active: (s) => chalk3.green(s),
3516
+ paused: (s) => chalk3.yellow(s),
3517
+ completed: (s) => chalk3.dim(s),
3518
+ expired: (s) => chalk3.red(s)
3519
+ };
3520
+ const label = `[${status.toUpperCase()}]`;
3521
+ if (!hasColor()) return label;
3522
+ const colorFn = map[status];
3523
+ return colorFn ? colorFn(label) : label;
3524
+ }
3525
+ async function automatedInvoiceGetCommand(id, opts) {
3469
3526
  const cfg = requireAuth();
3470
3527
  const client = new HisaaboClient(cfg);
3471
3528
  try {
3472
- const businesses = await client.business.list();
3529
+ let line2 = function(left, right) {
3530
+ if (right !== void 0) {
3531
+ const pad = Math.max(1, inner - left.length - right.length - 2);
3532
+ process.stdout.write(`| ${left}${" ".repeat(pad)}${right} |
3533
+ `);
3534
+ } else {
3535
+ const vis = left.length;
3536
+ const pad = Math.max(0, inner - vis);
3537
+ process.stdout.write(`| ${left}${" ".repeat(pad)} |
3538
+ `);
3539
+ }
3540
+ }, divider2 = function() {
3541
+ process.stdout.write(`+${"~".repeat(inner + 2)}+
3542
+ `);
3543
+ };
3544
+ var line = line2, divider = divider2;
3545
+ const tmpl = await client.recurringInvoice.getById(id);
3473
3546
  if (opts.json) {
3474
- outputJSON(businesses);
3547
+ outputJSON(tmpl);
3475
3548
  return;
3476
3549
  }
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}`);
3550
+ const w = Math.min(termWidth() - 2, 68);
3551
+ const inner = w - 2;
3552
+ const title = `RECURRING INVOICE ${tmpl.name}`;
3553
+ const badge = statusBadge(tmpl.status);
3554
+ const topPad = Math.max(1, inner - title.length - badge.replace(/\x1b\[[0-9;]*m/g, "").length);
3555
+ process.stdout.write(`
3556
+ +${"~".repeat(inner + 2)}+
3557
+ `);
3558
+ process.stdout.write(`| ${hasColor() ? chalk3.bold(title) : title}${" ".repeat(topPad)}${badge} |
3559
+ `);
3560
+ divider2();
3561
+ line2(`Party: ${tmpl.partyName}`);
3562
+ line2(`Type: ${tmpl.type === "sale" ? "Sale" : "Purchase"}`);
3563
+ line2(`Frequency: ${FREQUENCY_LABELS2[tmpl.frequency] ?? tmpl.frequency}`);
3564
+ if (tmpl.frequency === "custom" && tmpl.customIntervalDays) {
3565
+ line2(`Interval: Every ${tmpl.customIntervalDays} days`);
3566
+ }
3567
+ line2(`Start: ${formatDate(tmpl.startDate)}`);
3568
+ if (tmpl.endDate) line2(`End: ${formatDate(tmpl.endDate)}`);
3569
+ if (tmpl.nextRunDate) line2(`Next Run: ${formatDate(tmpl.nextRunDate)}`);
3570
+ if (tmpl.lastRunDate) line2(`Last Run: ${formatDate(tmpl.lastRunDate)}`);
3571
+ line2(`Runs: ${tmpl.totalRuns}${tmpl.maxRuns ? ` / ${tmpl.maxRuns}` : ""}`);
3572
+ divider2();
3573
+ process.stdout.write(`|${"".padEnd(inner + 2)}|
3574
+ `);
3575
+ process.stdout.write(`| # ${"Item".padEnd(18)} ${"Qty".padStart(5)} ${"Rate".padStart(10)} ${"Tax%".padStart(5)} |
3576
+ `);
3577
+ process.stdout.write(`| ${"--".padEnd(2)} ${"~".repeat(18)} ${"~".repeat(5)} ${"~".repeat(10)} ${"~".repeat(5)} |
3578
+ `);
3579
+ tmpl.lineItems.forEach((item, i) => {
3580
+ const idx = String(i + 1).padStart(2);
3581
+ const desc = item.description.slice(0, 18).padEnd(18);
3582
+ const qty = item.quantity.padStart(5);
3583
+ const rate = formatAmount(item.unitPrice).padStart(10);
3584
+ const tax = item.taxPercent ? `${item.taxPercent}%`.padStart(5) : " -";
3585
+ process.stdout.write(`| ${idx} ${desc} ${qty} ${rate} ${tax} |
3586
+ `);
3480
3587
  });
3588
+ process.stdout.write(`|${"".padEnd(inner + 2)}|
3589
+ `);
3590
+ if (tmpl.notes) {
3591
+ divider2();
3592
+ line2(`Notes: ${tmpl.notes}`);
3593
+ }
3594
+ process.stdout.write(` +${"~".repeat(inner + 2)}+
3595
+
3596
+ `);
3597
+ } catch (e) {
3598
+ if (e instanceof HisaaboApiError) {
3599
+ const err = e.hisaaboError;
3600
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${id}`, EXIT.NOT_FOUND);
3601
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3602
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3603
+ }
3604
+ fatalError(String(e instanceof Error ? e.message : e));
3605
+ }
3606
+ }
3607
+
3608
+ // src/commands/automated-invoice/create.ts
3609
+ async function automatedInvoiceCreateCommand(opts) {
3610
+ const cfg = requireAuth();
3611
+ const client = new HisaaboClient(cfg);
3612
+ if (!opts.partyId) fatalError("--party-id is required", EXIT.USAGE);
3613
+ if (!opts.name) fatalError("--name is required", EXIT.USAGE);
3614
+ if (!opts.type) fatalError("--type is required (sale or purchase)", EXIT.USAGE);
3615
+ if (!opts.frequency) fatalError("--frequency is required", EXIT.USAGE);
3616
+ if (!opts.startDate) fatalError("--start-date is required (YYYY-MM-DD)", EXIT.USAGE);
3617
+ const items = opts.lineItem ?? [];
3618
+ const qtys = opts.qty ?? [];
3619
+ const rates = opts.rate ?? [];
3620
+ const taxes = opts.tax ?? [];
3621
+ const discounts = opts.discount ?? [];
3622
+ if (items.length === 0) fatalError("At least one --line-item is required", EXIT.USAGE);
3623
+ const frequency = opts.frequency;
3624
+ if (frequency === "custom" && !opts.customIntervalDays) {
3625
+ fatalError("--custom-interval-days is required when frequency is 'custom'", EXIT.USAGE);
3626
+ }
3627
+ const lineItems = items.map((desc, i) => ({
3628
+ description: desc,
3629
+ quantity: qtys[i] ?? "1",
3630
+ unitPrice: rates[i] ?? "0",
3631
+ taxPercent: taxes[i],
3632
+ discountPercent: discounts[i]
3633
+ }));
3634
+ try {
3635
+ const result = await client.recurringInvoice.create({
3636
+ partyId: opts.partyId,
3637
+ name: opts.name,
3638
+ type: opts.type,
3639
+ frequency,
3640
+ customIntervalDays: opts.customIntervalDays ? parseInt(opts.customIntervalDays, 10) : void 0,
3641
+ lineItems,
3642
+ startDate: opts.startDate,
3643
+ endDate: opts.endDate,
3644
+ maxRuns: opts.maxRuns ? parseInt(opts.maxRuns, 10) : void 0,
3645
+ notes: opts.notes
3646
+ });
3647
+ if (opts.json) {
3648
+ outputJSON(result);
3649
+ return;
3650
+ }
3651
+ success(`Created recurring invoice template: ${result.name} (${result.id})`);
3652
+ } catch (e) {
3653
+ if (e instanceof HisaaboApiError) {
3654
+ const err = e.hisaaboError;
3655
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3656
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3657
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3658
+ }
3659
+ fatalError(String(e instanceof Error ? e.message : e));
3660
+ }
3661
+ }
3662
+
3663
+ // src/commands/automated-invoice/update.ts
3664
+ async function automatedInvoiceUpdateCommand(id, opts) {
3665
+ const cfg = requireAuth();
3666
+ const client = new HisaaboClient(cfg);
3667
+ const data = {};
3668
+ if (opts.name !== void 0) data["name"] = opts.name;
3669
+ if (opts.frequency !== void 0) data["frequency"] = opts.frequency;
3670
+ if (opts.startDate !== void 0) data["startDate"] = opts.startDate;
3671
+ if (opts.endDate !== void 0) data["endDate"] = opts.endDate;
3672
+ if (opts.maxRuns !== void 0) data["maxRuns"] = parseInt(opts.maxRuns, 10);
3673
+ if (opts.notes !== void 0) data["notes"] = opts.notes;
3674
+ if (Object.keys(data).length === 0) {
3675
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
3676
+ }
3677
+ try {
3678
+ const result = await client.recurringInvoice.update(
3679
+ id,
3680
+ data
3681
+ );
3682
+ if (opts.json) {
3683
+ outputJSON(result);
3684
+ return;
3685
+ }
3686
+ success(`Updated recurring invoice template: ${result.name} (${result.id})`);
3687
+ } catch (e) {
3688
+ if (e instanceof HisaaboApiError) {
3689
+ const err = e.hisaaboError;
3690
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${id}`, EXIT.NOT_FOUND);
3691
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3692
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3693
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3694
+ }
3695
+ fatalError(String(e instanceof Error ? e.message : e));
3696
+ }
3697
+ }
3698
+
3699
+ // src/commands/automated-invoice/pause.ts
3700
+ async function automatedInvoicePauseCommand(id, opts) {
3701
+ const cfg = requireAuth();
3702
+ const client = new HisaaboClient(cfg);
3703
+ try {
3704
+ const result = await client.recurringInvoice.pause(id);
3705
+ if (opts.json) {
3706
+ outputJSON(result);
3707
+ return;
3708
+ }
3709
+ success(`Paused recurring invoice template: ${id}`);
3710
+ } catch (e) {
3711
+ if (e instanceof HisaaboApiError) {
3712
+ const err = e.hisaaboError;
3713
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3714
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3715
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3716
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3717
+ }
3718
+ fatalError(String(e instanceof Error ? e.message : e));
3719
+ }
3720
+ }
3721
+
3722
+ // src/commands/automated-invoice/resume.ts
3723
+ async function automatedInvoiceResumeCommand(id, opts) {
3724
+ const cfg = requireAuth();
3725
+ const client = new HisaaboClient(cfg);
3726
+ try {
3727
+ const result = await client.recurringInvoice.resume(id);
3728
+ if (opts.json) {
3729
+ outputJSON(result);
3730
+ return;
3731
+ }
3732
+ success(`Resumed recurring invoice template: ${id}`);
3733
+ } catch (e) {
3734
+ if (e instanceof HisaaboApiError) {
3735
+ const err = e.hisaaboError;
3736
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3737
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3738
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3739
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3740
+ }
3741
+ fatalError(String(e instanceof Error ? e.message : e));
3742
+ }
3743
+ }
3744
+
3745
+ // src/commands/automated-invoice/run-now.ts
3746
+ async function automatedInvoiceRunNowCommand(id, opts) {
3747
+ const cfg = requireAuth();
3748
+ const client = new HisaaboClient(cfg);
3749
+ try {
3750
+ const result = await client.recurringInvoice.runNow(id);
3751
+ if (opts.json) {
3752
+ outputJSON(result);
3753
+ return;
3754
+ }
3755
+ success(`Manually triggered recurring invoice template: ${id}`);
3756
+ } catch (e) {
3757
+ if (e instanceof HisaaboApiError) {
3758
+ const err = e.hisaaboError;
3759
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3760
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3761
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3762
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3763
+ }
3764
+ fatalError(String(e instanceof Error ? e.message : e));
3765
+ }
3766
+ }
3767
+
3768
+ // src/commands/automated-invoice/delete.ts
3769
+ import * as readline12 from "readline";
3770
+ async function automatedInvoiceDeleteCommand(id, opts) {
3771
+ const cfg = requireAuth();
3772
+ const client = new HisaaboClient(cfg);
3773
+ try {
3774
+ if (!opts.yes && process.stdin.isTTY) {
3775
+ const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
3776
+ const answer = await new Promise((resolve2) => {
3777
+ rl.question(` Delete recurring invoice template ${id}? (y/N): `, resolve2);
3778
+ });
3779
+ rl.close();
3780
+ if (answer.trim().toLowerCase() !== "y") {
3781
+ console.log(" Cancelled.");
3782
+ process.exit(0);
3783
+ }
3784
+ }
3785
+ const result = await client.recurringInvoice.delete(id);
3786
+ if (opts.json) {
3787
+ outputJSON(result);
3788
+ return;
3789
+ }
3790
+ success(`Deleted recurring invoice template: ${id}`);
3791
+ } catch (e) {
3792
+ if (e instanceof HisaaboApiError) {
3793
+ const err = e.hisaaboError;
3794
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3795
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3796
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3797
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3798
+ }
3799
+ fatalError(String(e instanceof Error ? e.message : e));
3800
+ }
3801
+ }
3802
+
3803
+ // src/commands/automated-invoice/history.ts
3804
+ import chalk4 from "chalk";
3805
+ function executionStatusBadge(status) {
3806
+ const map = {
3807
+ success: chalk4.green("success"),
3808
+ failed: chalk4.red("failed"),
3809
+ skipped: chalk4.yellow("skipped")
3810
+ };
3811
+ return map[status] ?? status;
3812
+ }
3813
+ async function automatedInvoiceHistoryCommand(templateId, opts) {
3814
+ const cfg = requireAuth();
3815
+ const client = new HisaaboClient(cfg);
3816
+ const page = opts.page ?? 1;
3817
+ const limit = opts.limit ?? 20;
3818
+ try {
3819
+ const result = await client.recurringInvoice.executionHistory(templateId, page, limit);
3820
+ if (opts.json) {
3821
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
3822
+ return;
3823
+ }
3824
+ console.log(`
3825
+ Execution History ${result.total} total
3826
+ `);
3827
+ const cols = [
3828
+ { key: "executedAt", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
3829
+ { key: "invoiceNumber", header: "Invoice #", width: 20 },
3830
+ { key: "status", header: "Status", width: 10, format: (v) => executionStatusBadge(String(v ?? "")) },
3831
+ { key: "errorMessage", header: "Error", width: 30, format: (v) => v ? String(v) : "\u2014" }
3832
+ ];
3833
+ if (opts.format === "tsv") outputTSV(result.data, cols);
3834
+ else if (opts.format === "csv") outputCSV(result.data, cols);
3835
+ else {
3836
+ outputTable(result.data, cols);
3837
+ paginationFooter(result.page, result.limit, result.total);
3838
+ }
3839
+ } catch (e) {
3840
+ if (e instanceof HisaaboApiError) {
3841
+ const err = e.hisaaboError;
3842
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${templateId}`, EXIT.NOT_FOUND);
3843
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3844
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3845
+ }
3846
+ fatalError(String(e instanceof Error ? e.message : e));
3847
+ }
3848
+ }
3849
+
3850
+ // src/commands/automated-invoice/usage.ts
3851
+ import chalk5 from "chalk";
3852
+ var FREE_PLAN_LIMIT = 5;
3853
+ var BAR_WIDTH = 20;
3854
+ function usageBar(used, limit) {
3855
+ const pct = limit > 0 ? Math.min(used / limit, 1) : 0;
3856
+ const filled = Math.round(pct * BAR_WIDTH);
3857
+ const empty = BAR_WIDTH - filled;
3858
+ const filledChar = "\u2588".repeat(filled);
3859
+ const emptyChar = "\u2591".repeat(empty);
3860
+ if (!hasColor()) return `[${filledChar}${emptyChar}]`;
3861
+ const bar = pct >= 1 ? chalk5.red(filledChar) : pct >= 0.8 ? chalk5.yellow(filledChar) : chalk5.green(filledChar);
3862
+ return `[${bar}${chalk5.dim(emptyChar)}]`;
3863
+ }
3864
+ async function automatedInvoiceUsageCommand(opts) {
3865
+ const cfg = requireAuth();
3866
+ const client = new HisaaboClient(cfg);
3867
+ try {
3868
+ const result = await client.recurringInvoice.planUsage();
3869
+ if (opts.json) {
3870
+ outputJSON(result);
3871
+ return;
3872
+ }
3873
+ const limit = FREE_PLAN_LIMIT;
3874
+ const pct = limit > 0 ? Math.round(result.runsThisMonth / limit * 100) : 0;
3875
+ console.log("\n Plan Usage \u2014 Recurring Invoices\n");
3876
+ console.log(` Templates: ${result.totalTemplates}`);
3877
+ console.log(` Runs/month: ${result.runsThisMonth} / ${limit} ${usageBar(result.runsThisMonth, limit)} ${pct}%`);
3878
+ if (result.runsThisMonth >= limit) {
3879
+ const msg = " Monthly run limit reached. Upgrade your plan for unlimited runs.";
3880
+ console.log(hasColor() ? chalk5.red(msg) : msg);
3881
+ } else {
3882
+ const remaining = limit - result.runsThisMonth;
3883
+ console.log(` Remaining: ${remaining} run${remaining !== 1 ? "s" : ""} this month`);
3884
+ }
3481
3885
  console.log();
3482
3886
  } catch (e) {
3887
+ if (e instanceof HisaaboApiError) {
3888
+ const err = e.hisaaboError;
3889
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3890
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3891
+ }
3483
3892
  fatalError(String(e instanceof Error ? e.message : e));
3484
3893
  }
3485
- });
3486
- business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
3894
+ }
3895
+
3896
+ // src/commands/automated-invoice/suggestions.ts
3897
+ import chalk6 from "chalk";
3898
+ var FREQUENCY_LABELS3 = {
3899
+ weekly: "Weekly",
3900
+ biweekly: "Every 2 Weeks",
3901
+ monthly: "Monthly",
3902
+ quarterly: "Quarterly",
3903
+ half_yearly: "Every 6 Months",
3904
+ yearly: "Yearly",
3905
+ custom: "Custom"
3906
+ };
3907
+ function confidenceBadge(confidence) {
3908
+ const pct = Math.round(confidence * 100);
3909
+ const label = `${pct}%`;
3910
+ if (confidence >= 0.8) return chalk6.green(label);
3911
+ if (confidence >= 0.5) return chalk6.yellow(label);
3912
+ return chalk6.dim(label);
3913
+ }
3914
+ async function automatedInvoiceSuggestionsCommand(opts) {
3487
3915
  const cfg = requireAuth();
3488
3916
  const client = new HisaaboClient(cfg);
3489
3917
  try {
3490
- const businesses = await client.business.list();
3918
+ const result = await client.recurringInvoice.suggestions();
3491
3919
  if (opts.json) {
3492
- outputJSON(businesses);
3920
+ outputJSON(result);
3493
3921
  return;
3494
3922
  }
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}`);
3923
+ if (result.length === 0) {
3924
+ console.log("\n No recurring invoice suggestions yet.\n");
3925
+ console.log(" Suggestions appear after patterns are detected in your invoice history.\n");
3926
+ return;
3927
+ }
3928
+ console.log(`
3929
+ Recurring Invoice Suggestions ${result.length} found
3930
+ `);
3931
+ const cols = [
3932
+ { key: "partyName", header: "Party", width: 24 },
3933
+ { key: "frequency", header: "Suggested Frequency", width: 20, format: (v) => FREQUENCY_LABELS3[String(v ?? "")] ?? String(v ?? "") },
3934
+ { key: "confidence", header: "Confidence", width: 12, align: "right", format: (v) => confidenceBadge(Number(v ?? 0)) },
3935
+ { key: "reason", header: "Reason", width: 36 }
3936
+ ];
3937
+ outputTable(result, cols);
3938
+ console.log();
3939
+ console.log(` Tip: run ${chalk6.cyan("hisaabo automated-invoice create --party-id <id>")} to set up a template.
3940
+ `);
3507
3941
  } catch (e) {
3508
3942
  if (e instanceof HisaaboApiError) {
3509
- if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3943
+ const err = e.hisaaboError;
3944
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3945
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3510
3946
  }
3511
3947
  fatalError(String(e instanceof Error ? e.message : e));
3512
3948
  }
3513
- });
3949
+ }
3950
+
3951
+ // src/bin/registrars/automated-invoice.ts
3952
+ function registerAutomatedInvoiceCommands(program2) {
3953
+ const automatedInvoice = program2.command("automated-invoice").alias("auto-inv").description("Recurring / automated invoice management");
3954
+ automatedInvoice.command("list").description("List recurring invoice templates").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--status <status>", "Filter by status: active, paused, completed, expired").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
3955
+ await automatedInvoiceListCommand({
3956
+ json: opts.json,
3957
+ format: opts.format,
3958
+ status: opts.status,
3959
+ page: opts.page,
3960
+ limit: opts.limit
3961
+ });
3962
+ });
3963
+ automatedInvoice.command("get <id>").description("Get recurring invoice template details").option("--json", "JSON output").action(async (id, opts) => {
3964
+ await automatedInvoiceGetCommand(id, { json: opts.json });
3965
+ });
3966
+ automatedInvoice.command("create").description("Create a new recurring invoice template").option("--json", "JSON output").option("--party-id <id>", "Party UUID").option("--name <name>", "Template name").option("--type <type>", "sale or purchase").option("--frequency <freq>", "weekly/biweekly/monthly/quarterly/half_yearly/yearly/custom").option("--custom-interval-days <n>", "Custom interval in days (when frequency is custom)").option("--line-item <desc>", "Line item description (repeatable)", (v, a) => [...a, v], []).option("--qty <n>", "Quantity (per --line-item)", (v, a) => [...a, v], []).option("--rate <n>", "Unit price (per --line-item)", (v, a) => [...a, v], []).option("--tax <n>", "Tax percent (per --line-item)", (v, a) => [...a, v], []).option("--discount <n>", "Discount percent (per --line-item)", (v, a) => [...a, v], []).option("--start-date <date>", "Start date (YYYY-MM-DD)").option("--end-date <date>", "End date (YYYY-MM-DD)").option("--max-runs <n>", "Maximum number of runs").option("--notes <text>", "Notes").action(async (opts) => {
3967
+ await automatedInvoiceCreateCommand({
3968
+ json: opts.json,
3969
+ partyId: opts.partyId,
3970
+ name: opts.name,
3971
+ type: opts.type,
3972
+ frequency: opts.frequency,
3973
+ customIntervalDays: opts.customIntervalDays,
3974
+ lineItem: opts.lineItem,
3975
+ qty: opts.qty,
3976
+ rate: opts.rate,
3977
+ tax: opts.tax,
3978
+ discount: opts.discount,
3979
+ startDate: opts.startDate,
3980
+ endDate: opts.endDate,
3981
+ maxRuns: opts.maxRuns,
3982
+ notes: opts.notes
3983
+ });
3984
+ });
3985
+ automatedInvoice.command("pause <id>").description("Pause an active recurring invoice template").option("--json", "JSON output").action(async (id, opts) => {
3986
+ await automatedInvoicePauseCommand(id, { json: opts.json });
3987
+ });
3988
+ automatedInvoice.command("resume <id>").description("Resume a paused recurring invoice template").option("--json", "JSON output").action(async (id, opts) => {
3989
+ await automatedInvoiceResumeCommand(id, { json: opts.json });
3990
+ });
3991
+ automatedInvoice.command("run-now <id>").description("Manually trigger a recurring invoice template execution").option("--json", "JSON output").action(async (id, opts) => {
3992
+ await automatedInvoiceRunNowCommand(id, { json: opts.json });
3993
+ });
3994
+ automatedInvoice.command("delete <id>").description("Delete a recurring invoice template").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3995
+ await automatedInvoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
3996
+ });
3997
+ automatedInvoice.command("update <id>").description("Update a recurring invoice template").option("--name <name>", "Template name").option("--frequency <freq>", "weekly/biweekly/monthly/quarterly/half_yearly/yearly/custom").option("--start-date <date>", "Start date (YYYY-MM-DD)").option("--end-date <date>", "End date (YYYY-MM-DD)").option("--max-runs <n>", "Maximum number of runs").option("--notes <text>", "Notes").option("--json", "JSON output").action(async (id, opts) => {
3998
+ await automatedInvoiceUpdateCommand(id, {
3999
+ json: opts.json,
4000
+ name: opts.name,
4001
+ frequency: opts.frequency,
4002
+ startDate: opts.startDate,
4003
+ endDate: opts.endDate,
4004
+ maxRuns: opts.maxRuns,
4005
+ notes: opts.notes
4006
+ });
4007
+ });
4008
+ automatedInvoice.command("history <templateId>").description("Show execution history for a recurring invoice template").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (templateId, opts) => {
4009
+ await automatedInvoiceHistoryCommand(templateId, {
4010
+ json: opts.json,
4011
+ format: opts.format,
4012
+ page: opts.page,
4013
+ limit: opts.limit
4014
+ });
4015
+ });
4016
+ automatedInvoice.command("usage").description("Show plan usage for recurring invoices").option("--json", "JSON output").action(async (opts) => {
4017
+ await automatedInvoiceUsageCommand({ json: opts.json });
4018
+ });
4019
+ automatedInvoice.command("suggestions").description("Show suggested recurring invoice templates based on invoice history").option("--json", "JSON output").action(async (opts) => {
4020
+ await automatedInvoiceSuggestionsCommand({ json: opts.json });
4021
+ });
4022
+ }
4023
+
4024
+ // src/bin/registrars/business.ts
4025
+ import * as readline13 from "readline";
4026
+ function registerBusinessCommands(program2) {
4027
+ const business = program2.command("business").description("Business management");
4028
+ business.command("list").description("List all businesses").option("--json", "JSON output").action(async (opts) => {
4029
+ const cfg = requireAuth();
4030
+ const client = new HisaaboClient(cfg);
4031
+ try {
4032
+ const businesses = await client.business.list();
4033
+ if (opts.json) {
4034
+ outputJSON(businesses);
4035
+ return;
4036
+ }
4037
+ businesses.forEach((b, i) => {
4038
+ const active = b.id === cfg.businessId ? " [active]" : "";
4039
+ console.log(` ${i + 1} ${b.name.padEnd(30)} ${(b.gstin ?? "-").padEnd(18)} ${b.gstRegistrationType}${active}`);
4040
+ });
4041
+ console.log();
4042
+ } catch (e) {
4043
+ fatalError(String(e instanceof Error ? e.message : e));
4044
+ }
4045
+ });
4046
+ business.command("get").description("Show current business details").option("--json", "JSON output").action(async (opts) => {
4047
+ const { businessGetCommand } = await import("./get-A43QCI2S.js");
4048
+ await businessGetCommand(opts);
4049
+ });
4050
+ business.command("update").description("Update business settings").option("--name <name>", "Business name").option("--gstin <gstin>", "GSTIN").option("--address <address>", "Address").option("--state <state>", "State").option("--phone <phone>", "Phone number").option("--email <email>", "Email address").option("--financial-year-start <month>", "Financial year start month (1\u201312)").option("--json", "JSON output").action(async (opts) => {
4051
+ const { businessUpdateCommand } = await import("./update-H6LPO2Z4.js");
4052
+ await businessUpdateCommand(opts);
4053
+ });
4054
+ business.command("sequence").description("Update invoice sequence number / prefix").requiredOption("--type <type>", "Document type: sale or purchase").option("--prefix <prefix>", "Invoice prefix (e.g. INV-)").option("--next-number <n>", "Next sequence number").option("--json", "JSON output").action(async (opts) => {
4055
+ const { businessSequenceCommand } = await import("./sequence-FPOJTI2P.js");
4056
+ await businessSequenceCommand(opts);
4057
+ });
4058
+ business.command("audit-trail").description("View audit log for this business").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "25").option("--json", "JSON output").option("--format <fmt>", "Output format: table, tsv, csv").action(async (opts) => {
4059
+ const { businessAuditTrailCommand } = await import("./audit-trail-5LOCJ7XZ.js");
4060
+ await businessAuditTrailCommand(opts);
4061
+ });
4062
+ business.command("export").description("Export all business data").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (opts) => {
4063
+ const { businessExportCommand } = await import("./export-QICOQK34.js");
4064
+ await businessExportCommand(opts);
4065
+ });
4066
+ business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
4067
+ const cfg = requireAuth();
4068
+ const client = new HisaaboClient(cfg);
4069
+ try {
4070
+ const businesses = await client.business.list();
4071
+ if (opts.json) {
4072
+ outputJSON(businesses);
4073
+ return;
4074
+ }
4075
+ businesses.forEach((b, i) => {
4076
+ const active = b.id === cfg.businessId ? " [active]" : "";
4077
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
4078
+ });
4079
+ const rl = readline13.createInterface({ input: process.stdin, output: process.stdout });
4080
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
4081
+ rl.close();
4082
+ const idx = parseInt(answer.trim(), 10) - 1;
4083
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
4084
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
4085
+ setConfig({ businessId: selected.id, businessName: selected.name });
4086
+ success(`Switched to: ${selected.name}`);
4087
+ } catch (e) {
4088
+ if (e instanceof HisaaboApiError) {
4089
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
4090
+ }
4091
+ fatalError(String(e instanceof Error ? e.message : e));
4092
+ }
4093
+ });
4094
+ }
4095
+
4096
+ // src/bin/registrars/document.ts
4097
+ var DOC_TYPES = [
4098
+ {
4099
+ cmd: "quotation",
4100
+ label: "Quotation",
4101
+ nsKey: "quotation",
4102
+ statuses: ["draft", "sent", "accepted", "rejected", "expired", "cancelled"]
4103
+ },
4104
+ {
4105
+ cmd: "credit-note",
4106
+ label: "Credit Note",
4107
+ nsKey: "creditNote",
4108
+ statuses: ["draft", "confirmed", "cancelled"]
4109
+ },
4110
+ {
4111
+ cmd: "debit-note",
4112
+ label: "Debit Note",
4113
+ nsKey: "debitNote",
4114
+ statuses: ["draft", "confirmed", "cancelled"]
4115
+ },
4116
+ {
4117
+ cmd: "delivery-challan",
4118
+ label: "Delivery Challan",
4119
+ nsKey: "deliveryChallan",
4120
+ statuses: ["draft", "dispatched", "delivered", "cancelled"]
4121
+ },
4122
+ {
4123
+ cmd: "proforma",
4124
+ label: "Proforma Invoice",
4125
+ nsKey: "proforma",
4126
+ statuses: ["draft", "sent", "accepted", "rejected", "expired", "converted", "cancelled"]
4127
+ },
4128
+ {
4129
+ cmd: "sales-return",
4130
+ label: "Sales Return",
4131
+ nsKey: "salesReturn",
4132
+ statuses: ["draft", "confirmed", "cancelled"]
4133
+ },
4134
+ {
4135
+ cmd: "purchase-return",
4136
+ label: "Purchase Return",
4137
+ nsKey: "purchaseReturn",
4138
+ statuses: ["draft", "confirmed", "cancelled"]
4139
+ }
4140
+ ];
4141
+ function registerDocumentCommands(program2) {
4142
+ for (const dt of DOC_TYPES) {
4143
+ const parent = program2.command(dt.cmd).description(`${dt.label} management`);
4144
+ parent.command("list").description(`List ${dt.label.toLowerCase()}s`).option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv, ids").option("--status <status>", `Filter by status: ${dt.statuses.join(", ")}`).option("--party <search>", "Filter by party name").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Current month").option("--this-fy", "Current financial year").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Items per page", parseInt).action(async (opts) => {
4145
+ const { docListCommand } = await import("./factory-KOCW2AQM.js");
4146
+ await docListCommand(dt, opts);
4147
+ });
4148
+ parent.command("get <id>").description(`Get ${dt.label.toLowerCase()} details`).option("--json", "JSON output").action(async (id, opts) => {
4149
+ const { docGetCommand } = await import("./factory-KOCW2AQM.js");
4150
+ await docGetCommand(dt, id, opts);
4151
+ });
4152
+ parent.command("create").description(`Create a new ${dt.label.toLowerCase()}`).option("--json", "JSON output").option("--party-id <id>", "Party UUID").option("--party <name>", "Party search name").option("--date <date>", "Document date (YYYY-MM-DD)").option("--due-date <date>", "Due date (YYYY-MM-DD)").option("--item <desc>", "Item description (repeatable)", (v, a) => [...a, v], []).option("--qty <n>", "Quantity per item (repeatable)", (v, a) => [...a, v], []).option("--rate <n>", "Rate per item (repeatable)", (v, a) => [...a, v], []).option("--notes <text>", "Notes").option("--discount <pct>", "Discount percent").option("-y, --yes", "Skip confirmation").action(async (opts) => {
4153
+ const { docCreateCommand } = await import("./factory-KOCW2AQM.js");
4154
+ await docCreateCommand(dt, opts);
4155
+ });
4156
+ parent.command("update-status <id> <status>").description(`Update ${dt.label.toLowerCase()} status (${dt.statuses.join(", ")})`).option("--json", "JSON output").action(async (id, status, opts) => {
4157
+ const { docStatusCommand } = await import("./factory-KOCW2AQM.js");
4158
+ await docStatusCommand(dt, id, status, opts);
4159
+ });
4160
+ parent.command("delete <id>").description(`Delete a ${dt.label.toLowerCase()}`).option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
4161
+ const { docDeleteCommand } = await import("./factory-KOCW2AQM.js");
4162
+ await docDeleteCommand(dt, id, opts);
4163
+ });
4164
+ }
4165
+ program2.command("document").description("Document conversion operations").command("convert").description("Convert one document type to another").requiredOption("--from-type <type>", "Source type (quotation, proforma, delivery-challan, etc.)").requiredOption("--from-id <id>", "Source document ID").requiredOption("--to-type <type>", "Target type (invoice, credit-note, etc.)").option("--json", "JSON output").option("-y, --yes", "Skip confirmation").action(async (opts) => {
4166
+ const { HisaaboClient: HisaaboClient2, HisaaboApiError: HisaaboApiError2 } = await import("./client-5NZ23GML.js");
4167
+ const { requireAuth: requireAuth2 } = await import("./config-335MN4I7.js");
4168
+ const { fatalError: fatalError2, outputJSON: outputJSON2, success: success2, EXIT: EXIT2 } = await import("./output-NUOL7KJW.js");
4169
+ const cfg = requireAuth2();
4170
+ const client = new HisaaboClient2(cfg);
4171
+ if (!opts.yes && process.stdin.isTTY) {
4172
+ const readline14 = await import("readline");
4173
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
4174
+ const answer = await new Promise((resolve2) => {
4175
+ rl.question(
4176
+ ` Convert ${opts.fromType} ${opts.fromId} \u2192 ${opts.toType}? (y/N): `,
4177
+ resolve2
4178
+ );
4179
+ });
4180
+ rl.close();
4181
+ if (answer.trim().toLowerCase() !== "y") {
4182
+ console.log(" Cancelled.");
4183
+ process.exit(EXIT2.SUCCESS);
4184
+ }
4185
+ }
4186
+ try {
4187
+ const result = await client.document.convert({
4188
+ fromType: opts.fromType,
4189
+ fromId: opts.fromId,
4190
+ toType: opts.toType
4191
+ });
4192
+ if (opts.json) {
4193
+ outputJSON2(result);
4194
+ return;
4195
+ }
4196
+ const newId = result.id ?? result.documentId ?? "(unknown)";
4197
+ const newNum = result.documentNumber ?? result.number ?? newId;
4198
+ success2(`Converted: ${opts.fromType} \u2192 ${opts.toType} ${newNum}`);
4199
+ console.log(` New ID: ${newId}
4200
+ `);
4201
+ } catch (e) {
4202
+ if (e instanceof HisaaboApiError2) {
4203
+ const err = e.hisaaboError;
4204
+ if (err.code === "not_found") fatalError2(`Source document not found: ${opts.fromId}`, EXIT2.NOT_FOUND);
4205
+ if (err.code === "unauthorized") fatalError2("Session expired. Run: hisaabo login", EXIT2.AUTH);
4206
+ if (err.code === "forbidden") fatalError2(err.message, EXIT2.FORBIDDEN);
4207
+ if (err.code === "validation_failed") fatalError2(e.message, EXIT2.VALIDATION);
4208
+ if (err.code === "network_error") fatalError2(err.message, EXIT2.NETWORK);
4209
+ }
4210
+ fatalError2(String(e instanceof Error ? e.message : e));
4211
+ }
4212
+ });
4213
+ }
4214
+
4215
+ // src/bin/registrars/tenant.ts
4216
+ function registerTenantCommands(program2) {
4217
+ const tenant = program2.command("tenant").description("Tenant / workspace management");
4218
+ tenant.command("list").description("List tenants / organizations you belong to").option("--json", "JSON output").action(async (opts) => {
4219
+ const { tenantListCommand } = await import("./list-T74SN6IR.js");
4220
+ await tenantListCommand({ json: opts.json });
4221
+ });
4222
+ tenant.command("members").description("List members of the current tenant").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (opts) => {
4223
+ const { tenantMembersCommand } = await import("./members-W2GW3ODT.js");
4224
+ await tenantMembersCommand({ json: opts.json, format: opts.format });
4225
+ });
4226
+ tenant.command("invite <email>").description("Invite a user to the tenant").option("--role <role>", "Role: admin, seller_manager, seller, accountant (default: seller)").option("--json", "JSON output").action(async (email, opts) => {
4227
+ const { tenantInviteCommand } = await import("./invite-T3CKX53E.js");
4228
+ await tenantInviteCommand(email, { role: opts.role, json: opts.json });
4229
+ });
4230
+ tenant.command("remove <userId>").description("Remove a member from the tenant").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (userId, opts) => {
4231
+ const { tenantRemoveCommand } = await import("./remove-6QZI4JCY.js");
4232
+ await tenantRemoveCommand(userId, { yes: opts.yes, json: opts.json });
4233
+ });
4234
+ tenant.command("update-role <userId> <role>").description("Update a member's role (admin, seller_manager, seller, accountant)").option("--json", "JSON output").action(async (userId, role, opts) => {
4235
+ const { tenantUpdateRoleCommand } = await import("./update-role-QST7BVFX.js");
4236
+ await tenantUpdateRoleCommand(userId, role, { json: opts.json });
4237
+ });
4238
+ tenant.command("invitations").description("List pending invitations").option("--json", "JSON output").action(async (opts) => {
4239
+ const { listInvitationsCommand } = await import("./invitations-P3EEN5WI.js");
4240
+ await listInvitationsCommand(opts);
4241
+ });
4242
+ tenant.command("revoke-invitation <invitationId>").description("Revoke a pending invitation").option("--json", "JSON output").action(async (invitationId, opts) => {
4243
+ const { revokeInvitationCommand } = await import("./revoke-invitation-DTGQRJR4.js");
4244
+ await revokeInvitationCommand(invitationId, opts);
4245
+ });
4246
+ }
4247
+
4248
+ // src/bin/registrars/api-key.ts
4249
+ function registerApiKeyCommands(program2) {
4250
+ const apiKey = program2.command("api-key").alias("key").description("API key management");
4251
+ apiKey.command("list").description("List all API keys").option("--json", "JSON output").option("--format <fmt>", "Output format: table, tsv, csv").action(async (opts) => {
4252
+ const { apiKeyListCommand } = await import("./list-A2RKI3ZG.js");
4253
+ await apiKeyListCommand(opts);
4254
+ });
4255
+ apiKey.command("create").description("Create a new API key").requiredOption("--name <name>", "Name / label for this key").option("--json", "JSON output").action(async (opts) => {
4256
+ const { apiKeyCreateCommand } = await import("./create-RPDEORDD.js");
4257
+ await apiKeyCreateCommand(opts);
4258
+ });
4259
+ apiKey.command("revoke <id>").description("Revoke an API key by ID").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
4260
+ const { apiKeyRevokeCommand } = await import("./revoke-YUCFZFNR.js");
4261
+ await apiKeyRevokeCommand(id, opts);
4262
+ });
4263
+ }
4264
+
4265
+ // src/bin/registrars/session.ts
4266
+ function registerSessionCommands(program2) {
4267
+ const session = program2.command("session").description("Manage active sessions");
4268
+ session.command("list").description("List active sessions").option("--expired", "Show expired sessions instead").option("--json", "JSON output").action(async (opts) => {
4269
+ const { listSessionsCommand } = await import("./list-NRMBMKMI.js");
4270
+ await listSessionsCommand(opts);
4271
+ });
4272
+ session.command("revoke <sessionId>").description("Revoke a specific session").option("--json", "JSON output").action(async (sessionId, opts) => {
4273
+ const { revokeSessionCommand } = await import("./revoke-AVEMPAC7.js");
4274
+ await revokeSessionCommand(sessionId, opts);
4275
+ });
4276
+ session.command("revoke-all").description("Sign out from all devices").action(async () => {
4277
+ const { revokeAllSessionsCommand } = await import("./revoke-all-LFW5WBHO.js");
4278
+ await revokeAllSessionsCommand();
4279
+ });
4280
+ }
4281
+
4282
+ // src/bin/hisaabo.ts
4283
+ var program = new Command();
4284
+ var cliVersion = true ? "0.4.0" : "dev";
4285
+ program.name("hisaabo").description("Hisaabo CLI \u2014 Invoicing and business management").version(cliVersion);
4286
+ registerAuthCommands(program);
4287
+ registerDashboardCommands(program);
4288
+ registerInvoiceCommands(program);
4289
+ registerPartyCommands(program);
4290
+ registerItemCommands(program);
4291
+ registerPaymentCommands(program);
4292
+ registerExpenseCommands(program);
4293
+ registerGstCommands(program);
4294
+ registerReportCommands(program);
4295
+ registerBankCommands(program);
4296
+ registerShipmentCommands(program);
4297
+ registerTargetCommands(program);
4298
+ registerStoreCommands(program);
4299
+ registerImportCommands(program);
4300
+ registerAutomatedInvoiceCommands(program);
4301
+ registerBusinessCommands(program);
4302
+ registerDocumentCommands(program);
4303
+ registerTenantCommands(program);
4304
+ registerApiKeyCommands(program);
4305
+ registerSessionCommands(program);
3514
4306
  program.parseAsync(process.argv).catch((err) => {
3515
4307
  fatalError(String(err instanceof Error ? err.message : err));
3516
4308
  });