@hisaabo/cli 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +332 -0
  2. package/dist/bin/audit-trail-2YGXGUXW.js +78 -0
  3. package/dist/bin/categories-P5VFWD5F.js +47 -0
  4. package/dist/bin/check-slug-4TMOTWUJ.js +65 -0
  5. package/dist/bin/chunk-2P35S2C3.js +46 -0
  6. package/dist/bin/chunk-EYNDY7RB.js +175 -0
  7. package/dist/bin/chunk-FFBG6RU4.js +156 -0
  8. package/dist/bin/chunk-FTOBDKMO.js +804 -0
  9. package/dist/bin/client-QNJ2H5CW.js +11 -0
  10. package/dist/bin/collection-efficiency-WMKEGS6U.js +165 -0
  11. package/dist/bin/config-UKVQYPPR.js +18 -0
  12. package/dist/bin/create-Y22FAVOW.js +83 -0
  13. package/dist/bin/default-account-SA56M66A.js +58 -0
  14. package/dist/bin/expenses-VZAOLYUW.js +89 -0
  15. package/dist/bin/export-QZ6WT6PJ.js +59 -0
  16. package/dist/bin/factory-2DCU3B5T.js +483 -0
  17. package/dist/bin/get-6UYP6UVD.js +71 -0
  18. package/dist/bin/get-EXL44I2X.js +66 -0
  19. package/dist/bin/hisaabo.js +2029 -1450
  20. package/dist/bin/invite-O26SAL72.js +53 -0
  21. package/dist/bin/invoice-breakdown-XEATXVMR.js +97 -0
  22. package/dist/bin/items-3U5USBVG.js +62 -0
  23. package/dist/bin/items-toggle-YEKMI2CM.js +46 -0
  24. package/dist/bin/list-FX2C3NCL.js +46 -0
  25. package/dist/bin/list-VBAHY72W.js +79 -0
  26. package/dist/bin/members-5FPRUAB6.js +55 -0
  27. package/dist/bin/monthly-comparison-JEJ3TTY2.js +176 -0
  28. package/dist/bin/order-cancel-XI2LKYXV.js +55 -0
  29. package/dist/bin/order-confirm-HUFCU6MO.js +53 -0
  30. package/dist/bin/order-get-NSDMPUZR.js +88 -0
  31. package/dist/bin/order-update-C7QYSD5R.js +60 -0
  32. package/dist/bin/output-QFLEKG5W.js +35 -0
  33. package/dist/bin/payment-modes-WI3AWSES.js +126 -0
  34. package/dist/bin/profit-loss-5RIEOBKP.js +135 -0
  35. package/dist/bin/receivables-aging-L6DIQCNE.js +161 -0
  36. package/dist/bin/remove-M2B4TZ37.js +52 -0
  37. package/dist/bin/revoke-H3V2GNCD.js +52 -0
  38. package/dist/bin/sales-trend-TICB3KGF.js +71 -0
  39. package/dist/bin/sequence-XUD6FAKY.js +66 -0
  40. package/dist/bin/store-UQ2DDQ5I.js +82 -0
  41. package/dist/bin/summary-BPNFC7I2.js +113 -0
  42. package/dist/bin/top-customers-WGGJWKCN.js +81 -0
  43. package/dist/bin/top-items-C7ZDDJMR.js +84 -0
  44. package/dist/bin/top-outstanding-MOGWJIQS.js +64 -0
  45. package/dist/bin/unpaid-invoices-ZUPNMQJP.js +65 -0
  46. package/dist/bin/untracked-BCJEVDW4.js +67 -0
  47. package/dist/bin/update-HIU4PANX.js +54 -0
  48. package/dist/bin/update-IG565YIN.js +61 -0
  49. package/dist/bin/update-PVLAX7T3.js +57 -0
  50. package/dist/bin/update-role-Q4ZYJRYT.js +45 -0
  51. package/dist/bin/update-settings-XPC6L5WM.js +56 -0
  52. package/package.json +6 -1
  53. package/src/bin/hisaabo.ts +42 -933
  54. package/src/bin/registrars/api-key.ts +44 -0
  55. package/src/bin/registrars/auth.ts +153 -0
  56. package/src/bin/registrars/automated-invoice.ts +167 -0
  57. package/src/bin/registrars/bank.ts +90 -0
  58. package/src/bin/registrars/business.ts +120 -0
  59. package/src/bin/registrars/dashboard.ts +225 -0
  60. package/src/bin/registrars/document.ts +184 -0
  61. package/src/bin/registrars/expense.ts +87 -0
  62. package/src/bin/registrars/gst.ts +41 -0
  63. package/src/bin/registrars/import.ts +49 -0
  64. package/src/bin/registrars/invoice.ts +117 -0
  65. package/src/bin/registrars/item.ts +112 -0
  66. package/src/bin/registrars/party.ts +81 -0
  67. package/src/bin/registrars/payment.ts +128 -0
  68. package/src/bin/registrars/report.ts +142 -0
  69. package/src/bin/registrars/shipment.ts +74 -0
  70. package/src/bin/registrars/store.ts +128 -0
  71. package/src/bin/registrars/target.ts +46 -0
  72. package/src/bin/registrars/tenant.ts +55 -0
  73. package/src/client.ts +495 -4
  74. package/src/commands/api-key/create.ts +72 -0
  75. package/src/commands/api-key/list.ts +71 -0
  76. package/src/commands/api-key/revoke.ts +46 -0
  77. package/src/commands/automated-invoice/create.ts +85 -0
  78. package/src/commands/automated-invoice/delete.ts +42 -0
  79. package/src/commands/automated-invoice/get.ts +113 -0
  80. package/src/commands/automated-invoice/history.ts +65 -0
  81. package/src/commands/automated-invoice/index.ts +11 -0
  82. package/src/commands/automated-invoice/list.ts +91 -0
  83. package/src/commands/automated-invoice/pause.ts +29 -0
  84. package/src/commands/automated-invoice/resume.ts +29 -0
  85. package/src/commands/automated-invoice/run-now.ts +29 -0
  86. package/src/commands/automated-invoice/suggestions.ts +68 -0
  87. package/src/commands/automated-invoice/update.ts +54 -0
  88. package/src/commands/automated-invoice/usage.ts +68 -0
  89. package/src/commands/business/audit-trail.ts +79 -0
  90. package/src/commands/business/export.ts +52 -0
  91. package/src/commands/business/get.ts +55 -0
  92. package/src/commands/business/sequence.ts +65 -0
  93. package/src/commands/business/update.ts +64 -0
  94. package/src/commands/dashboard/collection-efficiency.ts +164 -0
  95. package/src/commands/dashboard/expenses.ts +76 -0
  96. package/src/commands/dashboard/invoice-breakdown.ts +89 -0
  97. package/src/commands/dashboard/monthly-comparison.ts +193 -0
  98. package/src/commands/dashboard/payment-modes.ts +121 -0
  99. package/src/commands/dashboard/profit-loss.ts +146 -0
  100. package/src/commands/dashboard/receivables-aging.ts +169 -0
  101. package/src/commands/dashboard/sales-trend.ts +68 -0
  102. package/src/commands/dashboard/summary.ts +105 -0
  103. package/src/commands/dashboard/top-customers.ts +70 -0
  104. package/src/commands/dashboard/top-items.ts +74 -0
  105. package/src/commands/dashboard/top-outstanding.ts +61 -0
  106. package/src/commands/document/factory.ts +590 -0
  107. package/src/commands/expense/categories.ts +40 -0
  108. package/src/commands/expense/update.ts +58 -0
  109. package/src/commands/import/index.ts +68 -0
  110. package/src/commands/item/categories.ts +40 -0
  111. package/src/commands/item/low-stock-count.ts +32 -0
  112. package/src/commands/item/merge.ts +53 -0
  113. package/src/commands/item/price-history.ts +59 -0
  114. package/src/commands/item/rename-unit.ts +39 -0
  115. package/src/commands/item/sales-stats.ts +44 -0
  116. package/src/commands/item/stock-history.ts +70 -0
  117. package/src/commands/item/switch-base-unit.ts +42 -0
  118. package/src/commands/item/update.ts +59 -0
  119. package/src/commands/item/variants-create.ts +58 -0
  120. package/src/commands/item/variants-delete.ts +47 -0
  121. package/src/commands/item/variants-list.ts +63 -0
  122. package/src/commands/item/variants-update.ts +61 -0
  123. package/src/commands/party/ledger-report.ts +81 -0
  124. package/src/commands/party/merge.ts +50 -0
  125. package/src/commands/party/stats.ts +40 -0
  126. package/src/commands/party/top-items.ts +57 -0
  127. package/src/commands/party/update.ts +65 -0
  128. package/src/commands/payment/default-account.ts +56 -0
  129. package/src/commands/payment/get.ts +59 -0
  130. package/src/commands/payment/unpaid-invoices.ts +69 -0
  131. package/src/commands/payment/untracked.ts +70 -0
  132. package/src/commands/payment/update.ts +54 -0
  133. package/src/commands/report/index.ts +348 -1
  134. package/src/commands/store/check-slug.ts +48 -0
  135. package/src/commands/store/items-toggle.ts +41 -0
  136. package/src/commands/store/items.ts +61 -0
  137. package/src/commands/store/order-cancel.ts +48 -0
  138. package/src/commands/store/order-confirm.ts +45 -0
  139. package/src/commands/store/order-get.ts +66 -0
  140. package/src/commands/store/order-update.ts +52 -0
  141. package/src/commands/store/update-settings.ts +52 -0
  142. package/src/commands/tenant/invite.ts +57 -0
  143. package/src/commands/tenant/list.ts +46 -0
  144. package/src/commands/tenant/members.ts +55 -0
  145. package/src/commands/tenant/remove.ts +47 -0
  146. package/src/commands/tenant/update-role.ts +41 -0
@@ -1,605 +1,49 @@
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-FFBG6RU4.js";
15
+ import {
16
+ HisaaboApiError,
17
+ HisaaboClient
18
+ } from "./chunk-FTOBDKMO.js";
19
+ import {
20
+ clearConfig,
21
+ getConfig,
22
+ getConfigPath,
23
+ requireAuth,
24
+ setConfig
25
+ } from "./chunk-2P35S2C3.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-EYNDY7RB.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
-
420
- // src/output.ts
421
- import chalk from "chalk";
422
- function isInteractive() {
423
- return process.stdout.isTTY === true;
424
- }
425
- function hasColor() {
426
- if (process.env["NO_COLOR"] !== void 0) return false;
427
- if (process.env["FORCE_COLOR"] === "0") return false;
428
- return process.stdout.hasColors?.() ?? isInteractive();
429
- }
430
- function stripAnsi(str) {
431
- return str.replace(/\x1b\[[0-9;]*m/g, "");
432
- }
433
- function getWidthTier() {
434
- const w = process.stdout.columns ?? 80;
435
- if (w < 80) return "narrow";
436
- if (w <= 120) return "standard";
437
- return "wide";
438
- }
439
- function termWidth() {
440
- return process.stdout.columns ?? 80;
441
- }
442
- var EXIT = {
443
- SUCCESS: 0,
444
- GENERAL: 1,
445
- USAGE: 2,
446
- AUTH: 3,
447
- FORBIDDEN: 4,
448
- NOT_FOUND: 5,
449
- VALIDATION: 6,
450
- NETWORK: 7,
451
- CONFLICT: 8
452
- };
453
- function fatalError(message, code = 1) {
454
- if (hasColor()) {
455
- process.stderr.write(chalk.red("Error: ") + message + "\n");
456
- } else {
457
- process.stderr.write("Error: " + message + "\n");
458
- }
459
- process.exit(code);
460
- }
461
- function success(message) {
462
- if (hasColor()) {
463
- process.stdout.write(chalk.green("\u2713 ") + message + "\n");
464
- } else {
465
- process.stdout.write("OK: " + message + "\n");
466
- }
467
- }
468
- function warn(message) {
469
- if (hasColor()) {
470
- process.stderr.write(chalk.yellow("Warning: ") + message + "\n");
471
- } else {
472
- process.stderr.write("Warning: " + message + "\n");
473
- }
474
- }
475
- function outputJSON(data) {
476
- process.stdout.write(JSON.stringify(data, null, 2) + "\n");
477
- }
478
- function getNestedValue(obj, key) {
479
- const parts = key.split(".");
480
- let cur = obj;
481
- for (const part of parts) {
482
- if (cur == null || typeof cur !== "object") return void 0;
483
- cur = cur[part];
484
- }
485
- return cur;
486
- }
487
- function padEnd(str, len) {
488
- const visual = stripAnsi(str).length;
489
- const pad = Math.max(0, len - visual);
490
- return str + " ".repeat(pad);
491
- }
492
- function padStart(str, len) {
493
- const visual = stripAnsi(str).length;
494
- const pad = Math.max(0, len - visual);
495
- return " ".repeat(pad) + str;
496
- }
497
- function outputTable(rows, columns) {
498
- if (rows.length === 0) {
499
- process.stdout.write(" (no results)\n");
500
- return;
501
- }
502
- const widths = columns.map((col) => {
503
- let max = stripAnsi(col.header).length;
504
- for (const row of rows) {
505
- const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
506
- const vis = stripAnsi(val).length;
507
- if (vis > max) max = vis;
508
- }
509
- if (col.width) max = Math.min(max, col.width);
510
- return max;
511
- });
512
- const sep = "\u2500".repeat(widths.reduce((s, w) => s + w + 2, 1));
513
- let header = " ";
514
- for (let i = 0; i < columns.length; i++) {
515
- const col = columns[i];
516
- const h = col.align === "right" ? padStart(col.header, widths[i]) : padEnd(col.header, widths[i]);
517
- header += (hasColor() ? chalk.dim(h) : h) + " ";
518
- }
519
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
520
- process.stdout.write(header.trimEnd() + "\n");
521
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
522
- for (const row of rows) {
523
- let line = " ";
524
- for (let i = 0; i < columns.length; i++) {
525
- const col = columns[i];
526
- let val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
527
- const vis = stripAnsi(val).length;
528
- if (col.width && vis > col.width) {
529
- val = val.slice(0, col.width - 1) + "\u2026";
530
- }
531
- const cell = col.align === "right" ? padStart(val, widths[i]) : padEnd(val, widths[i]);
532
- line += cell + " ";
533
- }
534
- process.stdout.write(line.trimEnd() + "\n");
535
- }
536
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
537
- }
538
- function outputTSV(rows, columns) {
539
- process.stdout.write(columns.map((c) => c.header).join(" ") + "\n");
540
- for (const row of rows) {
541
- const line = columns.map((col) => {
542
- const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
543
- return stripAnsi(val).replace(/\t/g, " ");
544
- });
545
- process.stdout.write(line.join(" ") + "\n");
546
- }
547
- }
548
- function csvEscape(val) {
549
- if (val.includes(",") || val.includes('"') || val.includes("\n")) {
550
- return `"${val.replace(/"/g, '""')}"`;
551
- }
552
- return val;
553
- }
554
- function outputCSV(rows, columns) {
555
- process.stdout.write(columns.map((c) => csvEscape(c.header)).join(",") + "\n");
556
- for (const row of rows) {
557
- const line = columns.map((col) => {
558
- const val = col.format ? col.format(getNestedValue(row, col.key), row) : String(getNestedValue(row, col.key) ?? "");
559
- return csvEscape(stripAnsi(val));
560
- });
561
- process.stdout.write(line.join(",") + "\n");
562
- }
563
- }
564
- function outputIds(ids) {
565
- for (const id of ids) {
566
- process.stdout.write(id + "\n");
567
- }
568
- }
569
- function paginationFooter(page, limit, total) {
570
- const from = (page - 1) * limit + 1;
571
- const to = Math.min(page * limit, total);
572
- const msg = ` Showing ${from}-${to} of ${total}`;
573
- process.stdout.write("\n" + (hasColor() ? chalk.dim(msg) : msg) + "\n");
574
- }
575
44
 
576
- // src/config.ts
577
- var conf = new Conf({
578
- projectName: "hisaabo",
579
- projectSuffix: "",
580
- configName: "config"
581
- });
582
- function getConfig() {
583
- return conf.store;
584
- }
585
- function setConfig(values) {
586
- for (const [k, v] of Object.entries(values)) {
587
- conf.set(k, v);
588
- }
589
- }
590
- function clearConfig() {
591
- conf.clear();
592
- }
593
- function requireAuth() {
594
- const cfg = getConfig();
595
- if (!cfg.token || !cfg.apiUrl || !cfg.businessId || !cfg.tenantId) {
596
- fatalError("Not authenticated. Run: hisaabo login", 3);
597
- }
598
- return cfg;
599
- }
600
- function getConfigPath() {
601
- return conf.path;
602
- }
45
+ // src/bin/registrars/auth.ts
46
+ import * as readline from "readline";
603
47
 
604
48
  // src/auth.ts
605
49
  async function loginWithToken(apiUrl, token) {
@@ -649,8 +93,8 @@ async function loginWithToken(apiUrl, token) {
649
93
  console.log();
650
94
  let selected = businesses[0];
651
95
  if (businesses.length > 1) {
652
- const readline12 = await import("readline");
653
- const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
96
+ const readline14 = await import("readline");
97
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
654
98
  const answer = await new Promise((resolve2) => {
655
99
  rl.question(" Select business [1]: ", resolve2);
656
100
  });
@@ -705,8 +149,8 @@ async function login(apiUrl, email, password) {
705
149
  console.log();
706
150
  let selected = businesses[0];
707
151
  if (businesses.length > 1) {
708
- const readline12 = await import("readline");
709
- const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
152
+ const readline14 = await import("readline");
153
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
710
154
  const answer = await new Promise((resolve2) => {
711
155
  rl.question(" Select business [1]: ", resolve2);
712
156
  });
@@ -773,240 +217,227 @@ async function whoami(jsonMode) {
773
217
  }
774
218
  }
775
219
 
776
- // src/format.ts
777
- import chalk2 from "chalk";
778
- function formatINR(amount) {
779
- const num = typeof amount === "string" ? parseFloat(amount) : amount;
780
- if (isNaN(num)) return "0.00";
781
- const abs = Math.abs(num);
782
- const formatted = new Intl.NumberFormat("en-IN", {
783
- minimumFractionDigits: 2,
784
- maximumFractionDigits: 2
785
- }).format(abs);
786
- return (num < 0 ? "-" : "") + "\u20B9" + formatted;
787
- }
788
- function formatAmount(amount) {
789
- const num = typeof amount === "string" ? parseFloat(amount) : amount;
790
- if (isNaN(num)) return "0.00";
791
- const abs = Math.abs(num);
792
- const formatted = new Intl.NumberFormat("en-IN", {
793
- minimumFractionDigits: 2,
794
- maximumFractionDigits: 2
795
- }).format(abs);
796
- return (num < 0 ? "-" : "") + formatted;
797
- }
798
- var MONTHS = [
799
- "Jan",
800
- "Feb",
801
- "Mar",
802
- "Apr",
803
- "May",
804
- "Jun",
805
- "Jul",
806
- "Aug",
807
- "Sep",
808
- "Oct",
809
- "Nov",
810
- "Dec"
811
- ];
812
- function formatDate(date) {
813
- if (!date) return "-";
814
- try {
815
- const d = new Date(date);
816
- if (isNaN(d.getTime())) return date;
817
- const day = String(d.getDate()).padStart(2, "0");
818
- const month = MONTHS[d.getMonth()];
819
- const year = d.getFullYear();
820
- return `${day} ${month} ${year}`;
821
- } catch {
822
- return date;
823
- }
824
- }
825
- function formatRelativeDate(date) {
826
- if (!date) return "-";
827
- try {
828
- const d = new Date(date);
829
- const now = /* @__PURE__ */ new Date();
830
- const diff = Math.floor((now.getTime() - d.getTime()) / (1e3 * 60 * 60 * 24));
831
- if (diff === 0) return "Today";
832
- if (diff === 1) return "Yesterday";
833
- if (diff < 30) return `${diff}d ago`;
834
- if (diff < 365) return `${Math.floor(diff / 30)}mo ago`;
835
- return `${Math.floor(diff / 365)}y ago`;
836
- } catch {
837
- return date ?? "-";
838
- }
839
- }
840
- var STATUS_CONFIG = {
841
- paid: { label: "PAID", color: (s) => chalk2.green(s) },
842
- sent: { label: "SENT", color: (s) => chalk2.blue(s) },
843
- draft: { label: "DRAFT", color: (s) => chalk2.dim(s) },
844
- partial: { label: "PARTIAL", color: (s) => chalk2.yellow(s) },
845
- overdue: { label: "OVERDUE", color: (s) => chalk2.red(s) },
846
- cancelled: { label: "CANCEL", color: (s) => chalk2.dim(chalk2.strikethrough(s)) },
847
- unfulfilled: { label: "UNFUL", color: (s) => chalk2.blue(s) },
848
- pending: { label: "PEND", color: (s) => chalk2.yellow(s) },
849
- confirmed: { label: "CONF", color: (s) => chalk2.blue(s) },
850
- delivered: { label: "DELIV", color: (s) => chalk2.green(s) },
851
- shipped: { label: "SHIPPED", color: (s) => chalk2.blue(s) },
852
- in_transit: { label: "TRANSIT", color: (s) => chalk2.cyan(s) },
853
- returned: { label: "RETURN", color: (s) => chalk2.red(s) },
854
- preparing: { label: "PREP", color: (s) => chalk2.yellow(s) },
855
- ready: { label: "READY", color: (s) => chalk2.cyan(s) }
856
- };
857
- function formatStatus(status) {
858
- const cfg = STATUS_CONFIG[status.toLowerCase()];
859
- const label = cfg ? `[${cfg.label}]` : `[${status.toUpperCase()}]`;
860
- if (!hasColor() || !cfg) return label;
861
- return cfg.color(label);
862
- }
863
- function currentFY() {
864
- const now = /* @__PURE__ */ new Date();
865
- const year = now.getFullYear();
866
- const month = now.getMonth() + 1;
867
- if (month >= 4) {
868
- return `${year}-${String(year + 1).slice(2)}`;
869
- }
870
- return `${year - 1}-${String(year).slice(2)}`;
871
- }
872
- function fyStart() {
873
- const now = /* @__PURE__ */ new Date();
874
- const year = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
875
- return `${year}-04-01`;
876
- }
877
- function todayISO() {
878
- return (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "";
879
- }
880
- function monthStart() {
881
- const now = /* @__PURE__ */ new Date();
882
- return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`;
883
- }
884
- function monthEnd() {
885
- const now = /* @__PURE__ */ new Date();
886
- const last = new Date(now.getFullYear(), now.getMonth() + 1, 0);
887
- return `${last.getFullYear()}-${String(last.getMonth() + 1).padStart(2, "0")}-${String(last.getDate()).padStart(2, "0")}`;
888
- }
889
- function quarterRange(q) {
890
- const now = /* @__PURE__ */ new Date();
891
- const fyYear = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
892
- const ranges = {
893
- Q1: { from: `${fyYear}-04-01`, to: `${fyYear}-06-30`, month: 4, year: fyYear },
894
- Q2: { from: `${fyYear}-07-01`, to: `${fyYear}-09-30`, month: 7, year: fyYear },
895
- Q3: { from: `${fyYear}-10-01`, to: `${fyYear}-12-31`, month: 10, year: fyYear },
896
- Q4: { from: `${fyYear + 1}-01-01`, to: `${fyYear + 1}-03-31`, month: 1, year: fyYear + 1 }
897
- };
898
- const upper = q.toUpperCase();
899
- return ranges[upper] ?? ranges["Q1"];
900
- }
901
- function deliveryMethodLabel(method) {
902
- const map = {
903
- self_pickup: "Self Pickup",
904
- hand_delivery: "Hand Delivery",
905
- courier: "Courier",
906
- bus: "Bus",
907
- transport: "Transport",
908
- post: "Post"
909
- };
910
- return map[method] ?? method;
911
- }
912
-
913
- // src/commands/dashboard.ts
914
- import chalk3 from "chalk";
915
- function box(title, lines, width) {
916
- const innerW = width - 2;
917
- const titleStr = `\u2500 ${title} `;
918
- const border = "\u250C" + titleStr + "\u2500".repeat(Math.max(1, innerW - titleStr.length)) + "\u2510";
919
- const bottom = "\u2514" + "\u2500".repeat(innerW) + "\u2518";
920
- const padded = lines.map((l) => {
921
- const vis = l.length;
922
- const pad = Math.max(0, innerW - vis - 1);
923
- return "\u2502 " + l + " ".repeat(pad) + "\u2502";
924
- });
925
- return [border, ...padded, bottom];
926
- }
927
- function colorMoney(amount, good = true) {
928
- if (!hasColor()) return formatAmount(amount);
929
- const num = parseFloat(amount);
930
- if (isNaN(num) || num === 0) return chalk3.dim(formatAmount(amount));
931
- if (good) return chalk3.green(formatAmount(amount));
932
- return chalk3.red(formatAmount(amount));
933
- }
934
- async function dashboardCommand(opts) {
935
- const cfg = requireAuth();
936
- const client = new HisaaboClient(cfg);
937
- const from = fyStart();
938
- const to = todayISO();
939
- try {
940
- const summary = await client.dashboard.summary({ fromDate: from, toDate: to });
941
- if (opts.json) {
942
- outputJSON(summary);
220
+ // src/bin/registrars/auth.ts
221
+ function registerAuthCommands(program2) {
222
+ 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").option("--token <token>", "API key (hisaabo_key_...) for passwordless auth").action(async (opts) => {
223
+ let apiUrl = opts.apiUrl;
224
+ if (opts.token) {
225
+ if (!apiUrl) {
226
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
227
+ const ask = (q) => new Promise((res) => rl.question(q, res));
228
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
229
+ const u = await ask(" Server URL [http://localhost:3000]: ");
230
+ rl.close();
231
+ apiUrl = u.trim() || "http://localhost:3000";
232
+ }
233
+ await loginWithToken(apiUrl, opts.token);
943
234
  return;
944
235
  }
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}`);
236
+ let email = opts.email;
237
+ let password = opts.password;
238
+ if (!apiUrl || !email || !password) {
239
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
240
+ const ask = (q) => new Promise((res) => rl.question(q, res));
241
+ console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
242
+ if (!apiUrl) {
243
+ const u = await ask(" Server URL [http://localhost:3000]: ");
244
+ apiUrl = u.trim() || "http://localhost:3000";
245
+ }
246
+ if (!email) email = (await ask(" Email: ")).trim();
247
+ if (!password) {
248
+ password = (await ask(" Password: ")).trim();
249
+ }
250
+ rl.close();
251
+ console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
967
252
  }
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);
253
+ await login(apiUrl, email, password);
254
+ });
255
+ program2.command("logout").description("Log out and clear saved credentials").option("--all", "Invalidate all sessions across all devices").action(async (opts) => {
256
+ if (opts.all) {
257
+ const cfg = requireAuth();
258
+ const client = new HisaaboClient(cfg);
259
+ try {
260
+ await client.auth.logoutAll();
261
+ await logout();
262
+ success("Logged out from all sessions.");
263
+ } catch (e) {
264
+ if (e instanceof HisaaboApiError) {
265
+ if (e.hisaaboError.code === "unauthorized") {
266
+ await logout();
267
+ success("Logged out from all sessions.");
268
+ return;
269
+ }
270
+ }
271
+ fatalError(String(e instanceof Error ? e.message : e));
272
+ }
273
+ return;
995
274
  }
996
- fatalError(String(e instanceof Error ? e.message : e));
997
- }
275
+ await logout();
276
+ });
277
+ program2.command("whoami").description("Show current user and active business").option("--json", "JSON output").action(async (opts) => {
278
+ await whoami(!!opts.json);
279
+ });
280
+ const profile = program2.command("profile").description("Manage your profile");
281
+ profile.command("update-name <name>").description("Update your display name").action(async (name) => {
282
+ const cfg = requireAuth();
283
+ const client = new HisaaboClient(cfg);
284
+ try {
285
+ await client.auth.updateName({ name });
286
+ success(`Name updated to: ${name}`);
287
+ } catch (e) {
288
+ if (e instanceof HisaaboApiError) {
289
+ const err = e.hisaaboError;
290
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
291
+ if (err.code === "validation_failed") fatalError(String(err.fields?.["name"]?.[0] ?? "Validation failed."), EXIT.VALIDATION);
292
+ }
293
+ fatalError(String(e instanceof Error ? e.message : e));
294
+ }
295
+ });
296
+ program2.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
297
+ const cfg = requireAuth();
298
+ const client = new HisaaboClient(cfg);
299
+ try {
300
+ const businesses = await client.business.list();
301
+ if (opts.json) {
302
+ outputJSON(businesses);
303
+ return;
304
+ }
305
+ businesses.forEach((b, i) => {
306
+ const active = b.id === cfg.businessId ? " [active]" : "";
307
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
308
+ });
309
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
310
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
311
+ rl.close();
312
+ const idx = parseInt(answer.trim(), 10) - 1;
313
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
314
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
315
+ setConfig({ businessId: selected.id, businessName: selected.name });
316
+ success(`Switched to: ${selected.name}`);
317
+ } catch (e) {
318
+ if (e instanceof HisaaboApiError) {
319
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
320
+ }
321
+ fatalError(String(e instanceof Error ? e.message : e));
322
+ }
323
+ });
998
324
  }
999
325
 
1000
- // src/commands/invoice/list.ts
1001
- async function invoiceListCommand(opts) {
1002
- const cfg = requireAuth();
1003
- const client = new HisaaboClient(cfg);
1004
- let from = opts.from;
1005
- let to = opts.to;
1006
- if (opts.thisFy) {
1007
- from = fyStart();
1008
- to = todayISO();
1009
- } else if (opts.thisMonth) {
326
+ // src/bin/registrars/dashboard.ts
327
+ function registerDashboardCommands(program2) {
328
+ const dash = program2.command("dashboard").alias("dash").description("Business dashboard & analytics");
329
+ dash.command("summary").description("Financial summary overview (FY to date)").option("--json", "JSON output").action(async (opts) => {
330
+ const { dashboardCommand } = await import("./summary-BPNFC7I2.js");
331
+ await dashboardCommand({ json: opts.json });
332
+ });
333
+ 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) => {
334
+ const { dashboardSalesTrendCommand } = await import("./sales-trend-TICB3KGF.js");
335
+ await dashboardSalesTrendCommand(opts);
336
+ });
337
+ 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) => {
338
+ const { dashboardTopOutstandingCommand } = await import("./top-outstanding-MOGWJIQS.js");
339
+ await dashboardTopOutstandingCommand(opts);
340
+ });
341
+ 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) => {
342
+ const { dashboardTopCustomersCommand } = await import("./top-customers-WGGJWKCN.js");
343
+ await dashboardTopCustomersCommand({
344
+ limit: opts.limit,
345
+ from: opts.from,
346
+ to: opts.to,
347
+ thisMonth: opts.thisMonth,
348
+ thisFy: opts.thisFy,
349
+ json: opts.json,
350
+ format: opts.format
351
+ });
352
+ });
353
+ 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) => {
354
+ const { dashboardTopItemsCommand } = await import("./top-items-C7ZDDJMR.js");
355
+ await dashboardTopItemsCommand({
356
+ limit: opts.limit,
357
+ type: opts.type,
358
+ from: opts.from,
359
+ to: opts.to,
360
+ thisMonth: opts.thisMonth,
361
+ thisFy: opts.thisFy,
362
+ json: opts.json,
363
+ format: opts.format
364
+ });
365
+ });
366
+ 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) => {
367
+ const { dashboardExpensesCommand } = await import("./expenses-VZAOLYUW.js");
368
+ await dashboardExpensesCommand({
369
+ from: opts.from,
370
+ to: opts.to,
371
+ thisMonth: opts.thisMonth,
372
+ thisFy: opts.thisFy,
373
+ json: opts.json,
374
+ format: opts.format
375
+ });
376
+ });
377
+ expensesCmd.alias("expenses-by-category");
378
+ 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) => {
379
+ const { dashboardInvoiceBreakdownCommand } = await import("./invoice-breakdown-XEATXVMR.js");
380
+ await dashboardInvoiceBreakdownCommand({
381
+ from: opts.from,
382
+ to: opts.to,
383
+ thisMonth: opts.thisMonth,
384
+ thisFy: opts.thisFy,
385
+ json: opts.json
386
+ });
387
+ });
388
+ 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) => {
389
+ const { dashboardProfitLossCommand } = await import("./profit-loss-5RIEOBKP.js");
390
+ await dashboardProfitLossCommand({
391
+ from: opts.from,
392
+ to: opts.to,
393
+ thisMonth: opts.thisMonth,
394
+ thisFy: opts.thisFy,
395
+ json: opts.json
396
+ });
397
+ });
398
+ plCmd.alias("pl");
399
+ 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) => {
400
+ const { dashboardReceivablesAgingCommand } = await import("./receivables-aging-L6DIQCNE.js");
401
+ await dashboardReceivablesAgingCommand({ json: opts.json, format: opts.format });
402
+ });
403
+ 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) => {
404
+ const { dashboardPaymentModesCommand } = await import("./payment-modes-WI3AWSES.js");
405
+ await dashboardPaymentModesCommand({
406
+ from: opts.from,
407
+ to: opts.to,
408
+ thisMonth: opts.thisMonth,
409
+ thisFy: opts.thisFy,
410
+ json: opts.json,
411
+ format: opts.format
412
+ });
413
+ });
414
+ 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) => {
415
+ const { dashboardCollectionEfficiencyCommand } = await import("./collection-efficiency-WMKEGS6U.js");
416
+ await dashboardCollectionEfficiencyCommand({
417
+ from: opts.from,
418
+ to: opts.to,
419
+ thisMonth: opts.thisMonth,
420
+ thisFy: opts.thisFy,
421
+ json: opts.json,
422
+ format: opts.format
423
+ });
424
+ });
425
+ 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) => {
426
+ const { dashboardMonthlyComparisonCommand } = await import("./monthly-comparison-JEJ3TTY2.js");
427
+ await dashboardMonthlyComparisonCommand({ json: opts.json, format: opts.format });
428
+ });
429
+ }
430
+
431
+ // src/commands/invoice/list.ts
432
+ async function invoiceListCommand(opts) {
433
+ const cfg = requireAuth();
434
+ const client = new HisaaboClient(cfg);
435
+ let from = opts.from;
436
+ let to = opts.to;
437
+ if (opts.thisFy) {
438
+ from = fyStart();
439
+ to = todayISO();
440
+ } else if (opts.thisMonth) {
1010
441
  from = monthStart();
1011
442
  to = monthEnd();
1012
443
  } else if (opts.thisQuarter) {
@@ -1100,7 +531,7 @@ async function invoiceListCommand(opts) {
1100
531
  }
1101
532
 
1102
533
  // src/commands/invoice/get.ts
1103
- import chalk4 from "chalk";
534
+ import chalk from "chalk";
1104
535
  async function invoiceGetCommand(id, opts) {
1105
536
  const cfg = requireAuth();
1106
537
  const client = new HisaaboClient(cfg);
@@ -1129,12 +560,12 @@ async function invoiceGetCommand(id, opts) {
1129
560
  const w = Math.min(termWidth() - 2, 68);
1130
561
  const inner = w - 2;
1131
562
  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);
563
+ const statusBadge2 = formatStatus(inv.status);
564
+ const topPad = Math.max(1, inner - title.length - statusBadge2.replace(/\x1b\[[0-9;]*m/g, "").length);
1134
565
  process.stdout.write(`
1135
566
  \u250C${"\u2500".repeat(inner + 2)}\u2510
1136
567
  `);
1137
- process.stdout.write(`\u2502 ${hasColor() ? chalk4.bold(title) : title}${" ".repeat(topPad)}${statusBadge} \u2502
568
+ process.stdout.write(`\u2502 ${hasColor() ? chalk.bold(title) : title}${" ".repeat(topPad)}${statusBadge2} \u2502
1138
569
  `);
1139
570
  divider2();
1140
571
  line2(`Party: ${inv.partyName}`);
@@ -1149,13 +580,13 @@ async function invoiceGetCommand(id, opts) {
1149
580
  `);
1150
581
  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
582
  `);
1152
- inv.lineItems.forEach((item2, i) => {
583
+ inv.lineItems.forEach((item, i) => {
1153
584
  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);
585
+ const desc = item.description.slice(0, 18).padEnd(18);
586
+ const qty = item.quantity.padStart(5);
587
+ const rate = formatAmount(item.unitPrice).padStart(10);
588
+ const tax = `${item.taxPercent}%`.padStart(5);
589
+ const amt = formatAmount(item.amount).padStart(12);
1159
590
  process.stdout.write(`\u2502 ${idx} ${desc} ${qty} ${rate} ${tax} ${amt} \u2502
1160
591
  `);
1161
592
  });
@@ -1174,7 +605,7 @@ async function invoiceGetCommand(id, opts) {
1174
605
  line2(`Round Off:`, formatAmount(inv.roundOff).padStart(16));
1175
606
  process.stdout.write(`\u2502 ${"\u2500".repeat(inner - 2)} \u2502
1176
607
  `);
1177
- line2(`Total:`, (hasColor() ? chalk4.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
608
+ line2(`Total:`, (hasColor() ? chalk.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
1178
609
  line2(`Paid:`, formatAmount(inv.amountPaid).padStart(16));
1179
610
  line2(`Balance:`, formatAmount(inv.balanceDue).padStart(16));
1180
611
  if (inv.notes || inv.termsAndConditions) {
@@ -1200,7 +631,7 @@ async function invoiceGetCommand(id, opts) {
1200
631
  }
1201
632
 
1202
633
  // src/commands/invoice/create.ts
1203
- import * as readline from "readline";
634
+ import * as readline2 from "readline";
1204
635
  async function prompt(rl, question) {
1205
636
  return new Promise((resolve2) => rl.question(question, resolve2));
1206
637
  }
@@ -1215,7 +646,7 @@ async function invoiceCreateCommand(opts) {
1215
646
  let partyName = opts.party ?? "";
1216
647
  if (!partyId) {
1217
648
  if (!isNonInteractive) {
1218
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
649
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1219
650
  console.log(`
1220
651
  New ${invoiceType === "sale" ? "Sale Invoice" : "Purchase Bill"}`);
1221
652
  console.log(" " + "\u2500".repeat(40) + "\n");
@@ -1285,7 +716,7 @@ async function invoiceCreateCommand(opts) {
1285
716
  }
1286
717
  }
1287
718
  } else if (!isNonInteractive) {
1288
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
719
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1289
720
  console.log(" Add Line Items (empty description to finish):\n");
1290
721
  let itemNum = 1;
1291
722
  while (true) {
@@ -1336,13 +767,13 @@ async function invoiceCreateCommand(opts) {
1336
767
  } else {
1337
768
  fatalError("No items specified. Use --item flags.", EXIT.USAGE);
1338
769
  }
1339
- const subtotal = lineItems.reduce((s, item2) => {
1340
- const amt = parseFloat(item2.quantity) * parseFloat(item2.unitPrice);
770
+ const subtotal = lineItems.reduce((s, item) => {
771
+ const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
1341
772
  return s + amt;
1342
773
  }, 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;
774
+ const taxTotal = lineItems.reduce((s, item) => {
775
+ const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
776
+ const tax = parseFloat(item.taxPercent ?? "0") / 100;
1346
777
  return s + amt * tax;
1347
778
  }, 0);
1348
779
  let invoiceDate = todayISO();
@@ -1351,7 +782,7 @@ async function invoiceCreateCommand(opts) {
1351
782
  let notes = opts.notes;
1352
783
  let terms = opts.terms;
1353
784
  if (!isNonInteractive) {
1354
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
785
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
1355
786
  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
787
  console.log(` Subtotal: ${formatAmount(String(subtotal))}`);
1357
788
  console.log(` Tax: ${formatAmount(String(taxTotal))}`);
@@ -1375,7 +806,7 @@ async function invoiceCreateCommand(opts) {
1375
806
  process.exit(EXIT.SUCCESS);
1376
807
  }
1377
808
  }
1378
- const invoice2 = await client.invoice.create({
809
+ const invoice = await client.invoice.create({
1379
810
  partyId,
1380
811
  type: invoiceType,
1381
812
  invoiceDate,
@@ -1386,12 +817,12 @@ async function invoiceCreateCommand(opts) {
1386
817
  lineItems
1387
818
  });
1388
819
  if (opts.json) {
1389
- outputJSON(invoice2);
820
+ outputJSON(invoice);
1390
821
  return;
1391
822
  }
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}
823
+ success(`Created: ${invoice.invoiceNumber} for ${formatINR(invoice.totalAmount)}`);
824
+ console.log(` View: hisaabo invoice get ${invoice.invoiceNumber}`);
825
+ console.log(` PDF: hisaabo invoice pdf ${invoice.invoiceNumber}
1395
826
  `);
1396
827
  } catch (e) {
1397
828
  if (e instanceof HisaaboApiError) {
@@ -1490,14 +921,14 @@ async function invoicePdfCommand(id, opts) {
1490
921
  }
1491
922
 
1492
923
  // src/commands/invoice/delete.ts
1493
- import * as readline2 from "readline";
924
+ import * as readline3 from "readline";
1494
925
  async function invoiceDeleteCommand(id, opts) {
1495
926
  const cfg = requireAuth();
1496
927
  const client = new HisaaboClient(cfg);
1497
928
  try {
1498
929
  const inv = await client.invoice.get(id);
1499
930
  if (!opts.yes && process.stdin.isTTY) {
1500
- const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
931
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1501
932
  const answer = await new Promise((resolve2) => {
1502
933
  rl.question(` Delete ${inv.invoiceNumber} (${inv.partyName}, ${inv.totalAmount})? (y/N): `, resolve2);
1503
934
  });
@@ -1525,6 +956,58 @@ async function invoiceDeleteCommand(id, opts) {
1525
956
  }
1526
957
  }
1527
958
 
959
+ // src/bin/registrars/invoice.ts
960
+ function registerInvoiceCommands(program2) {
961
+ const invoice = program2.command("invoice").description("Invoice management");
962
+ 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) => {
963
+ await invoiceListCommand({
964
+ json: opts.json,
965
+ format: opts.format,
966
+ type: opts.type,
967
+ status: opts.status,
968
+ party: opts.party,
969
+ partyId: opts.partyId,
970
+ from: opts.from,
971
+ to: opts.to,
972
+ thisMonth: opts.thisMonth,
973
+ thisQuarter: opts.thisQuarter,
974
+ thisFy: opts.thisFy,
975
+ page: opts.page,
976
+ limit: opts.limit,
977
+ search: opts.search,
978
+ sortBy: opts.sortBy,
979
+ sortDir: opts.sortDir
980
+ });
981
+ });
982
+ invoice.command("get <id>").description("Get invoice details").option("--json", "JSON output").action(async (id, opts) => {
983
+ await invoiceGetCommand(id, { json: opts.json });
984
+ });
985
+ 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) => {
986
+ await invoiceCreateCommand({
987
+ json: opts.json,
988
+ party: opts.party,
989
+ partyId: opts.partyId,
990
+ type: opts.type,
991
+ items: opts.item,
992
+ qty: opts.qty,
993
+ rate: opts.rate,
994
+ delivery: opts.delivery,
995
+ notes: opts.notes,
996
+ terms: opts.terms,
997
+ yes: opts.yes
998
+ });
999
+ });
1000
+ invoice.command("status <id> <status>").description("Update invoice status").option("--json", "JSON output").action(async (id, status, opts) => {
1001
+ await invoiceStatusCommand(id, status, { json: opts.json });
1002
+ });
1003
+ 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) => {
1004
+ await invoicePdfCommand(id, { output: opts.output, open: opts.open });
1005
+ });
1006
+ invoice.command("delete <id>").description("Delete an invoice").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1007
+ await invoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
1008
+ });
1009
+ }
1010
+
1528
1011
  // src/commands/party/list.ts
1529
1012
  async function partyListCommand(opts) {
1530
1013
  const cfg = requireAuth();
@@ -1579,25 +1062,25 @@ async function partyGetCommand(id, opts) {
1579
1062
  const cfg = requireAuth();
1580
1063
  const client = new HisaaboClient(cfg);
1581
1064
  try {
1582
- const party2 = await client.party.get(id);
1065
+ const party = await client.party.get(id);
1583
1066
  if (opts.json) {
1584
- outputJSON(party2);
1067
+ outputJSON(party);
1585
1068
  return;
1586
1069
  }
1587
1070
  console.log(`
1588
- ${party2.name} (${party2.type.toUpperCase()})`);
1071
+ ${party.name} (${party.type.toUpperCase()})`);
1589
1072
  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)}`);
1073
+ if (party.phone) console.log(` Phone: ${party.phone}`);
1074
+ if (party.email) console.log(` Email: ${party.email}`);
1075
+ if (party.gstin) console.log(` GSTIN: ${party.gstin}`);
1076
+ if (party.pan) console.log(` PAN: ${party.pan}`);
1077
+ if (party.billingAddress) console.log(` Address: ${party.billingAddress}`);
1078
+ if (party.city) console.log(` City: ${party.city}`);
1079
+ if (party.state) console.log(` State: ${party.state}`);
1080
+ if (party.category) console.log(` Category: ${party.category}`);
1081
+ if (party.creditPeriodDays) console.log(` Credit Period: ${party.creditPeriodDays} days`);
1082
+ if (party.creditLimit && parseFloat(party.creditLimit) > 0) console.log(` Credit Limit: ${formatINR(party.creditLimit)}`);
1083
+ console.log(` Balance: ${formatINR(party.balance)}`);
1601
1084
  console.log();
1602
1085
  } catch (e) {
1603
1086
  if (e instanceof HisaaboApiError) {
@@ -1611,7 +1094,7 @@ async function partyGetCommand(id, opts) {
1611
1094
  }
1612
1095
 
1613
1096
  // src/commands/party/create.ts
1614
- import * as readline3 from "readline";
1097
+ import * as readline4 from "readline";
1615
1098
  async function prompt2(rl, q) {
1616
1099
  return new Promise((resolve2) => rl.question(q, resolve2));
1617
1100
  }
@@ -1627,7 +1110,7 @@ async function partyCreateCommand(opts) {
1627
1110
  let city = opts.city;
1628
1111
  let category = opts.category;
1629
1112
  if (!isNonInteractive) {
1630
- const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1113
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1631
1114
  console.log("\n New Party\n " + "\u2500".repeat(30) + "\n");
1632
1115
  if (!type) {
1633
1116
  const t = await prompt2(rl, " Type (customer/supplier) [customer]: ");
@@ -1657,13 +1140,13 @@ async function partyCreateCommand(opts) {
1657
1140
  if (!name) fatalError("--name is required", EXIT.USAGE);
1658
1141
  if (!type) type = "customer";
1659
1142
  try {
1660
- const party2 = await client.party.create({ type, name, phone, email, gstin, city, category });
1143
+ const party = await client.party.create({ type, name, phone, email, gstin, city, category });
1661
1144
  if (opts.json) {
1662
- outputJSON(party2);
1145
+ outputJSON(party);
1663
1146
  return;
1664
1147
  }
1665
- success(`Created: ${party2.name} (${party2.type})`);
1666
- console.log(` ID: ${party2.id}
1148
+ success(`Created: ${party.name} (${party.type})`);
1149
+ console.log(` ID: ${party.id}
1667
1150
  `);
1668
1151
  } catch (e) {
1669
1152
  if (e instanceof HisaaboApiError) {
@@ -1677,16 +1160,16 @@ async function partyCreateCommand(opts) {
1677
1160
  }
1678
1161
 
1679
1162
  // src/commands/party/delete.ts
1680
- import * as readline4 from "readline";
1163
+ import * as readline5 from "readline";
1681
1164
  async function partyDeleteCommand(id, opts) {
1682
1165
  const cfg = requireAuth();
1683
1166
  const client = new HisaaboClient(cfg);
1684
1167
  try {
1685
- const party2 = await client.party.get(id);
1168
+ const party = await client.party.get(id);
1686
1169
  if (!opts.yes && process.stdin.isTTY) {
1687
- const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1170
+ const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1688
1171
  const answer = await new Promise((resolve2) => {
1689
- rl.question(` Delete ${party2.name}? (y/N): `, resolve2);
1172
+ rl.question(` Delete ${party.name}? (y/N): `, resolve2);
1690
1173
  });
1691
1174
  rl.close();
1692
1175
  if (answer.trim().toLowerCase() !== "y") {
@@ -1699,7 +1182,7 @@ async function partyDeleteCommand(id, opts) {
1699
1182
  outputJSON(result);
1700
1183
  return;
1701
1184
  }
1702
- success(`Deleted: ${party2.name}`);
1185
+ success(`Deleted: ${party.name}`);
1703
1186
  } catch (e) {
1704
1187
  if (e instanceof HisaaboApiError) {
1705
1188
  const err = e.hisaaboError;
@@ -1757,8 +1240,36 @@ async function partyLedgerCommand(partyId, opts) {
1757
1240
  }
1758
1241
  }
1759
1242
 
1243
+ // src/bin/registrars/party.ts
1244
+ function registerPartyCommands(program2) {
1245
+ const party = program2.command("party").description("Party (customer/supplier) management");
1246
+ 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) => {
1247
+ await partyListCommand({
1248
+ json: opts.json,
1249
+ format: opts.format,
1250
+ type: opts.type,
1251
+ search: opts.search,
1252
+ category: opts.category,
1253
+ page: opts.page,
1254
+ limit: opts.limit
1255
+ });
1256
+ });
1257
+ party.command("get <id>").description("Get party details").option("--json", "JSON output").action(async (id, opts) => {
1258
+ await partyGetCommand(id, { json: opts.json });
1259
+ });
1260
+ 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) => {
1261
+ await partyCreateCommand(opts);
1262
+ });
1263
+ party.command("delete <id>").description("Delete a party").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1264
+ await partyDeleteCommand(id, { yes: opts.yes, json: opts.json });
1265
+ });
1266
+ 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) => {
1267
+ await partyLedgerCommand(partyId, opts);
1268
+ });
1269
+ }
1270
+
1760
1271
  // src/commands/item/list.ts
1761
- import chalk5 from "chalk";
1272
+ import chalk2 from "chalk";
1762
1273
  async function itemListCommand(opts) {
1763
1274
  const cfg = requireAuth();
1764
1275
  const client = new HisaaboClient(cfg);
@@ -1799,7 +1310,7 @@ async function itemListCommand(opts) {
1799
1310
  const low = row.lowStockAlert;
1800
1311
  const isLow = low && parseFloat(qty) <= parseFloat(low);
1801
1312
  const str = row.itemType === "service" ? "-" : isLow ? `${qty} !` : qty;
1802
- return isLow && hasColor() ? chalk5.red(str) : str;
1313
+ return isLow && hasColor() ? chalk2.red(str) : str;
1803
1314
  }
1804
1315
  },
1805
1316
  { key: "taxPercent", header: "Tax%", width: 6, format: (v) => `${v ?? 0}%` },
@@ -1826,7 +1337,7 @@ async function itemListCommand(opts) {
1826
1337
  }
1827
1338
 
1828
1339
  // src/commands/item/create.ts
1829
- import * as readline5 from "readline";
1340
+ import * as readline6 from "readline";
1830
1341
  async function prompt3(rl, q) {
1831
1342
  return new Promise((resolve2) => rl.question(q, resolve2));
1832
1343
  }
@@ -1844,7 +1355,7 @@ async function itemCreateCommand(opts) {
1844
1355
  let category = opts.category;
1845
1356
  let itemType = opts.type ?? "product";
1846
1357
  if (!isNonInteractive) {
1847
- const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1358
+ const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1848
1359
  console.log("\n New Item\n " + "\u2500".repeat(30) + "\n");
1849
1360
  if (!name) name = (await prompt3(rl, " Name: ")).trim();
1850
1361
  const typeStr = await prompt3(rl, " Type (product/service) [product]: ");
@@ -1869,7 +1380,7 @@ async function itemCreateCommand(opts) {
1869
1380
  }
1870
1381
  if (!name) fatalError("--name is required", EXIT.USAGE);
1871
1382
  try {
1872
- const item2 = await client.item.create({
1383
+ const item = await client.item.create({
1873
1384
  name,
1874
1385
  unit,
1875
1386
  salePrice,
@@ -1881,11 +1392,11 @@ async function itemCreateCommand(opts) {
1881
1392
  itemType
1882
1393
  });
1883
1394
  if (opts.json) {
1884
- outputJSON(item2);
1395
+ outputJSON(item);
1885
1396
  return;
1886
1397
  }
1887
- success(`Created: ${item2.name} (${item2.itemType})`);
1888
- console.log(` ID: ${item2.id}
1398
+ success(`Created: ${item.name} (${item.itemType})`);
1399
+ console.log(` ID: ${item.id}
1889
1400
  `);
1890
1401
  } catch (e) {
1891
1402
  if (e instanceof HisaaboApiError) {
@@ -1899,16 +1410,16 @@ async function itemCreateCommand(opts) {
1899
1410
  }
1900
1411
 
1901
1412
  // src/commands/item/delete.ts
1902
- import * as readline6 from "readline";
1413
+ import * as readline7 from "readline";
1903
1414
  async function itemDeleteCommand(id, opts) {
1904
1415
  const cfg = requireAuth();
1905
1416
  const client = new HisaaboClient(cfg);
1906
1417
  try {
1907
- const item2 = await client.item.get(id);
1418
+ const item = await client.item.get(id);
1908
1419
  if (!opts.yes && process.stdin.isTTY) {
1909
- const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1420
+ const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
1910
1421
  const answer = await new Promise((resolve2) => {
1911
- rl.question(` Delete ${item2.name}? (y/N): `, resolve2);
1422
+ rl.question(` Delete ${item.name}? (y/N): `, resolve2);
1912
1423
  });
1913
1424
  rl.close();
1914
1425
  if (answer.trim().toLowerCase() !== "y") {
@@ -1921,7 +1432,7 @@ async function itemDeleteCommand(id, opts) {
1921
1432
  outputJSON(result);
1922
1433
  return;
1923
1434
  }
1924
- success(`Deleted: ${item2.name}`);
1435
+ success(`Deleted: ${item.name}`);
1925
1436
  } catch (e) {
1926
1437
  if (e instanceof HisaaboApiError) {
1927
1438
  const err = e.hisaaboError;
@@ -1966,6 +1477,69 @@ async function itemStockCommand(id, adjustment, opts) {
1966
1477
  }
1967
1478
  }
1968
1479
 
1480
+ // src/bin/registrars/item.ts
1481
+ function registerItemCommands(program2) {
1482
+ const item = program2.command("item").description("Item / product management");
1483
+ 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) => {
1484
+ await itemListCommand({
1485
+ json: opts.json,
1486
+ format: opts.format,
1487
+ search: opts.search,
1488
+ category: opts.category,
1489
+ type: opts.type,
1490
+ lowStock: opts.lowStock,
1491
+ page: opts.page,
1492
+ limit: opts.limit
1493
+ });
1494
+ });
1495
+ item.command("get <id>").description("Get item details").option("--json", "JSON output").action(async (id, opts) => {
1496
+ const cfg = requireAuth();
1497
+ const client = new HisaaboClient(cfg);
1498
+ try {
1499
+ const it = await client.item.get(id);
1500
+ if (opts.json) {
1501
+ outputJSON(it);
1502
+ return;
1503
+ }
1504
+ console.log(`
1505
+ ${it.name} (${it.itemType})`);
1506
+ console.log(" " + "\u2500".repeat(40));
1507
+ if (it.sku) console.log(` SKU: ${it.sku}`);
1508
+ if (it.hsn) console.log(` HSN: ${it.hsn}`);
1509
+ console.log(` Unit: ${it.unit}`);
1510
+ if (it.salePrice) console.log(` Sale: \u20B9${it.salePrice}`);
1511
+ if (it.purchasePrice) console.log(` Purchase: \u20B9${it.purchasePrice}`);
1512
+ console.log(` Tax: ${it.taxPercent}%`);
1513
+ if (it.itemType === "product") console.log(` Stock: ${it.stockQuantity}`);
1514
+ console.log();
1515
+ } catch (e) {
1516
+ if (e instanceof HisaaboApiError && e.hisaaboError.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1517
+ fatalError(String(e instanceof Error ? e.message : e));
1518
+ }
1519
+ });
1520
+ 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) => {
1521
+ await itemCreateCommand({
1522
+ json: opts.json,
1523
+ name: opts.name,
1524
+ unit: opts.unit,
1525
+ salePrice: opts.salePrice,
1526
+ purchasePrice: opts.purchasePrice,
1527
+ taxPercent: opts.tax,
1528
+ stock: opts.stock,
1529
+ hsn: opts.hsn,
1530
+ category: opts.category,
1531
+ type: opts.type,
1532
+ yes: opts.yes
1533
+ });
1534
+ });
1535
+ item.command("delete <id>").description("Delete an item").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1536
+ await itemDeleteCommand(id, { yes: opts.yes, json: opts.json });
1537
+ });
1538
+ 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) => {
1539
+ await itemStockCommand(id, adjustment, { json: opts.json, reason: opts.reason });
1540
+ });
1541
+ }
1542
+
1969
1543
  // src/commands/payment/list.ts
1970
1544
  async function paymentListCommand(opts) {
1971
1545
  const cfg = requireAuth();
@@ -2013,7 +1587,7 @@ async function paymentListCommand(opts) {
2013
1587
  }
2014
1588
 
2015
1589
  // src/commands/payment/create.ts
2016
- import * as readline7 from "readline";
1590
+ import * as readline8 from "readline";
2017
1591
  async function prompt4(rl, q) {
2018
1592
  return new Promise((resolve2) => rl.question(q, resolve2));
2019
1593
  }
@@ -2029,7 +1603,7 @@ async function paymentCreateCommand(opts) {
2029
1603
  let notes = opts.notes;
2030
1604
  try {
2031
1605
  if (!isNonInteractive) {
2032
- const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
1606
+ const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
2033
1607
  console.log("\n Record Payment\n " + "\u2500".repeat(30) + "\n");
2034
1608
  if (!partyId) {
2035
1609
  const search = await prompt4(rl, " Select Party:\n > Search: ");
@@ -2092,7 +1666,7 @@ async function paymentCreateCommand(opts) {
2092
1666
  if (!partyId) fatalError("--party-id is required", EXIT.USAGE);
2093
1667
  if (!amount) fatalError("--amount is required", EXIT.USAGE);
2094
1668
  if (!mode) mode = "cash";
2095
- const payment2 = await client.payment.create({
1669
+ const payment = await client.payment.create({
2096
1670
  partyId,
2097
1671
  amount,
2098
1672
  mode,
@@ -2102,10 +1676,10 @@ async function paymentCreateCommand(opts) {
2102
1676
  invoiceId: opts.invoiceId
2103
1677
  });
2104
1678
  if (opts.json) {
2105
- outputJSON(payment2);
1679
+ outputJSON(payment);
2106
1680
  return;
2107
1681
  }
2108
- success(`Recorded: ${payment2.paymentNumber} for ${formatINR(payment2.amount)}`);
1682
+ success(`Recorded: ${payment.paymentNumber} for ${formatINR(payment.amount)}`);
2109
1683
  } catch (e) {
2110
1684
  if (e instanceof HisaaboApiError) {
2111
1685
  const err = e.hisaaboError;
@@ -2118,17 +1692,17 @@ async function paymentCreateCommand(opts) {
2118
1692
  }
2119
1693
 
2120
1694
  // src/commands/payment/delete.ts
2121
- import * as readline8 from "readline";
1695
+ import * as readline9 from "readline";
2122
1696
  async function paymentDeleteCommand(id, opts) {
2123
1697
  const cfg = requireAuth();
2124
1698
  const client = new HisaaboClient(cfg);
2125
1699
  try {
2126
- const payment2 = await client.payment.getById(id);
2127
- if (!payment2) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
1700
+ const payment = await client.payment.getById(id);
1701
+ if (!payment) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
2128
1702
  if (!opts.yes && process.stdin.isTTY) {
2129
- const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
1703
+ const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
2130
1704
  const answer = await new Promise((resolve2) => {
2131
- rl.question(` Delete ${payment2.paymentNumber} (${formatINR(payment2.amount)})? (y/N): `, resolve2);
1705
+ rl.question(` Delete ${payment.paymentNumber} (${formatINR(payment.amount)})? (y/N): `, resolve2);
2132
1706
  });
2133
1707
  rl.close();
2134
1708
  if (answer.trim().toLowerCase() !== "y") {
@@ -2141,7 +1715,7 @@ async function paymentDeleteCommand(id, opts) {
2141
1715
  outputJSON(result);
2142
1716
  return;
2143
1717
  }
2144
- success(`Deleted: ${payment2.paymentNumber}`);
1718
+ success(`Deleted: ${payment.paymentNumber}`);
2145
1719
  } catch (e) {
2146
1720
  if (e instanceof HisaaboApiError) {
2147
1721
  const err = e.hisaaboError;
@@ -2154,6 +1728,63 @@ async function paymentDeleteCommand(id, opts) {
2154
1728
  }
2155
1729
  }
2156
1730
 
1731
+ // src/bin/registrars/payment.ts
1732
+ function registerPaymentCommands(program2) {
1733
+ const payment = program2.command("payment").description("Payment recording");
1734
+ 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) => {
1735
+ await paymentListCommand(opts);
1736
+ });
1737
+ 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) => {
1738
+ await paymentCreateCommand({
1739
+ json: opts.json,
1740
+ partyId: opts.partyId,
1741
+ party: opts.party,
1742
+ amount: opts.amount,
1743
+ mode: opts.mode,
1744
+ invoiceId: opts.invoiceId,
1745
+ reference: opts.reference,
1746
+ date: opts.date,
1747
+ notes: opts.notes,
1748
+ yes: opts.yes
1749
+ });
1750
+ });
1751
+ payment.command("delete <id>").description("Delete a payment").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1752
+ await paymentDeleteCommand(id, { yes: opts.yes, json: opts.json });
1753
+ });
1754
+ payment.command("get <id>").description("Get payment details").option("--json", "JSON output").action(async (id, opts) => {
1755
+ const { paymentGetCommand } = await import("./get-6UYP6UVD.js");
1756
+ await paymentGetCommand(id, { json: opts.json });
1757
+ });
1758
+ 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) => {
1759
+ const { paymentUpdateCommand } = await import("./update-HIU4PANX.js");
1760
+ await paymentUpdateCommand(id, {
1761
+ json: opts.json,
1762
+ amount: opts.amount,
1763
+ mode: opts.mode,
1764
+ date: opts.date,
1765
+ reference: opts.reference,
1766
+ notes: opts.notes
1767
+ });
1768
+ });
1769
+ 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) => {
1770
+ const { paymentUnpaidInvoicesCommand } = await import("./unpaid-invoices-ZUPNMQJP.js");
1771
+ await paymentUnpaidInvoicesCommand(partyId, { json: opts.json, format: opts.format });
1772
+ });
1773
+ 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) => {
1774
+ const { paymentUntrackedCommand } = await import("./untracked-BCJEVDW4.js");
1775
+ await paymentUntrackedCommand({
1776
+ json: opts.json,
1777
+ format: opts.format,
1778
+ page: opts.page,
1779
+ limit: opts.limit
1780
+ });
1781
+ });
1782
+ 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) => {
1783
+ const { paymentDefaultAccountCommand } = await import("./default-account-SA56M66A.js");
1784
+ await paymentDefaultAccountCommand({ json: opts.json, partyId: opts.partyId });
1785
+ });
1786
+ }
1787
+
2157
1788
  // src/commands/expense/list.ts
2158
1789
  async function expenseListCommand(opts) {
2159
1790
  const cfg = requireAuth();
@@ -2207,7 +1838,7 @@ async function expenseCreateCommand(opts) {
2207
1838
  if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2208
1839
  const mode = opts.mode ?? "cash";
2209
1840
  try {
2210
- const expense2 = await client.expense.create({
1841
+ const expense = await client.expense.create({
2211
1842
  category: opts.category,
2212
1843
  amount: opts.amount,
2213
1844
  mode,
@@ -2216,10 +1847,10 @@ async function expenseCreateCommand(opts) {
2216
1847
  referenceNumber: opts.reference
2217
1848
  });
2218
1849
  if (opts.json) {
2219
- outputJSON(expense2);
1850
+ outputJSON(expense);
2220
1851
  return;
2221
1852
  }
2222
- success(`Created: ${expense2.category} ${formatINR(expense2.amount)}`);
1853
+ success(`Created: ${expense.category} ${formatINR(expense.amount)}`);
2223
1854
  } catch (e) {
2224
1855
  if (e instanceof HisaaboApiError) {
2225
1856
  const err = e.hisaaboError;
@@ -2232,14 +1863,14 @@ async function expenseCreateCommand(opts) {
2232
1863
  }
2233
1864
 
2234
1865
  // src/commands/expense/delete.ts
2235
- import * as readline9 from "readline";
1866
+ import * as readline10 from "readline";
2236
1867
  async function expenseDeleteCommand(id, opts) {
2237
1868
  const cfg = requireAuth();
2238
1869
  const client = new HisaaboClient(cfg);
2239
1870
  try {
2240
1871
  const _list = await client.expense.list({ page: 1, limit: 1 });
2241
1872
  if (!opts.yes && process.stdin.isTTY) {
2242
- const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
1873
+ const rl = readline10.createInterface({ input: process.stdin, output: process.stdout });
2243
1874
  const answer = await new Promise((resolve2) => {
2244
1875
  rl.question(` Delete expense ${id}? (y/N): `, resolve2);
2245
1876
  });
@@ -2267,6 +1898,44 @@ async function expenseDeleteCommand(id, opts) {
2267
1898
  }
2268
1899
  }
2269
1900
 
1901
+ // src/bin/registrars/expense.ts
1902
+ function registerExpenseCommands(program2) {
1903
+ const expense = program2.command("expense").description("Expense tracking");
1904
+ 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) => {
1905
+ await expenseListCommand(opts);
1906
+ });
1907
+ 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) => {
1908
+ await expenseCreateCommand({
1909
+ json: opts.json,
1910
+ category: opts.category,
1911
+ amount: opts.amount,
1912
+ mode: opts.mode,
1913
+ description: opts.description,
1914
+ date: opts.date,
1915
+ reference: opts.reference
1916
+ });
1917
+ });
1918
+ expense.command("delete <id>").description("Delete an expense").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
1919
+ await expenseDeleteCommand(id, { yes: opts.yes, json: opts.json });
1920
+ });
1921
+ 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) => {
1922
+ const { expenseUpdateCommand } = await import("./update-PVLAX7T3.js");
1923
+ await expenseUpdateCommand(id, {
1924
+ json: opts.json,
1925
+ amount: opts.amount,
1926
+ category: opts.category,
1927
+ date: opts.date,
1928
+ description: opts.description,
1929
+ paymentMode: opts.paymentMode,
1930
+ reference: opts.reference
1931
+ });
1932
+ });
1933
+ expense.command("categories").description("List all expense categories").option("--json", "JSON output").action(async (opts) => {
1934
+ const { expenseCategoriesCommand } = await import("./categories-P5VFWD5F.js");
1935
+ await expenseCategoriesCommand({ json: opts.json });
1936
+ });
1937
+ }
1938
+
2270
1939
  // src/commands/gst/index.ts
2271
1940
  import * as fs2 from "fs";
2272
1941
  function resolveMonthYear(opts) {
@@ -2285,9 +1954,9 @@ async function gstR1Command(opts) {
2285
1954
  const client = new HisaaboClient(cfg);
2286
1955
  const { month, year } = resolveMonthYear(opts);
2287
1956
  try {
2288
- const report2 = await client.gst.gstr1({ month, year });
1957
+ const report = await client.gst.gstr1({ month, year });
2289
1958
  if (opts.json) {
2290
- outputJSON(report2);
1959
+ outputJSON(report);
2291
1960
  return;
2292
1961
  }
2293
1962
  const quarterLabel = opts.quarter ? `${opts.quarter} ` : "";
@@ -2295,8 +1964,8 @@ async function gstR1Command(opts) {
2295
1964
  GSTR-1 Summary ${quarterLabel}FY ${year}-${String(year + 1).slice(2)}`);
2296
1965
  console.log(` ${"\u2550".repeat(60)}
2297
1966
  `);
2298
- if (report2.summary && typeof report2.summary === "object") {
2299
- const s = report2.summary;
1967
+ if (report.summary && typeof report.summary === "object") {
1968
+ const s = report.summary;
2300
1969
  if (s["totalTaxableValue"]) console.log(` Total Taxable: ${formatAmount(String(s["totalTaxableValue"]))}`);
2301
1970
  if (s["totalTax"]) console.log(` Total Tax: ${formatAmount(String(s["totalTax"]))}`);
2302
1971
  if (s["totalInvoices"]) console.log(` Total Invoices: ${s["totalInvoices"]}`);
@@ -2318,17 +1987,17 @@ async function gstR3bCommand(opts) {
2318
1987
  const client = new HisaaboClient(cfg);
2319
1988
  const { month, year } = resolveMonthYear(opts);
2320
1989
  try {
2321
- const report2 = await client.gst.gstr3b({ month, year });
1990
+ const report = await client.gst.gstr3b({ month, year });
2322
1991
  if (opts.json) {
2323
- outputJSON(report2);
1992
+ outputJSON(report);
2324
1993
  return;
2325
1994
  }
2326
1995
  console.log(`
2327
1996
  GSTR-3B Summary ${month}/${year}`);
2328
1997
  console.log(` ${"\u2550".repeat(60)}
2329
1998
  `);
2330
- if (report2.summary && typeof report2.summary === "object") {
2331
- const s = report2.summary;
1999
+ if (report.summary && typeof report.summary === "object") {
2000
+ const s = report.summary;
2332
2001
  Object.entries(s).forEach(([k, v]) => {
2333
2002
  console.log(` ${k.padEnd(28)}: ${String(v ?? "-")}`);
2334
2003
  });
@@ -2362,6 +2031,20 @@ async function gstR1CsvCommand(opts) {
2362
2031
  }
2363
2032
  }
2364
2033
 
2034
+ // src/bin/registrars/gst.ts
2035
+ function registerGstCommands(program2) {
2036
+ const gst = program2.command("gst").description("GST reports");
2037
+ 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) => {
2038
+ await gstR1Command({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
2039
+ });
2040
+ 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) => {
2041
+ await gstR3bCommand({ json: opts.json, quarter: opts.quarter, month: opts.month, year: opts.year });
2042
+ });
2043
+ 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) => {
2044
+ await gstR1CsvCommand({ quarter: opts.quarter, month: opts.month, year: opts.year, output: opts.output });
2045
+ });
2046
+ }
2047
+
2365
2048
  // src/commands/report/index.ts
2366
2049
  function resolveRange(opts) {
2367
2050
  if (opts.thisFy) return { from: fyStart(), to: todayISO() };
@@ -2542,41 +2225,40 @@ async function reportStockSummaryCommand(opts) {
2542
2225
  fatalError(String(e instanceof Error ? e.message : e));
2543
2226
  }
2544
2227
  }
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) {
2228
+ async function reportSalesRegisterCommand(opts) {
2552
2229
  const cfg = requireAuth();
2553
2230
  const client = new HisaaboClient(cfg);
2231
+ const { from, to } = resolveRange(opts);
2554
2232
  try {
2555
- const [accounts, summary] = await Promise.all([
2556
- client.bankAccount.list(),
2557
- client.bankAccount.summary()
2558
- ]);
2233
+ const result = await client.reports.salesRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
2559
2234
  if (opts.json) {
2560
- outputJSON({ accounts, summary });
2235
+ outputJSON(result);
2561
2236
  return;
2562
2237
  }
2563
- console.log("\n Bank Accounts\n");
2564
- console.log(` ${"\u2550".repeat(60)}
2238
+ console.log(`
2239
+ Sales Register ${from} \u2192 ${to}
2565
2240
  `);
2241
+ console.log(` ${"\u2550".repeat(80)}
2242
+ `);
2243
+ const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
2566
2244
  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" : "" }
2245
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2246
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2247
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2248
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2249
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2250
+ { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2251
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
2573
2252
  ];
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)}
2253
+ if (opts.format === "tsv") outputTSV(rows, cols);
2254
+ else if (opts.format === "csv") outputCSV(rows, cols);
2255
+ else outputTable(rows, cols);
2256
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2257
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2258
+ console.log(`
2259
+ Total: ${formatAmount(String(total)).padStart(14)}
2579
2260
  `);
2261
+ }
2580
2262
  } catch (e) {
2581
2263
  if (e instanceof HisaaboApiError) {
2582
2264
  const err = e.hisaaboError;
@@ -2586,24 +2268,40 @@ async function bankListCommand(opts) {
2586
2268
  fatalError(String(e instanceof Error ? e.message : e));
2587
2269
  }
2588
2270
  }
2589
- async function bankGetCommand(id, opts) {
2271
+ async function reportPurchaseRegisterCommand(opts) {
2590
2272
  const cfg = requireAuth();
2591
2273
  const client = new HisaaboClient(cfg);
2274
+ const { from, to } = resolveRange(opts);
2592
2275
  try {
2593
- const account = await client.bankAccount.get(id);
2594
- if (!account) fatalError(`Bank account not found: ${id}`, EXIT.NOT_FOUND);
2276
+ const result = await client.reports.purchaseRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
2595
2277
  if (opts.json) {
2596
- outputJSON(account);
2278
+ outputJSON(result);
2597
2279
  return;
2598
2280
  }
2599
2281
  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();
2282
+ Purchase Register ${from} \u2192 ${to}
2283
+ `);
2284
+ console.log(` ${"\u2550".repeat(80)}
2285
+ `);
2286
+ const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
2287
+ const cols = [
2288
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2289
+ { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2290
+ { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2291
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2292
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2293
+ { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2294
+ { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
2295
+ ];
2296
+ if (opts.format === "tsv") outputTSV(rows, cols);
2297
+ else if (opts.format === "csv") outputCSV(rows, cols);
2298
+ else outputTable(rows, cols);
2299
+ if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2300
+ const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2301
+ console.log(`
2302
+ Total: ${formatAmount(String(total)).padStart(14)}
2303
+ `);
2304
+ }
2607
2305
  } catch (e) {
2608
2306
  if (e instanceof HisaaboApiError) {
2609
2307
  const err = e.hisaaboError;
@@ -2613,67 +2311,353 @@ async function bankGetCommand(id, opts) {
2613
2311
  fatalError(String(e instanceof Error ? e.message : e));
2614
2312
  }
2615
2313
  }
2616
- async function bankCreateCommand(opts) {
2314
+ async function reportPartyStatementCommand(partyId, opts) {
2617
2315
  const cfg = requireAuth();
2618
2316
  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);
2317
+ const { from, to } = resolveRange(opts);
2642
2318
  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
- });
2319
+ const result = await client.reports.partyStatement({ partyId, fromDate: from, toDate: to });
2652
2320
  if (opts.json) {
2653
- outputJSON(account);
2321
+ outputJSON(result);
2654
2322
  return;
2655
2323
  }
2656
- success(`Created: ${account.accountName}`);
2657
- console.log(` ID: ${account.id}
2324
+ const res = result;
2325
+ const partyName = String(res["partyName"] ?? res["party"] ?? partyId);
2326
+ console.log(`
2327
+ Party Statement \u2014 ${partyName} ${from} \u2192 ${to}
2328
+ `);
2329
+ console.log(` ${"\u2550".repeat(75)}
2330
+ `);
2331
+ const openingBalance = String(res["openingBalance"] ?? "0");
2332
+ console.log(` Opening Balance: ${formatAmount(openingBalance).padStart(14)}
2333
+ `);
2334
+ const rows = Array.isArray(res["entries"]) ? res["entries"] : Array.isArray(res["rows"]) ? res["rows"] : [];
2335
+ const cols = [
2336
+ { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? v ?? "")) },
2337
+ { key: "type", header: "Type", width: 12, format: (v, r) => String(r.type ?? r.entryType ?? v ?? "-") },
2338
+ { key: "number", header: "Number", width: 14, format: (v, r) => String(r.number ?? r.invoiceNumber ?? v ?? "-") },
2339
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.debit ?? v ?? "0")) !== 0 ? formatAmount(String(r.debit ?? v)) : "-" },
2340
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.credit ?? v ?? "0")) !== 0 ? formatAmount(String(r.credit ?? v)) : "-" },
2341
+ { key: "balance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.balance ?? r.runningBalance ?? v ?? "0")) }
2342
+ ];
2343
+ if (opts.format === "tsv") outputTSV(rows, cols);
2344
+ else if (opts.format === "csv") outputCSV(rows, cols);
2345
+ else outputTable(rows, cols);
2346
+ if (opts.format !== "tsv" && opts.format !== "csv") {
2347
+ const closingBalance = String(res["closingBalance"] ?? res["balance"] ?? "0");
2348
+ console.log(`
2349
+ Closing Balance: ${formatAmount(closingBalance).padStart(14)}
2658
2350
  `);
2351
+ }
2659
2352
  } catch (e) {
2660
2353
  if (e instanceof HisaaboApiError) {
2661
2354
  const err = e.hisaaboError;
2662
2355
  if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2663
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2664
2356
  if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2665
2357
  }
2666
2358
  fatalError(String(e instanceof Error ? e.message : e));
2667
2359
  }
2668
2360
  }
2669
- async function bankTransferCommand(opts) {
2361
+ async function reportPaymentSummaryCommand(opts) {
2670
2362
  const cfg = requireAuth();
2671
2363
  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);
2364
+ const { from, to } = resolveRange(opts);
2675
2365
  try {
2676
- const result = await client.bankAccount.transfer({
2366
+ const result = await client.reports.paymentSummary({
2367
+ fromDate: from,
2368
+ toDate: to,
2369
+ type: opts.type ?? "both"
2370
+ });
2371
+ if (opts.json) {
2372
+ outputJSON(result);
2373
+ return;
2374
+ }
2375
+ const res = result;
2376
+ console.log(`
2377
+ Payment Summary ${from} \u2192 ${to}
2378
+ `);
2379
+ console.log(" " + "\u2550".repeat(60) + "\n");
2380
+ const received = String(res["totalReceived"] ?? res["received"] ?? "0");
2381
+ const made = String(res["totalMade"] ?? res["made"] ?? "0");
2382
+ const net = String(res["net"] ?? res["netCash"] ?? "0");
2383
+ console.log(` Total Received: ${formatAmount(received).padStart(14)}`);
2384
+ console.log(` Total Made: ${formatAmount(made).padStart(14)}`);
2385
+ console.log(` Net: ${formatAmount(net).padStart(14)}`);
2386
+ const breakdown = res["breakdown"] ?? res["byMode"] ?? res["modes"];
2387
+ if (breakdown && Array.isArray(breakdown)) {
2388
+ console.log(`
2389
+ By Payment Mode:
2390
+ `);
2391
+ breakdown.forEach((row) => {
2392
+ const mode = String(row["mode"] ?? row["paymentMode"] ?? "-").padEnd(18);
2393
+ const amount = formatAmount(String(row["amount"] ?? row["total"] ?? "0")).padStart(14);
2394
+ console.log(` ${mode} ${amount}`);
2395
+ });
2396
+ }
2397
+ console.log();
2398
+ } catch (e) {
2399
+ if (e instanceof HisaaboApiError) {
2400
+ const err = e.hisaaboError;
2401
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2402
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2403
+ }
2404
+ fatalError(String(e instanceof Error ? e.message : e));
2405
+ }
2406
+ }
2407
+ async function reportCashFlowCommand(opts) {
2408
+ const cfg = requireAuth();
2409
+ const client = new HisaaboClient(cfg);
2410
+ try {
2411
+ const result = await client.reports.cashFlowForecast();
2412
+ if (opts.json) {
2413
+ outputJSON(result);
2414
+ return;
2415
+ }
2416
+ const res = result;
2417
+ console.log("\n Cash Flow Forecast\n");
2418
+ console.log(" " + "\u2550".repeat(60) + "\n");
2419
+ const currentBalance = String(res["currentBalance"] ?? res["balance"] ?? "0");
2420
+ const avgDailyExpenses = String(res["avgDailyExpenses"] ?? res["dailyBurn"] ?? "0");
2421
+ console.log(` Current Balance: ${formatAmount(currentBalance).padStart(14)}`);
2422
+ console.log(` Avg Daily Expenses: ${formatAmount(avgDailyExpenses).padStart(14)}`);
2423
+ const forecasts = res["forecasts"] ?? res["forecast"];
2424
+ if (forecasts && Array.isArray(forecasts)) {
2425
+ console.log(`
2426
+ Forecast:
2427
+ `);
2428
+ forecasts.forEach((f) => {
2429
+ const days = String(f["days"] ?? f["day"] ?? "-");
2430
+ const balance = formatAmount(String(f["balance"] ?? f["amount"] ?? "0")).padStart(14);
2431
+ console.log(` ${`${days}d`.padEnd(6)} ${balance}`);
2432
+ });
2433
+ } else {
2434
+ const current = parseFloat(currentBalance);
2435
+ const daily = parseFloat(avgDailyExpenses);
2436
+ if (!isNaN(current) && !isNaN(daily)) {
2437
+ console.log(`
2438
+ Forecast:
2439
+ `);
2440
+ for (const days of [7, 14, 30]) {
2441
+ const projected = current - daily * days;
2442
+ console.log(` ${`${days}d`.padEnd(6)} ${formatAmount(String(projected)).padStart(14)}`);
2443
+ }
2444
+ }
2445
+ }
2446
+ console.log();
2447
+ } catch (e) {
2448
+ if (e instanceof HisaaboApiError) {
2449
+ const err = e.hisaaboError;
2450
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2451
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2452
+ }
2453
+ fatalError(String(e instanceof Error ? e.message : e));
2454
+ }
2455
+ }
2456
+ async function reportCollectionEfficiencyCommand(opts) {
2457
+ const cfg = requireAuth();
2458
+ const client = new HisaaboClient(cfg);
2459
+ const { from, to } = resolveRange(opts);
2460
+ try {
2461
+ const result = await client.reports.collectionEfficiency({ fromDate: from, toDate: to });
2462
+ if (opts.json) {
2463
+ outputJSON(result);
2464
+ return;
2465
+ }
2466
+ const res = result;
2467
+ console.log(`
2468
+ Collection Efficiency ${from} \u2192 ${to}
2469
+ `);
2470
+ console.log(" " + "\u2550".repeat(60) + "\n");
2471
+ const rate = String(res["collectionRate"] ?? res["rate"] ?? "0");
2472
+ const dso = String(res["dso"] ?? res["daysSalesOutstanding"] ?? "-");
2473
+ const paidOnTime = String(res["paidOnTime"] ?? res["onTimeCount"] ?? "-");
2474
+ const totalInvoiced = String(res["totalInvoiced"] ?? res["invoiced"] ?? "-");
2475
+ console.log(` Collection Rate: ${parseFloat(rate).toFixed(1).padStart(8)}%`);
2476
+ console.log(` DSO (Days): ${dso.padStart(8)}`);
2477
+ console.log(` Paid On Time: ${paidOnTime.padStart(8)}`);
2478
+ if (totalInvoiced !== "-") {
2479
+ console.log(` Total Invoiced: ${formatAmount(totalInvoiced).padStart(14)}`);
2480
+ }
2481
+ console.log();
2482
+ } catch (e) {
2483
+ if (e instanceof HisaaboApiError) {
2484
+ const err = e.hisaaboError;
2485
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2486
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2487
+ }
2488
+ fatalError(String(e instanceof Error ? e.message : e));
2489
+ }
2490
+ }
2491
+
2492
+ // src/bin/registrars/report.ts
2493
+ function registerReportCommands(program2) {
2494
+ const report = program2.command("report").description("Business reports");
2495
+ 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) => {
2496
+ await reportDaybookCommand(opts);
2497
+ });
2498
+ report.command("outstanding").description("Outstanding receivables and payables").option("--json", "JSON output").option("--type <type>", "receivable, payable, or both").action(async (opts) => {
2499
+ await reportOutstandingCommand({ json: opts.json, type: opts.type });
2500
+ });
2501
+ 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) => {
2502
+ await reportTaxSummaryCommand(opts);
2503
+ });
2504
+ 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) => {
2505
+ await reportItemSalesCommand(opts);
2506
+ });
2507
+ report.command("stock").description("Stock summary report").option("--json", "JSON output").option("--category <cat>", "Filter by category").action(async (opts) => {
2508
+ await reportStockSummaryCommand({ json: opts.json, category: opts.category });
2509
+ });
2510
+ 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) => {
2511
+ await reportSalesRegisterCommand(opts);
2512
+ });
2513
+ 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) => {
2514
+ await reportPurchaseRegisterCommand(opts);
2515
+ });
2516
+ 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) => {
2517
+ await reportPartyStatementCommand(partyId, opts);
2518
+ });
2519
+ 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) => {
2520
+ await reportPaymentSummaryCommand(opts);
2521
+ });
2522
+ report.command("cash-flow").description("Cash flow forecast").option("--json", "JSON output").action(async (opts) => {
2523
+ await reportCashFlowCommand({ json: opts.json });
2524
+ });
2525
+ 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) => {
2526
+ await reportCollectionEfficiencyCommand(opts);
2527
+ });
2528
+ }
2529
+
2530
+ // src/commands/bank/index.ts
2531
+ import * as readline11 from "readline";
2532
+ async function prompt5(rl, q) {
2533
+ return new Promise((resolve2) => rl.question(q, resolve2));
2534
+ }
2535
+ async function bankListCommand(opts) {
2536
+ const cfg = requireAuth();
2537
+ const client = new HisaaboClient(cfg);
2538
+ try {
2539
+ const [accounts, summary] = await Promise.all([
2540
+ client.bankAccount.list(),
2541
+ client.bankAccount.summary()
2542
+ ]);
2543
+ if (opts.json) {
2544
+ outputJSON({ accounts, summary });
2545
+ return;
2546
+ }
2547
+ console.log("\n Bank Accounts\n");
2548
+ console.log(` ${"\u2550".repeat(60)}
2549
+ `);
2550
+ const cols = [
2551
+ { key: "accountName", header: "Name", width: 22 },
2552
+ { key: "bankName", header: "Bank", width: 16, format: (v) => String(v ?? "-") },
2553
+ { key: "accountType", header: "Type", width: 10 },
2554
+ { key: "accountNumber", header: "Account #", width: 16, format: (v) => String(v ?? "-") },
2555
+ { key: "currentBalance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
2556
+ { key: "isDefault", header: "Default", width: 8, format: (v) => v ? "Yes" : "" }
2557
+ ];
2558
+ outputTable(accounts, cols);
2559
+ console.log(`
2560
+ Total Balance: ${formatINR(summary.totalBalance)}`);
2561
+ console.log(` Cash in Hand: ${formatINR(summary.cashInHand)}`);
2562
+ console.log(` Bank Balance: ${formatINR(summary.bankBalance)}
2563
+ `);
2564
+ } catch (e) {
2565
+ if (e instanceof HisaaboApiError) {
2566
+ const err = e.hisaaboError;
2567
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2568
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2569
+ }
2570
+ fatalError(String(e instanceof Error ? e.message : e));
2571
+ }
2572
+ }
2573
+ async function bankGetCommand(id, opts) {
2574
+ const cfg = requireAuth();
2575
+ const client = new HisaaboClient(cfg);
2576
+ try {
2577
+ const account = await client.bankAccount.get(id);
2578
+ if (!account) fatalError(`Bank account not found: ${id}`, EXIT.NOT_FOUND);
2579
+ if (opts.json) {
2580
+ outputJSON(account);
2581
+ return;
2582
+ }
2583
+ console.log(`
2584
+ ${account.accountName} (${account.accountType})`);
2585
+ console.log(" " + "\u2500".repeat(45));
2586
+ if (account.bankName) console.log(` Bank: ${account.bankName}`);
2587
+ if (account.accountNumber) console.log(` Account: ${account.accountNumber}`);
2588
+ if (account.ifsc) console.log(` IFSC: ${account.ifsc}`);
2589
+ console.log(` Balance: ${formatINR(account.currentBalance)}`);
2590
+ console.log();
2591
+ } catch (e) {
2592
+ if (e instanceof HisaaboApiError) {
2593
+ const err = e.hisaaboError;
2594
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2595
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2596
+ }
2597
+ fatalError(String(e instanceof Error ? e.message : e));
2598
+ }
2599
+ }
2600
+ async function bankCreateCommand(opts) {
2601
+ const cfg = requireAuth();
2602
+ const client = new HisaaboClient(cfg);
2603
+ const isNonInteractive = !process.stdin.isTTY || opts.yes;
2604
+ let name = opts.name;
2605
+ let accountType = opts.type ?? "current";
2606
+ let bankName = opts.bank;
2607
+ let accountNumber = opts.accountNumber;
2608
+ let ifsc = opts.ifsc;
2609
+ let openingBalance = opts.openingBalance;
2610
+ if (!isNonInteractive) {
2611
+ const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
2612
+ if (!name) name = (await prompt5(rl, " Account Name: ")).trim();
2613
+ const typeStr = await prompt5(rl, " Type (savings/current/cash/credit/other) [current]: ");
2614
+ accountType = typeStr.trim() || "current";
2615
+ const bankStr = await prompt5(rl, " Bank Name: ");
2616
+ if (bankStr.trim()) bankName = bankStr.trim();
2617
+ const numStr = await prompt5(rl, " Account Number: ");
2618
+ if (numStr.trim()) accountNumber = numStr.trim();
2619
+ const ifscStr = await prompt5(rl, " IFSC: ");
2620
+ if (ifscStr.trim()) ifsc = ifscStr.trim();
2621
+ const balStr = await prompt5(rl, " Opening Balance [0]: ");
2622
+ openingBalance = balStr.trim() || "0";
2623
+ rl.close();
2624
+ }
2625
+ if (!name) fatalError("--name is required", EXIT.USAGE);
2626
+ try {
2627
+ const account = await client.bankAccount.create({
2628
+ accountName: name,
2629
+ accountType,
2630
+ bankName,
2631
+ accountNumber,
2632
+ ifsc,
2633
+ openingBalance,
2634
+ isDefault: opts.default
2635
+ });
2636
+ if (opts.json) {
2637
+ outputJSON(account);
2638
+ return;
2639
+ }
2640
+ success(`Created: ${account.accountName}`);
2641
+ console.log(` ID: ${account.id}
2642
+ `);
2643
+ } catch (e) {
2644
+ if (e instanceof HisaaboApiError) {
2645
+ const err = e.hisaaboError;
2646
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2647
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2648
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2649
+ }
2650
+ fatalError(String(e instanceof Error ? e.message : e));
2651
+ }
2652
+ }
2653
+ async function bankTransferCommand(opts) {
2654
+ const cfg = requireAuth();
2655
+ const client = new HisaaboClient(cfg);
2656
+ if (!opts.from) fatalError("--from account ID is required", EXIT.USAGE);
2657
+ if (!opts.to) fatalError("--to account ID is required", EXIT.USAGE);
2658
+ if (!opts.amount) fatalError("--amount is required", EXIT.USAGE);
2659
+ try {
2660
+ const result = await client.bankAccount.transfer({
2677
2661
  fromAccountId: opts.from,
2678
2662
  toAccountId: opts.to,
2679
2663
  amount: opts.amount,
@@ -2734,6 +2718,49 @@ async function bankTransactionsCommand(accountId, opts) {
2734
2718
  }
2735
2719
  }
2736
2720
 
2721
+ // src/bin/registrars/bank.ts
2722
+ function registerBankCommands(program2) {
2723
+ const bank = program2.command("bank").description("Bank account management");
2724
+ bank.command("list").description("List bank accounts with balances").option("--json", "JSON output").action(async (opts) => {
2725
+ await bankListCommand({ json: opts.json });
2726
+ });
2727
+ bank.command("get <id>").description("Get bank account details").option("--json", "JSON output").action(async (id, opts) => {
2728
+ await bankGetCommand(id, { json: opts.json });
2729
+ });
2730
+ 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) => {
2731
+ await bankCreateCommand({
2732
+ json: opts.json,
2733
+ name: opts.name,
2734
+ type: opts.type,
2735
+ bank: opts.bank,
2736
+ accountNumber: opts.accountNumber,
2737
+ ifsc: opts.ifsc,
2738
+ openingBalance: opts.openingBalance,
2739
+ default: opts.default,
2740
+ yes: opts.yes
2741
+ });
2742
+ });
2743
+ 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) => {
2744
+ await bankTransferCommand({
2745
+ json: opts.json,
2746
+ from: opts.from,
2747
+ to: opts.to,
2748
+ amount: opts.amount,
2749
+ description: opts.description,
2750
+ date: opts.date
2751
+ });
2752
+ });
2753
+ 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) => {
2754
+ await bankTransactionsCommand(accountId, {
2755
+ json: opts.json,
2756
+ from: opts.from,
2757
+ to: opts.to,
2758
+ page: opts.page,
2759
+ limit: opts.limit
2760
+ });
2761
+ });
2762
+ }
2763
+
2737
2764
  // src/commands/shipment/index.ts
2738
2765
  async function shipmentListCommand(opts) {
2739
2766
  const cfg = requireAuth();
@@ -2777,24 +2804,24 @@ async function shipmentGetCommand(id, opts) {
2777
2804
  const cfg = requireAuth();
2778
2805
  const client = new HisaaboClient(cfg);
2779
2806
  try {
2780
- const shipment2 = await client.shipment.get(id);
2781
- if (!shipment2) fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2807
+ const shipment = await client.shipment.get(id);
2808
+ if (!shipment) fatalError(`Shipment not found: ${id}`, EXIT.NOT_FOUND);
2782
2809
  if (opts.json) {
2783
- outputJSON(shipment2);
2810
+ outputJSON(shipment);
2784
2811
  return;
2785
2812
  }
2786
2813
  console.log(`
2787
2814
  Shipment ${id}`);
2788
2815
  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)}`);
2816
+ if (shipment.invoiceNumber) console.log(` Invoice: ${shipment.invoiceNumber}`);
2817
+ if (shipment.partyName) console.log(` Party: ${shipment.partyName}`);
2818
+ if (shipment.carrier) console.log(` Carrier: ${shipment.carrier}`);
2819
+ if (shipment.trackingNumber) console.log(` Tracking: ${shipment.trackingNumber}`);
2820
+ if (shipment.trackingUrl) console.log(` URL: ${shipment.trackingUrl}`);
2821
+ console.log(` Status: ${formatStatus(shipment.status)}`);
2822
+ if (shipment.shipmentDate) console.log(` Shipped: ${formatDate(shipment.shipmentDate)}`);
2823
+ if (shipment.estimatedDelivery) console.log(` Est. Del: ${formatDate(shipment.estimatedDelivery)}`);
2824
+ if (shipment.actualDelivery) console.log(` Delivered:${formatDate(shipment.actualDelivery)}`);
2798
2825
  console.log();
2799
2826
  } catch (e) {
2800
2827
  if (e instanceof HisaaboApiError) {
@@ -2809,7 +2836,7 @@ async function shipmentCreateCommand(opts) {
2809
2836
  const cfg = requireAuth();
2810
2837
  const client = new HisaaboClient(cfg);
2811
2838
  try {
2812
- const shipment2 = await client.shipment.create({
2839
+ const shipment = await client.shipment.create({
2813
2840
  invoiceId: opts.invoiceId,
2814
2841
  partyId: opts.partyId,
2815
2842
  carrier: opts.carrier,
@@ -2818,11 +2845,11 @@ async function shipmentCreateCommand(opts) {
2818
2845
  shipmentDate: opts.date
2819
2846
  });
2820
2847
  if (opts.json) {
2821
- outputJSON(shipment2);
2848
+ outputJSON(shipment);
2822
2849
  return;
2823
2850
  }
2824
- success(`Shipment created: ${shipment2.id}`);
2825
- if (shipment2.trackingNumber) console.log(` Tracking: ${shipment2.trackingNumber}`);
2851
+ success(`Shipment created: ${shipment.id}`);
2852
+ if (shipment.trackingNumber) console.log(` Tracking: ${shipment.trackingNumber}`);
2826
2853
  console.log();
2827
2854
  } catch (e) {
2828
2855
  if (e instanceof HisaaboApiError) {
@@ -2838,17 +2865,17 @@ async function shipmentUpdateCommand(id, opts) {
2838
2865
  const cfg = requireAuth();
2839
2866
  const client = new HisaaboClient(cfg);
2840
2867
  try {
2841
- const shipment2 = await client.shipment.update({
2868
+ const shipment = await client.shipment.update({
2842
2869
  id,
2843
2870
  status: opts.status,
2844
2871
  trackingNumber: opts.tracking,
2845
2872
  carrier: opts.carrier
2846
2873
  });
2847
2874
  if (opts.json) {
2848
- outputJSON(shipment2);
2875
+ outputJSON(shipment);
2849
2876
  return;
2850
2877
  }
2851
- success(`Shipment updated: ${formatStatus(shipment2.status)}`);
2878
+ success(`Shipment updated: ${formatStatus(shipment.status)}`);
2852
2879
  } catch (e) {
2853
2880
  if (e instanceof HisaaboApiError) {
2854
2881
  const err = e.hisaaboError;
@@ -2860,6 +2887,42 @@ async function shipmentUpdateCommand(id, opts) {
2860
2887
  }
2861
2888
  }
2862
2889
 
2890
+ // src/bin/registrars/shipment.ts
2891
+ function registerShipmentCommands(program2) {
2892
+ const shipment = program2.command("shipment").description("Shipment tracking");
2893
+ 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) => {
2894
+ await shipmentListCommand({
2895
+ json: opts.json,
2896
+ status: opts.status,
2897
+ invoiceId: opts.invoiceId,
2898
+ page: opts.page,
2899
+ limit: opts.limit
2900
+ });
2901
+ });
2902
+ shipment.command("get <id>").description("Get shipment details").option("--json", "JSON output").action(async (id, opts) => {
2903
+ await shipmentGetCommand(id, { json: opts.json });
2904
+ });
2905
+ 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) => {
2906
+ await shipmentCreateCommand({
2907
+ json: opts.json,
2908
+ invoiceId: opts.invoiceId,
2909
+ partyId: opts.partyId,
2910
+ carrier: opts.carrier,
2911
+ tracking: opts.tracking,
2912
+ mode: opts.mode,
2913
+ date: opts.date
2914
+ });
2915
+ });
2916
+ 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) => {
2917
+ await shipmentUpdateCommand(id, {
2918
+ json: opts.json,
2919
+ status: opts.status,
2920
+ tracking: opts.tracking,
2921
+ carrier: opts.carrier
2922
+ });
2923
+ });
2924
+ }
2925
+
2863
2926
  // src/commands/target/index.ts
2864
2927
  async function targetListCommand(opts) {
2865
2928
  const cfg = requireAuth();
@@ -2924,7 +2987,7 @@ async function targetCreateCommand(opts) {
2924
2987
  if (!opts.value) fatalError("--value is required", EXIT.USAGE);
2925
2988
  if (!opts.startDate) fatalError("--start-date is required", EXIT.USAGE);
2926
2989
  try {
2927
- const target2 = await client.target.create({
2990
+ const target = await client.target.create({
2928
2991
  type: opts.type,
2929
2992
  period: opts.period ?? "monthly",
2930
2993
  targetValue: opts.value,
@@ -2933,10 +2996,10 @@ async function targetCreateCommand(opts) {
2933
2996
  notes: opts.notes
2934
2997
  });
2935
2998
  if (opts.json) {
2936
- outputJSON(target2);
2999
+ outputJSON(target);
2937
3000
  return;
2938
3001
  }
2939
- success(`Target created: ${target2.type} ${target2.period} ${formatAmount(target2.targetValue)}`);
3002
+ success(`Target created: ${target.type} ${target.period} ${formatAmount(target.targetValue)}`);
2940
3003
  } catch (e) {
2941
3004
  if (e instanceof HisaaboApiError) {
2942
3005
  const err = e.hisaaboError;
@@ -2948,62 +3011,89 @@ async function targetCreateCommand(opts) {
2948
3011
  }
2949
3012
  }
2950
3013
 
2951
- // src/commands/store/index.ts
2952
- async function storeSettingsCommand(opts) {
2953
- const cfg = requireAuth();
2954
- const client = new HisaaboClient(cfg);
2955
- try {
2956
- const settings = await client.store.getSettings();
2957
- if (opts.json) {
2958
- outputJSON(settings);
2959
- return;
2960
- }
2961
- console.log("\n Store Settings\n " + "\u2500".repeat(35));
2962
- console.log(` Enabled: ${settings.storeEnabled ? "Yes" : "No"}`);
2963
- if (settings.storeSlug) console.log(` Slug: ${settings.storeSlug}`);
2964
- if (settings.storeName) console.log(` Name: ${settings.storeName}`);
2965
- if (settings.storeDescription) console.log(` About: ${settings.storeDescription}`);
2966
- console.log();
2967
- } catch (e) {
2968
- if (e instanceof HisaaboApiError) {
2969
- const err = e.hisaaboError;
2970
- if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2971
- if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2972
- }
2973
- fatalError(String(e instanceof Error ? e.message : e));
2974
- }
3014
+ // src/bin/registrars/target.ts
3015
+ function registerTargetCommands(program2) {
3016
+ const target = program2.command("target").description("Sales target management");
3017
+ target.command("list").description("List sales targets").option("--json", "JSON output").action(async (opts) => {
3018
+ await targetListCommand({ json: opts.json });
3019
+ });
3020
+ target.command("my").description("Show my target progress").option("--json", "JSON output").action(async (opts) => {
3021
+ await targetMyCommand({ json: opts.json });
3022
+ });
3023
+ 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) => {
3024
+ await targetCreateCommand({
3025
+ json: opts.json,
3026
+ type: opts.type,
3027
+ period: opts.period,
3028
+ value: opts.value,
3029
+ startDate: opts.startDate,
3030
+ endDate: opts.endDate,
3031
+ notes: opts.notes
3032
+ });
3033
+ });
2975
3034
  }
2976
- async function storeOrdersCommand(opts) {
2977
- const cfg = requireAuth();
2978
- const client = new HisaaboClient(cfg);
2979
- const page = opts.page ?? 1;
2980
- const limit = opts.limit ?? 20;
2981
- try {
2982
- const result = await client.store.listOrders({ status: opts.status ?? null, page, limit });
2983
- if (opts.json) {
2984
- outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
2985
- return;
2986
- }
2987
- console.log(`
2988
- Store Orders ${result.total} total
2989
- `);
2990
- const cols = [
2991
- { key: "orderNumber", header: "#", width: 12 },
2992
- { key: "customerName", header: "Customer", width: 20 },
2993
- { key: "createdAt", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
2994
- { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
2995
- { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
2996
- ];
2997
- outputTable(result.data, cols);
2998
- paginationFooter(result.page, result.limit, result.total);
2999
- } catch (e) {
3000
- if (e instanceof HisaaboApiError) {
3001
- const err = e.hisaaboError;
3002
- if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3003
- if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3004
- }
3005
- fatalError(String(e instanceof Error ? e.message : e));
3006
- }
3035
+
3036
+ // src/bin/registrars/store.ts
3037
+ function registerStoreCommands(program2) {
3038
+ const store = program2.command("store").description("Online store management");
3039
+ store.command("settings").description("Show store settings").option("--json", "JSON output").action(async (opts) => {
3040
+ const { storeSettingsCommand } = await import("./store-UQ2DDQ5I.js");
3041
+ await storeSettingsCommand({ json: opts.json });
3042
+ });
3043
+ 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) => {
3044
+ const { storeUpdateSettingsCommand } = await import("./update-settings-XPC6L5WM.js");
3045
+ await storeUpdateSettingsCommand({
3046
+ slug: opts.slug,
3047
+ tagline: opts.tagline,
3048
+ enabled: opts.enabled,
3049
+ json: opts.json
3050
+ });
3051
+ });
3052
+ 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) => {
3053
+ const { storeItemsCommand } = await import("./items-3U5USBVG.js");
3054
+ await storeItemsCommand({ json: opts.json, format: opts.format });
3055
+ });
3056
+ 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) => {
3057
+ const { storeItemsToggleCommand } = await import("./items-toggle-YEKMI2CM.js");
3058
+ await storeItemsToggleCommand({
3059
+ enable: opts.enable,
3060
+ disable: opts.disable,
3061
+ json: opts.json
3062
+ });
3063
+ });
3064
+ 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) => {
3065
+ const { storeOrdersCommand } = await import("./store-UQ2DDQ5I.js");
3066
+ await storeOrdersCommand({
3067
+ json: opts.json,
3068
+ status: opts.status,
3069
+ page: opts.page,
3070
+ limit: opts.limit
3071
+ });
3072
+ });
3073
+ store.command("order-get <id>").description("Get order details").option("--json", "JSON output").action(async (id, opts) => {
3074
+ const { storeOrderGetCommand } = await import("./order-get-NSDMPUZR.js");
3075
+ await storeOrderGetCommand(id, { json: opts.json });
3076
+ });
3077
+ store.command("order-confirm <id>").description("Confirm a pending order").option("-y, --yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
3078
+ const { storeOrderConfirmCommand } = await import("./order-confirm-HUFCU6MO.js");
3079
+ await storeOrderConfirmCommand(id, { json: opts.json, yes: opts.yes });
3080
+ });
3081
+ 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) => {
3082
+ const { storeOrderCancelCommand } = await import("./order-cancel-XI2LKYXV.js");
3083
+ await storeOrderCancelCommand(id, {
3084
+ json: opts.json,
3085
+ yes: opts.yes,
3086
+ reason: opts.reason
3087
+ });
3088
+ });
3089
+ 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) => {
3090
+ const { storeOrderUpdateCommand } = await import("./order-update-C7QYSD5R.js");
3091
+ await storeOrderUpdateCommand(id, { json: opts.json, status: opts.status });
3092
+ });
3093
+ store.command("check-slug <slug>").description("Check store slug availability").option("--json", "JSON output").action(async (slug, opts) => {
3094
+ const { storeCheckSlugCommand } = await import("./check-slug-4TMOTWUJ.js");
3095
+ await storeCheckSlugCommand(slug, { json: opts.json });
3096
+ });
3007
3097
  }
3008
3098
 
3009
3099
  // src/commands/import/index.ts
@@ -3086,431 +3176,920 @@ async function importItemsCommand(filePath, opts) {
3086
3176
  fatalError(String(e instanceof Error ? e.message : e));
3087
3177
  }
3088
3178
  }
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";
3179
+ async function importInvoicesCommand(filePath, opts) {
3180
+ const cfg = requireAuth();
3181
+ const client = new HisaaboClient(cfg);
3182
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3183
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3184
+ console.log(` Importing ${data.length} invoices...`);
3185
+ try {
3186
+ const result = await client.import.importInvoices({ invoices: data });
3187
+ if (opts.json) {
3188
+ outputJSON(result);
3189
+ return;
3116
3190
  }
3117
- if (!email) email = (await ask(" Email: ")).trim();
3118
- if (!password) {
3119
- password = (await ask(" Password: ")).trim();
3191
+ success(`Imported: ${result.imported} invoices`);
3192
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3193
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3194
+ } catch (e) {
3195
+ if (e instanceof HisaaboApiError) {
3196
+ const err = e.hisaaboError;
3197
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3198
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3199
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3120
3200
  }
3121
- rl.close();
3122
- console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
3201
+ fatalError(String(e instanceof Error ? e.message : e));
3123
3202
  }
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) => {
3203
+ }
3204
+ async function importPaymentsCommand(filePath, opts) {
3133
3205
  const cfg = requireAuth();
3134
3206
  const client = new HisaaboClient(cfg);
3207
+ const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3208
+ const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3209
+ console.log(` Importing ${data.length} payments...`);
3135
3210
  try {
3136
- const businesses = await client.business.list();
3211
+ const result = await client.import.importPayments({ payments: data });
3137
3212
  if (opts.json) {
3138
- outputJSON(businesses);
3213
+ outputJSON(result);
3139
3214
  return;
3140
3215
  }
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}`);
3216
+ success(`Imported: ${result.imported} payments`);
3217
+ if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3218
+ result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3153
3219
  } catch (e) {
3154
3220
  if (e instanceof HisaaboApiError) {
3155
- if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3221
+ const err = e.hisaaboError;
3222
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3223
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3224
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3156
3225
  }
3157
3226
  fatalError(String(e instanceof Error ? e.message : e));
3158
3227
  }
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
3228
+ }
3229
+
3230
+ // src/bin/registrars/import.ts
3231
+ function registerImportCommands(program2) {
3232
+ const importCmd = program2.command("import").description("Bulk import data");
3233
+ 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) => {
3234
+ await importPartiesCommand(file, { json: opts.json, format: opts.format });
3182
3235
  });
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
3236
+ 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) => {
3237
+ await importItemsCommand(file, { json: opts.json, format: opts.format });
3200
3238
  });
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
3239
+ 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) => {
3240
+ await importInvoicesCommand(file, { json: opts.json, format: opts.format });
3221
3241
  });
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
3242
+ 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) => {
3243
+ await importPaymentsCommand(file, { json: opts.json, format: opts.format });
3246
3244
  });
3247
- });
3248
- item.command("get <id>").description("Get item details").option("--json", "JSON output").action(async (id, opts) => {
3245
+ }
3246
+
3247
+ // src/commands/automated-invoice/list.ts
3248
+ var FREQUENCY_LABELS = {
3249
+ weekly: "Weekly",
3250
+ biweekly: "Every 2 Weeks",
3251
+ monthly: "Monthly",
3252
+ quarterly: "Quarterly",
3253
+ half_yearly: "Every 6 Months",
3254
+ yearly: "Yearly",
3255
+ custom: "Custom"
3256
+ };
3257
+ function formatFrequency(freq) {
3258
+ return FREQUENCY_LABELS[freq] ?? freq;
3259
+ }
3260
+ function formatTemplateStatus(status) {
3261
+ const map = {
3262
+ active: "Active",
3263
+ paused: "Paused",
3264
+ completed: "Completed",
3265
+ expired: "Expired"
3266
+ };
3267
+ return map[status] ?? status;
3268
+ }
3269
+ function formatRuns(totalRuns, maxRuns) {
3270
+ if (maxRuns) return `${totalRuns}/${maxRuns}`;
3271
+ return String(totalRuns);
3272
+ }
3273
+ async function automatedInvoiceListCommand(opts) {
3249
3274
  const cfg = requireAuth();
3250
3275
  const client = new HisaaboClient(cfg);
3276
+ const page = opts.page ?? 1;
3277
+ const limit = opts.limit ?? 20;
3251
3278
  try {
3252
- const it = await client.item.get(id);
3279
+ const result = await client.recurringInvoice.list({
3280
+ status: opts.status,
3281
+ page,
3282
+ limit
3283
+ });
3253
3284
  if (opts.json) {
3254
- outputJSON(it);
3285
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
3255
3286
  return;
3256
3287
  }
3257
3288
  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();
3289
+ Recurring Invoices ${result.total} total
3290
+ `);
3291
+ const cols = [
3292
+ { key: "name", header: "Name", width: 20 },
3293
+ { key: "partyName", header: "Party", width: 18 },
3294
+ { key: "frequency", header: "Frequency", width: 14, format: (v) => formatFrequency(String(v ?? "")) },
3295
+ { key: "status", header: "Status", width: 10, format: (v) => formatTemplateStatus(String(v ?? "")) },
3296
+ { key: "nextRunDate", header: "Next Run", width: 13, format: (v) => formatDate(String(v ?? "")) },
3297
+ { key: "totalRuns", header: "Runs", width: 8, align: "right", format: (v, row) => formatRuns(Number(v ?? 0), row.maxRuns) }
3298
+ ];
3299
+ if (opts.format === "tsv") outputTSV(result.data, cols);
3300
+ else if (opts.format === "csv") outputCSV(result.data, cols);
3301
+ else if (opts.format === "ids") outputIds(result.data.map((r) => r.id));
3302
+ else {
3303
+ outputTable(result.data, cols);
3304
+ paginationFooter(result.page, result.limit, result.total);
3305
+ }
3268
3306
  } catch (e) {
3269
- if (e instanceof HisaaboApiError && e.hisaaboError.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
3307
+ if (e instanceof HisaaboApiError) {
3308
+ const err = e.hisaaboError;
3309
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3310
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3311
+ }
3270
3312
  fatalError(String(e instanceof Error ? e.message : e));
3271
3313
  }
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) => {
3314
+ }
3315
+
3316
+ // src/commands/automated-invoice/get.ts
3317
+ import chalk3 from "chalk";
3318
+ var FREQUENCY_LABELS2 = {
3319
+ weekly: "Weekly",
3320
+ biweekly: "Every 2 Weeks",
3321
+ monthly: "Monthly",
3322
+ quarterly: "Quarterly",
3323
+ half_yearly: "Every 6 Months",
3324
+ yearly: "Yearly",
3325
+ custom: "Custom"
3326
+ };
3327
+ function statusBadge(status) {
3328
+ const map = {
3329
+ active: (s) => chalk3.green(s),
3330
+ paused: (s) => chalk3.yellow(s),
3331
+ completed: (s) => chalk3.dim(s),
3332
+ expired: (s) => chalk3.red(s)
3333
+ };
3334
+ const label = `[${status.toUpperCase()}]`;
3335
+ if (!hasColor()) return label;
3336
+ const colorFn = map[status];
3337
+ return colorFn ? colorFn(label) : label;
3338
+ }
3339
+ async function automatedInvoiceGetCommand(id, opts) {
3469
3340
  const cfg = requireAuth();
3470
3341
  const client = new HisaaboClient(cfg);
3471
3342
  try {
3472
- const businesses = await client.business.list();
3343
+ let line2 = function(left, right) {
3344
+ if (right !== void 0) {
3345
+ const pad = Math.max(1, inner - left.length - right.length - 2);
3346
+ process.stdout.write(`| ${left}${" ".repeat(pad)}${right} |
3347
+ `);
3348
+ } else {
3349
+ const vis = left.length;
3350
+ const pad = Math.max(0, inner - vis);
3351
+ process.stdout.write(`| ${left}${" ".repeat(pad)} |
3352
+ `);
3353
+ }
3354
+ }, divider2 = function() {
3355
+ process.stdout.write(`+${"~".repeat(inner + 2)}+
3356
+ `);
3357
+ };
3358
+ var line = line2, divider = divider2;
3359
+ const tmpl = await client.recurringInvoice.getById(id);
3473
3360
  if (opts.json) {
3474
- outputJSON(businesses);
3361
+ outputJSON(tmpl);
3475
3362
  return;
3476
3363
  }
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}`);
3364
+ const w = Math.min(termWidth() - 2, 68);
3365
+ const inner = w - 2;
3366
+ const title = `RECURRING INVOICE ${tmpl.name}`;
3367
+ const badge = statusBadge(tmpl.status);
3368
+ const topPad = Math.max(1, inner - title.length - badge.replace(/\x1b\[[0-9;]*m/g, "").length);
3369
+ process.stdout.write(`
3370
+ +${"~".repeat(inner + 2)}+
3371
+ `);
3372
+ process.stdout.write(`| ${hasColor() ? chalk3.bold(title) : title}${" ".repeat(topPad)}${badge} |
3373
+ `);
3374
+ divider2();
3375
+ line2(`Party: ${tmpl.partyName}`);
3376
+ line2(`Type: ${tmpl.type === "sale" ? "Sale" : "Purchase"}`);
3377
+ line2(`Frequency: ${FREQUENCY_LABELS2[tmpl.frequency] ?? tmpl.frequency}`);
3378
+ if (tmpl.frequency === "custom" && tmpl.customIntervalDays) {
3379
+ line2(`Interval: Every ${tmpl.customIntervalDays} days`);
3380
+ }
3381
+ line2(`Start: ${formatDate(tmpl.startDate)}`);
3382
+ if (tmpl.endDate) line2(`End: ${formatDate(tmpl.endDate)}`);
3383
+ if (tmpl.nextRunDate) line2(`Next Run: ${formatDate(tmpl.nextRunDate)}`);
3384
+ if (tmpl.lastRunDate) line2(`Last Run: ${formatDate(tmpl.lastRunDate)}`);
3385
+ line2(`Runs: ${tmpl.totalRuns}${tmpl.maxRuns ? ` / ${tmpl.maxRuns}` : ""}`);
3386
+ divider2();
3387
+ process.stdout.write(`|${"".padEnd(inner + 2)}|
3388
+ `);
3389
+ process.stdout.write(`| # ${"Item".padEnd(18)} ${"Qty".padStart(5)} ${"Rate".padStart(10)} ${"Tax%".padStart(5)} |
3390
+ `);
3391
+ process.stdout.write(`| ${"--".padEnd(2)} ${"~".repeat(18)} ${"~".repeat(5)} ${"~".repeat(10)} ${"~".repeat(5)} |
3392
+ `);
3393
+ tmpl.lineItems.forEach((item, i) => {
3394
+ const idx = String(i + 1).padStart(2);
3395
+ const desc = item.description.slice(0, 18).padEnd(18);
3396
+ const qty = item.quantity.padStart(5);
3397
+ const rate = formatAmount(item.unitPrice).padStart(10);
3398
+ const tax = item.taxPercent ? `${item.taxPercent}%`.padStart(5) : " -";
3399
+ process.stdout.write(`| ${idx} ${desc} ${qty} ${rate} ${tax} |
3400
+ `);
3480
3401
  });
3481
- console.log();
3402
+ process.stdout.write(`|${"".padEnd(inner + 2)}|
3403
+ `);
3404
+ if (tmpl.notes) {
3405
+ divider2();
3406
+ line2(`Notes: ${tmpl.notes}`);
3407
+ }
3408
+ process.stdout.write(` +${"~".repeat(inner + 2)}+
3409
+
3410
+ `);
3482
3411
  } catch (e) {
3412
+ if (e instanceof HisaaboApiError) {
3413
+ const err = e.hisaaboError;
3414
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${id}`, EXIT.NOT_FOUND);
3415
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3416
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3417
+ }
3483
3418
  fatalError(String(e instanceof Error ? e.message : e));
3484
3419
  }
3485
- });
3486
- business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
3420
+ }
3421
+
3422
+ // src/commands/automated-invoice/create.ts
3423
+ async function automatedInvoiceCreateCommand(opts) {
3487
3424
  const cfg = requireAuth();
3488
3425
  const client = new HisaaboClient(cfg);
3426
+ if (!opts.partyId) fatalError("--party-id is required", EXIT.USAGE);
3427
+ if (!opts.name) fatalError("--name is required", EXIT.USAGE);
3428
+ if (!opts.type) fatalError("--type is required (sale or purchase)", EXIT.USAGE);
3429
+ if (!opts.frequency) fatalError("--frequency is required", EXIT.USAGE);
3430
+ if (!opts.startDate) fatalError("--start-date is required (YYYY-MM-DD)", EXIT.USAGE);
3431
+ const items = opts.lineItem ?? [];
3432
+ const qtys = opts.qty ?? [];
3433
+ const rates = opts.rate ?? [];
3434
+ const taxes = opts.tax ?? [];
3435
+ const discounts = opts.discount ?? [];
3436
+ if (items.length === 0) fatalError("At least one --line-item is required", EXIT.USAGE);
3437
+ const frequency = opts.frequency;
3438
+ if (frequency === "custom" && !opts.customIntervalDays) {
3439
+ fatalError("--custom-interval-days is required when frequency is 'custom'", EXIT.USAGE);
3440
+ }
3441
+ const lineItems = items.map((desc, i) => ({
3442
+ description: desc,
3443
+ quantity: qtys[i] ?? "1",
3444
+ unitPrice: rates[i] ?? "0",
3445
+ taxPercent: taxes[i],
3446
+ discountPercent: discounts[i]
3447
+ }));
3489
3448
  try {
3490
- const businesses = await client.business.list();
3449
+ const result = await client.recurringInvoice.create({
3450
+ partyId: opts.partyId,
3451
+ name: opts.name,
3452
+ type: opts.type,
3453
+ frequency,
3454
+ customIntervalDays: opts.customIntervalDays ? parseInt(opts.customIntervalDays, 10) : void 0,
3455
+ lineItems,
3456
+ startDate: opts.startDate,
3457
+ endDate: opts.endDate,
3458
+ maxRuns: opts.maxRuns ? parseInt(opts.maxRuns, 10) : void 0,
3459
+ notes: opts.notes
3460
+ });
3491
3461
  if (opts.json) {
3492
- outputJSON(businesses);
3462
+ outputJSON(result);
3493
3463
  return;
3494
3464
  }
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}`);
3465
+ success(`Created recurring invoice template: ${result.name} (${result.id})`);
3507
3466
  } catch (e) {
3508
3467
  if (e instanceof HisaaboApiError) {
3509
- if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3510
- }
3468
+ const err = e.hisaaboError;
3469
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3470
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3471
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3472
+ }
3511
3473
  fatalError(String(e instanceof Error ? e.message : e));
3512
3474
  }
3513
- });
3475
+ }
3476
+
3477
+ // src/commands/automated-invoice/update.ts
3478
+ async function automatedInvoiceUpdateCommand(id, opts) {
3479
+ const cfg = requireAuth();
3480
+ const client = new HisaaboClient(cfg);
3481
+ const data = {};
3482
+ if (opts.name !== void 0) data["name"] = opts.name;
3483
+ if (opts.frequency !== void 0) data["frequency"] = opts.frequency;
3484
+ if (opts.startDate !== void 0) data["startDate"] = opts.startDate;
3485
+ if (opts.endDate !== void 0) data["endDate"] = opts.endDate;
3486
+ if (opts.maxRuns !== void 0) data["maxRuns"] = parseInt(opts.maxRuns, 10);
3487
+ if (opts.notes !== void 0) data["notes"] = opts.notes;
3488
+ if (Object.keys(data).length === 0) {
3489
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
3490
+ }
3491
+ try {
3492
+ const result = await client.recurringInvoice.update(
3493
+ id,
3494
+ data
3495
+ );
3496
+ if (opts.json) {
3497
+ outputJSON(result);
3498
+ return;
3499
+ }
3500
+ success(`Updated recurring invoice template: ${result.name} (${result.id})`);
3501
+ } catch (e) {
3502
+ if (e instanceof HisaaboApiError) {
3503
+ const err = e.hisaaboError;
3504
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${id}`, EXIT.NOT_FOUND);
3505
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3506
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3507
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3508
+ }
3509
+ fatalError(String(e instanceof Error ? e.message : e));
3510
+ }
3511
+ }
3512
+
3513
+ // src/commands/automated-invoice/pause.ts
3514
+ async function automatedInvoicePauseCommand(id, opts) {
3515
+ const cfg = requireAuth();
3516
+ const client = new HisaaboClient(cfg);
3517
+ try {
3518
+ const result = await client.recurringInvoice.pause(id);
3519
+ if (opts.json) {
3520
+ outputJSON(result);
3521
+ return;
3522
+ }
3523
+ success(`Paused recurring invoice template: ${id}`);
3524
+ } catch (e) {
3525
+ if (e instanceof HisaaboApiError) {
3526
+ const err = e.hisaaboError;
3527
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3528
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3529
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3530
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3531
+ }
3532
+ fatalError(String(e instanceof Error ? e.message : e));
3533
+ }
3534
+ }
3535
+
3536
+ // src/commands/automated-invoice/resume.ts
3537
+ async function automatedInvoiceResumeCommand(id, opts) {
3538
+ const cfg = requireAuth();
3539
+ const client = new HisaaboClient(cfg);
3540
+ try {
3541
+ const result = await client.recurringInvoice.resume(id);
3542
+ if (opts.json) {
3543
+ outputJSON(result);
3544
+ return;
3545
+ }
3546
+ success(`Resumed recurring invoice template: ${id}`);
3547
+ } catch (e) {
3548
+ if (e instanceof HisaaboApiError) {
3549
+ const err = e.hisaaboError;
3550
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3551
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3552
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3553
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3554
+ }
3555
+ fatalError(String(e instanceof Error ? e.message : e));
3556
+ }
3557
+ }
3558
+
3559
+ // src/commands/automated-invoice/run-now.ts
3560
+ async function automatedInvoiceRunNowCommand(id, opts) {
3561
+ const cfg = requireAuth();
3562
+ const client = new HisaaboClient(cfg);
3563
+ try {
3564
+ const result = await client.recurringInvoice.runNow(id);
3565
+ if (opts.json) {
3566
+ outputJSON(result);
3567
+ return;
3568
+ }
3569
+ success(`Manually triggered recurring invoice template: ${id}`);
3570
+ } catch (e) {
3571
+ if (e instanceof HisaaboApiError) {
3572
+ const err = e.hisaaboError;
3573
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3574
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3575
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3576
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3577
+ }
3578
+ fatalError(String(e instanceof Error ? e.message : e));
3579
+ }
3580
+ }
3581
+
3582
+ // src/commands/automated-invoice/delete.ts
3583
+ import * as readline12 from "readline";
3584
+ async function automatedInvoiceDeleteCommand(id, opts) {
3585
+ const cfg = requireAuth();
3586
+ const client = new HisaaboClient(cfg);
3587
+ try {
3588
+ if (!opts.yes && process.stdin.isTTY) {
3589
+ const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
3590
+ const answer = await new Promise((resolve2) => {
3591
+ rl.question(` Delete recurring invoice template ${id}? (y/N): `, resolve2);
3592
+ });
3593
+ rl.close();
3594
+ if (answer.trim().toLowerCase() !== "y") {
3595
+ console.log(" Cancelled.");
3596
+ process.exit(0);
3597
+ }
3598
+ }
3599
+ const result = await client.recurringInvoice.delete(id);
3600
+ if (opts.json) {
3601
+ outputJSON(result);
3602
+ return;
3603
+ }
3604
+ success(`Deleted recurring invoice template: ${id}`);
3605
+ } catch (e) {
3606
+ if (e instanceof HisaaboApiError) {
3607
+ const err = e.hisaaboError;
3608
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
3609
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3610
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
3611
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3612
+ }
3613
+ fatalError(String(e instanceof Error ? e.message : e));
3614
+ }
3615
+ }
3616
+
3617
+ // src/commands/automated-invoice/history.ts
3618
+ import chalk4 from "chalk";
3619
+ function executionStatusBadge(status) {
3620
+ const map = {
3621
+ success: chalk4.green("success"),
3622
+ failed: chalk4.red("failed"),
3623
+ skipped: chalk4.yellow("skipped")
3624
+ };
3625
+ return map[status] ?? status;
3626
+ }
3627
+ async function automatedInvoiceHistoryCommand(templateId, opts) {
3628
+ const cfg = requireAuth();
3629
+ const client = new HisaaboClient(cfg);
3630
+ const page = opts.page ?? 1;
3631
+ const limit = opts.limit ?? 20;
3632
+ try {
3633
+ const result = await client.recurringInvoice.executionHistory(templateId, page, limit);
3634
+ if (opts.json) {
3635
+ outputJSON({ data: result.data, pagination: { page: result.page, limit: result.limit, total: result.total } });
3636
+ return;
3637
+ }
3638
+ console.log(`
3639
+ Execution History ${result.total} total
3640
+ `);
3641
+ const cols = [
3642
+ { key: "executedAt", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
3643
+ { key: "invoiceNumber", header: "Invoice #", width: 20 },
3644
+ { key: "status", header: "Status", width: 10, format: (v) => executionStatusBadge(String(v ?? "")) },
3645
+ { key: "errorMessage", header: "Error", width: 30, format: (v) => v ? String(v) : "\u2014" }
3646
+ ];
3647
+ if (opts.format === "tsv") outputTSV(result.data, cols);
3648
+ else if (opts.format === "csv") outputCSV(result.data, cols);
3649
+ else {
3650
+ outputTable(result.data, cols);
3651
+ paginationFooter(result.page, result.limit, result.total);
3652
+ }
3653
+ } catch (e) {
3654
+ if (e instanceof HisaaboApiError) {
3655
+ const err = e.hisaaboError;
3656
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${templateId}`, EXIT.NOT_FOUND);
3657
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3658
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3659
+ }
3660
+ fatalError(String(e instanceof Error ? e.message : e));
3661
+ }
3662
+ }
3663
+
3664
+ // src/commands/automated-invoice/usage.ts
3665
+ import chalk5 from "chalk";
3666
+ var FREE_PLAN_LIMIT = 5;
3667
+ var BAR_WIDTH = 20;
3668
+ function usageBar(used, limit) {
3669
+ const pct = limit > 0 ? Math.min(used / limit, 1) : 0;
3670
+ const filled = Math.round(pct * BAR_WIDTH);
3671
+ const empty = BAR_WIDTH - filled;
3672
+ const filledChar = "\u2588".repeat(filled);
3673
+ const emptyChar = "\u2591".repeat(empty);
3674
+ if (!hasColor()) return `[${filledChar}${emptyChar}]`;
3675
+ const bar = pct >= 1 ? chalk5.red(filledChar) : pct >= 0.8 ? chalk5.yellow(filledChar) : chalk5.green(filledChar);
3676
+ return `[${bar}${chalk5.dim(emptyChar)}]`;
3677
+ }
3678
+ async function automatedInvoiceUsageCommand(opts) {
3679
+ const cfg = requireAuth();
3680
+ const client = new HisaaboClient(cfg);
3681
+ try {
3682
+ const result = await client.recurringInvoice.planUsage();
3683
+ if (opts.json) {
3684
+ outputJSON(result);
3685
+ return;
3686
+ }
3687
+ const limit = FREE_PLAN_LIMIT;
3688
+ const pct = limit > 0 ? Math.round(result.runsThisMonth / limit * 100) : 0;
3689
+ console.log("\n Plan Usage \u2014 Recurring Invoices\n");
3690
+ console.log(` Templates: ${result.totalTemplates}`);
3691
+ console.log(` Runs/month: ${result.runsThisMonth} / ${limit} ${usageBar(result.runsThisMonth, limit)} ${pct}%`);
3692
+ if (result.runsThisMonth >= limit) {
3693
+ const msg = " Monthly run limit reached. Upgrade your plan for unlimited runs.";
3694
+ console.log(hasColor() ? chalk5.red(msg) : msg);
3695
+ } else {
3696
+ const remaining = limit - result.runsThisMonth;
3697
+ console.log(` Remaining: ${remaining} run${remaining !== 1 ? "s" : ""} this month`);
3698
+ }
3699
+ console.log();
3700
+ } catch (e) {
3701
+ if (e instanceof HisaaboApiError) {
3702
+ const err = e.hisaaboError;
3703
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3704
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3705
+ }
3706
+ fatalError(String(e instanceof Error ? e.message : e));
3707
+ }
3708
+ }
3709
+
3710
+ // src/commands/automated-invoice/suggestions.ts
3711
+ import chalk6 from "chalk";
3712
+ var FREQUENCY_LABELS3 = {
3713
+ weekly: "Weekly",
3714
+ biweekly: "Every 2 Weeks",
3715
+ monthly: "Monthly",
3716
+ quarterly: "Quarterly",
3717
+ half_yearly: "Every 6 Months",
3718
+ yearly: "Yearly",
3719
+ custom: "Custom"
3720
+ };
3721
+ function confidenceBadge(confidence) {
3722
+ const pct = Math.round(confidence * 100);
3723
+ const label = `${pct}%`;
3724
+ if (confidence >= 0.8) return chalk6.green(label);
3725
+ if (confidence >= 0.5) return chalk6.yellow(label);
3726
+ return chalk6.dim(label);
3727
+ }
3728
+ async function automatedInvoiceSuggestionsCommand(opts) {
3729
+ const cfg = requireAuth();
3730
+ const client = new HisaaboClient(cfg);
3731
+ try {
3732
+ const result = await client.recurringInvoice.suggestions();
3733
+ if (opts.json) {
3734
+ outputJSON(result);
3735
+ return;
3736
+ }
3737
+ if (result.length === 0) {
3738
+ console.log("\n No recurring invoice suggestions yet.\n");
3739
+ console.log(" Suggestions appear after patterns are detected in your invoice history.\n");
3740
+ return;
3741
+ }
3742
+ console.log(`
3743
+ Recurring Invoice Suggestions ${result.length} found
3744
+ `);
3745
+ const cols = [
3746
+ { key: "partyName", header: "Party", width: 24 },
3747
+ { key: "frequency", header: "Suggested Frequency", width: 20, format: (v) => FREQUENCY_LABELS3[String(v ?? "")] ?? String(v ?? "") },
3748
+ { key: "confidence", header: "Confidence", width: 12, align: "right", format: (v) => confidenceBadge(Number(v ?? 0)) },
3749
+ { key: "reason", header: "Reason", width: 36 }
3750
+ ];
3751
+ outputTable(result, cols);
3752
+ console.log();
3753
+ console.log(` Tip: run ${chalk6.cyan("hisaabo automated-invoice create --party-id <id>")} to set up a template.
3754
+ `);
3755
+ } catch (e) {
3756
+ if (e instanceof HisaaboApiError) {
3757
+ const err = e.hisaaboError;
3758
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3759
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3760
+ }
3761
+ fatalError(String(e instanceof Error ? e.message : e));
3762
+ }
3763
+ }
3764
+
3765
+ // src/bin/registrars/automated-invoice.ts
3766
+ function registerAutomatedInvoiceCommands(program2) {
3767
+ const automatedInvoice = program2.command("automated-invoice").alias("auto-inv").description("Recurring / automated invoice management");
3768
+ 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) => {
3769
+ await automatedInvoiceListCommand({
3770
+ json: opts.json,
3771
+ format: opts.format,
3772
+ status: opts.status,
3773
+ page: opts.page,
3774
+ limit: opts.limit
3775
+ });
3776
+ });
3777
+ automatedInvoice.command("get <id>").description("Get recurring invoice template details").option("--json", "JSON output").action(async (id, opts) => {
3778
+ await automatedInvoiceGetCommand(id, { json: opts.json });
3779
+ });
3780
+ 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) => {
3781
+ await automatedInvoiceCreateCommand({
3782
+ json: opts.json,
3783
+ partyId: opts.partyId,
3784
+ name: opts.name,
3785
+ type: opts.type,
3786
+ frequency: opts.frequency,
3787
+ customIntervalDays: opts.customIntervalDays,
3788
+ lineItem: opts.lineItem,
3789
+ qty: opts.qty,
3790
+ rate: opts.rate,
3791
+ tax: opts.tax,
3792
+ discount: opts.discount,
3793
+ startDate: opts.startDate,
3794
+ endDate: opts.endDate,
3795
+ maxRuns: opts.maxRuns,
3796
+ notes: opts.notes
3797
+ });
3798
+ });
3799
+ automatedInvoice.command("pause <id>").description("Pause an active recurring invoice template").option("--json", "JSON output").action(async (id, opts) => {
3800
+ await automatedInvoicePauseCommand(id, { json: opts.json });
3801
+ });
3802
+ automatedInvoice.command("resume <id>").description("Resume a paused recurring invoice template").option("--json", "JSON output").action(async (id, opts) => {
3803
+ await automatedInvoiceResumeCommand(id, { json: opts.json });
3804
+ });
3805
+ automatedInvoice.command("run-now <id>").description("Manually trigger a recurring invoice template execution").option("--json", "JSON output").action(async (id, opts) => {
3806
+ await automatedInvoiceRunNowCommand(id, { json: opts.json });
3807
+ });
3808
+ automatedInvoice.command("delete <id>").description("Delete a recurring invoice template").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3809
+ await automatedInvoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
3810
+ });
3811
+ 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) => {
3812
+ await automatedInvoiceUpdateCommand(id, {
3813
+ json: opts.json,
3814
+ name: opts.name,
3815
+ frequency: opts.frequency,
3816
+ startDate: opts.startDate,
3817
+ endDate: opts.endDate,
3818
+ maxRuns: opts.maxRuns,
3819
+ notes: opts.notes
3820
+ });
3821
+ });
3822
+ 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) => {
3823
+ await automatedInvoiceHistoryCommand(templateId, {
3824
+ json: opts.json,
3825
+ format: opts.format,
3826
+ page: opts.page,
3827
+ limit: opts.limit
3828
+ });
3829
+ });
3830
+ automatedInvoice.command("usage").description("Show plan usage for recurring invoices").option("--json", "JSON output").action(async (opts) => {
3831
+ await automatedInvoiceUsageCommand({ json: opts.json });
3832
+ });
3833
+ automatedInvoice.command("suggestions").description("Show suggested recurring invoice templates based on invoice history").option("--json", "JSON output").action(async (opts) => {
3834
+ await automatedInvoiceSuggestionsCommand({ json: opts.json });
3835
+ });
3836
+ }
3837
+
3838
+ // src/bin/registrars/business.ts
3839
+ import * as readline13 from "readline";
3840
+ function registerBusinessCommands(program2) {
3841
+ const business = program2.command("business").description("Business management");
3842
+ business.command("list").description("List all businesses").option("--json", "JSON output").action(async (opts) => {
3843
+ const cfg = requireAuth();
3844
+ const client = new HisaaboClient(cfg);
3845
+ try {
3846
+ const businesses = await client.business.list();
3847
+ if (opts.json) {
3848
+ outputJSON(businesses);
3849
+ return;
3850
+ }
3851
+ businesses.forEach((b, i) => {
3852
+ const active = b.id === cfg.businessId ? " [active]" : "";
3853
+ console.log(` ${i + 1} ${b.name.padEnd(30)} ${(b.gstin ?? "-").padEnd(18)} ${b.gstRegistrationType}${active}`);
3854
+ });
3855
+ console.log();
3856
+ } catch (e) {
3857
+ fatalError(String(e instanceof Error ? e.message : e));
3858
+ }
3859
+ });
3860
+ business.command("get").description("Show current business details").option("--json", "JSON output").action(async (opts) => {
3861
+ const { businessGetCommand } = await import("./get-EXL44I2X.js");
3862
+ await businessGetCommand(opts);
3863
+ });
3864
+ 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) => {
3865
+ const { businessUpdateCommand } = await import("./update-IG565YIN.js");
3866
+ await businessUpdateCommand(opts);
3867
+ });
3868
+ 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) => {
3869
+ const { businessSequenceCommand } = await import("./sequence-XUD6FAKY.js");
3870
+ await businessSequenceCommand(opts);
3871
+ });
3872
+ 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) => {
3873
+ const { businessAuditTrailCommand } = await import("./audit-trail-2YGXGUXW.js");
3874
+ await businessAuditTrailCommand(opts);
3875
+ });
3876
+ business.command("export").description("Export all business data").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (opts) => {
3877
+ const { businessExportCommand } = await import("./export-QZ6WT6PJ.js");
3878
+ await businessExportCommand(opts);
3879
+ });
3880
+ business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
3881
+ const cfg = requireAuth();
3882
+ const client = new HisaaboClient(cfg);
3883
+ try {
3884
+ const businesses = await client.business.list();
3885
+ if (opts.json) {
3886
+ outputJSON(businesses);
3887
+ return;
3888
+ }
3889
+ businesses.forEach((b, i) => {
3890
+ const active = b.id === cfg.businessId ? " [active]" : "";
3891
+ console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
3892
+ });
3893
+ const rl = readline13.createInterface({ input: process.stdin, output: process.stdout });
3894
+ const answer = await new Promise((res) => rl.question("\n Select: ", res));
3895
+ rl.close();
3896
+ const idx = parseInt(answer.trim(), 10) - 1;
3897
+ const selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
3898
+ if (!selected) fatalError("Invalid selection.", EXIT.USAGE);
3899
+ setConfig({ businessId: selected.id, businessName: selected.name });
3900
+ success(`Switched to: ${selected.name}`);
3901
+ } catch (e) {
3902
+ if (e instanceof HisaaboApiError) {
3903
+ if (e.hisaaboError.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3904
+ }
3905
+ fatalError(String(e instanceof Error ? e.message : e));
3906
+ }
3907
+ });
3908
+ }
3909
+
3910
+ // src/bin/registrars/document.ts
3911
+ var DOC_TYPES = [
3912
+ {
3913
+ cmd: "quotation",
3914
+ label: "Quotation",
3915
+ nsKey: "quotation",
3916
+ statuses: ["draft", "sent", "accepted", "rejected", "expired", "cancelled"]
3917
+ },
3918
+ {
3919
+ cmd: "credit-note",
3920
+ label: "Credit Note",
3921
+ nsKey: "creditNote",
3922
+ statuses: ["draft", "confirmed", "cancelled"]
3923
+ },
3924
+ {
3925
+ cmd: "debit-note",
3926
+ label: "Debit Note",
3927
+ nsKey: "debitNote",
3928
+ statuses: ["draft", "confirmed", "cancelled"]
3929
+ },
3930
+ {
3931
+ cmd: "delivery-challan",
3932
+ label: "Delivery Challan",
3933
+ nsKey: "deliveryChallan",
3934
+ statuses: ["draft", "dispatched", "delivered", "cancelled"]
3935
+ },
3936
+ {
3937
+ cmd: "proforma",
3938
+ label: "Proforma Invoice",
3939
+ nsKey: "proforma",
3940
+ statuses: ["draft", "sent", "accepted", "rejected", "expired", "converted", "cancelled"]
3941
+ },
3942
+ {
3943
+ cmd: "sales-return",
3944
+ label: "Sales Return",
3945
+ nsKey: "salesReturn",
3946
+ statuses: ["draft", "confirmed", "cancelled"]
3947
+ },
3948
+ {
3949
+ cmd: "purchase-return",
3950
+ label: "Purchase Return",
3951
+ nsKey: "purchaseReturn",
3952
+ statuses: ["draft", "confirmed", "cancelled"]
3953
+ }
3954
+ ];
3955
+ function registerDocumentCommands(program2) {
3956
+ for (const dt of DOC_TYPES) {
3957
+ const parent = program2.command(dt.cmd).description(`${dt.label} management`);
3958
+ 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) => {
3959
+ const { docListCommand } = await import("./factory-2DCU3B5T.js");
3960
+ await docListCommand(dt, opts);
3961
+ });
3962
+ parent.command("get <id>").description(`Get ${dt.label.toLowerCase()} details`).option("--json", "JSON output").action(async (id, opts) => {
3963
+ const { docGetCommand } = await import("./factory-2DCU3B5T.js");
3964
+ await docGetCommand(dt, id, opts);
3965
+ });
3966
+ 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) => {
3967
+ const { docCreateCommand } = await import("./factory-2DCU3B5T.js");
3968
+ await docCreateCommand(dt, opts);
3969
+ });
3970
+ parent.command("update-status <id> <status>").description(`Update ${dt.label.toLowerCase()} status (${dt.statuses.join(", ")})`).option("--json", "JSON output").action(async (id, status, opts) => {
3971
+ const { docStatusCommand } = await import("./factory-2DCU3B5T.js");
3972
+ await docStatusCommand(dt, id, status, opts);
3973
+ });
3974
+ parent.command("delete <id>").description(`Delete a ${dt.label.toLowerCase()}`).option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
3975
+ const { docDeleteCommand } = await import("./factory-2DCU3B5T.js");
3976
+ await docDeleteCommand(dt, id, opts);
3977
+ });
3978
+ }
3979
+ 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) => {
3980
+ const { HisaaboClient: HisaaboClient2, HisaaboApiError: HisaaboApiError2 } = await import("./client-QNJ2H5CW.js");
3981
+ const { requireAuth: requireAuth2 } = await import("./config-UKVQYPPR.js");
3982
+ const { fatalError: fatalError2, outputJSON: outputJSON2, success: success2, EXIT: EXIT2 } = await import("./output-QFLEKG5W.js");
3983
+ const cfg = requireAuth2();
3984
+ const client = new HisaaboClient2(cfg);
3985
+ if (!opts.yes && process.stdin.isTTY) {
3986
+ const readline14 = await import("readline");
3987
+ const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
3988
+ const answer = await new Promise((resolve2) => {
3989
+ rl.question(
3990
+ ` Convert ${opts.fromType} ${opts.fromId} \u2192 ${opts.toType}? (y/N): `,
3991
+ resolve2
3992
+ );
3993
+ });
3994
+ rl.close();
3995
+ if (answer.trim().toLowerCase() !== "y") {
3996
+ console.log(" Cancelled.");
3997
+ process.exit(EXIT2.SUCCESS);
3998
+ }
3999
+ }
4000
+ try {
4001
+ const result = await client.document.convert({
4002
+ fromType: opts.fromType,
4003
+ fromId: opts.fromId,
4004
+ toType: opts.toType
4005
+ });
4006
+ if (opts.json) {
4007
+ outputJSON2(result);
4008
+ return;
4009
+ }
4010
+ const newId = result.id ?? result.documentId ?? "(unknown)";
4011
+ const newNum = result.documentNumber ?? result.number ?? newId;
4012
+ success2(`Converted: ${opts.fromType} \u2192 ${opts.toType} ${newNum}`);
4013
+ console.log(` New ID: ${newId}
4014
+ `);
4015
+ } catch (e) {
4016
+ if (e instanceof HisaaboApiError2) {
4017
+ const err = e.hisaaboError;
4018
+ if (err.code === "not_found") fatalError2(`Source document not found: ${opts.fromId}`, EXIT2.NOT_FOUND);
4019
+ if (err.code === "unauthorized") fatalError2("Session expired. Run: hisaabo login", EXIT2.AUTH);
4020
+ if (err.code === "forbidden") fatalError2(err.message, EXIT2.FORBIDDEN);
4021
+ if (err.code === "validation_failed") fatalError2(e.message, EXIT2.VALIDATION);
4022
+ if (err.code === "network_error") fatalError2(err.message, EXIT2.NETWORK);
4023
+ }
4024
+ fatalError2(String(e instanceof Error ? e.message : e));
4025
+ }
4026
+ });
4027
+ }
4028
+
4029
+ // src/bin/registrars/tenant.ts
4030
+ function registerTenantCommands(program2) {
4031
+ const tenant = program2.command("tenant").description("Tenant / workspace management");
4032
+ tenant.command("list").description("List tenants / organizations you belong to").option("--json", "JSON output").action(async (opts) => {
4033
+ const { tenantListCommand } = await import("./list-FX2C3NCL.js");
4034
+ await tenantListCommand({ json: opts.json });
4035
+ });
4036
+ 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) => {
4037
+ const { tenantMembersCommand } = await import("./members-5FPRUAB6.js");
4038
+ await tenantMembersCommand({ json: opts.json, format: opts.format });
4039
+ });
4040
+ 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) => {
4041
+ const { tenantInviteCommand } = await import("./invite-O26SAL72.js");
4042
+ await tenantInviteCommand(email, { role: opts.role, json: opts.json });
4043
+ });
4044
+ tenant.command("remove <userId>").description("Remove a member from the tenant").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (userId, opts) => {
4045
+ const { tenantRemoveCommand } = await import("./remove-M2B4TZ37.js");
4046
+ await tenantRemoveCommand(userId, { yes: opts.yes, json: opts.json });
4047
+ });
4048
+ 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) => {
4049
+ const { tenantUpdateRoleCommand } = await import("./update-role-Q4ZYJRYT.js");
4050
+ await tenantUpdateRoleCommand(userId, role, { json: opts.json });
4051
+ });
4052
+ }
4053
+
4054
+ // src/bin/registrars/api-key.ts
4055
+ function registerApiKeyCommands(program2) {
4056
+ const apiKey = program2.command("api-key").alias("key").description("API key management");
4057
+ apiKey.command("list").description("List all API keys").option("--json", "JSON output").option("--format <fmt>", "Output format: table, tsv, csv").action(async (opts) => {
4058
+ const { apiKeyListCommand } = await import("./list-VBAHY72W.js");
4059
+ await apiKeyListCommand(opts);
4060
+ });
4061
+ apiKey.command("create").description("Create a new API key").requiredOption("--name <name>", "Name / label for this key").option("--json", "JSON output").action(async (opts) => {
4062
+ const { apiKeyCreateCommand } = await import("./create-Y22FAVOW.js");
4063
+ await apiKeyCreateCommand(opts);
4064
+ });
4065
+ apiKey.command("revoke <id>").description("Revoke an API key by ID").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
4066
+ const { apiKeyRevokeCommand } = await import("./revoke-H3V2GNCD.js");
4067
+ await apiKeyRevokeCommand(id, opts);
4068
+ });
4069
+ }
4070
+
4071
+ // src/bin/hisaabo.ts
4072
+ var program = new Command();
4073
+ program.name("hisaabo").description("Hisaabo CLI \u2014 Invoicing and business management").version("0.1.0");
4074
+ registerAuthCommands(program);
4075
+ registerDashboardCommands(program);
4076
+ registerInvoiceCommands(program);
4077
+ registerPartyCommands(program);
4078
+ registerItemCommands(program);
4079
+ registerPaymentCommands(program);
4080
+ registerExpenseCommands(program);
4081
+ registerGstCommands(program);
4082
+ registerReportCommands(program);
4083
+ registerBankCommands(program);
4084
+ registerShipmentCommands(program);
4085
+ registerTargetCommands(program);
4086
+ registerStoreCommands(program);
4087
+ registerImportCommands(program);
4088
+ registerAutomatedInvoiceCommands(program);
4089
+ registerBusinessCommands(program);
4090
+ registerDocumentCommands(program);
4091
+ registerTenantCommands(program);
4092
+ registerApiKeyCommands(program);
3514
4093
  program.parseAsync(process.argv).catch((err) => {
3515
4094
  fatalError(String(err instanceof Error ? err.message : err));
3516
4095
  });