@hisaabo/cli 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +154 -4
  2. package/dist/bin/{audit-trail-IJ6SKACR.js → audit-trail-RTPTWZAL.js} +12 -15
  3. package/dist/bin/{categories-O6TODPAH.js → categories-JJDTOT5T.js} +3 -3
  4. package/dist/bin/{check-slug-P7RFU6OP.js → check-slug-5L2VDAEN.js} +16 -4
  5. package/dist/bin/chunk-2DDIXPNI.js +1512 -0
  6. package/dist/bin/chunk-ALOHN6GR.js +78 -0
  7. package/dist/bin/{chunk-QUITS2FE.js → chunk-ESX7V56A.js} +95 -20
  8. package/dist/bin/chunk-M7DVLVD5.js +245 -0
  9. package/dist/bin/{chunk-WDN7RIE3.js → chunk-VXEEFNIY.js} +133 -47
  10. package/dist/bin/client-NFYNYEDI.js +17 -0
  11. package/dist/bin/{collection-efficiency-DA5RWG3V.js → collection-efficiency-UF3AJPQB.js} +12 -56
  12. package/dist/bin/{config-4LLNT4SH.js → config-7HVBRHL3.js} +2 -2
  13. package/dist/bin/{create-C5INBPQO.js → create-2BZQLXQA.js} +18 -9
  14. package/dist/bin/{default-account-2GMQ7ZA4.js → default-account-MR6O5LPT.js} +7 -13
  15. package/dist/bin/{expenses-S2YVA5UT.js → expenses-CU6JGDVX.js} +12 -11
  16. package/dist/bin/{export-YOOODNVX.js → export-GFYQIQLT.js} +9 -24
  17. package/dist/bin/{export-6PMJ2YVL.js → export-WS24LYNH.js} +47 -11
  18. package/dist/bin/{factory-6MUCSXTL.js → factory-JSEQCPY3.js} +51 -57
  19. package/dist/bin/{get-GMQRROK2.js → get-HGMB7T6Y.js} +5 -4
  20. package/dist/bin/{get-ZV3SC2VY.js → get-KAOGGRJR.js} +4 -4
  21. package/dist/bin/hisaabo.js +2024 -837
  22. package/dist/bin/{import-UUHMLCKX.js → import-6CEMNCTM.js} +30 -33
  23. package/dist/bin/{invitations-OVORTTMF.js → invitations-LASABD2X.js} +11 -14
  24. package/dist/bin/{invite-GGHBZY4U.js → invite-VCBXS7VY.js} +13 -15
  25. package/dist/bin/{invoice-breakdown-32XXAZDP.js → invoice-breakdown-3XXSYA77.js} +12 -37
  26. package/dist/bin/{items-6NOIMH6B.js → items-PJPN6ZX3.js} +11 -10
  27. package/dist/bin/{items-toggle-L6W6QKQD.js → items-toggle-53C35MJU.js} +6 -5
  28. package/dist/bin/{list-RAR56EMQ.js → list-63EKE6DT.js} +13 -16
  29. package/dist/bin/{list-OXAVDXH7.js → list-7OSZX6C7.js} +5 -5
  30. package/dist/bin/{list-FC5JHKHD.js → list-OOROCQR2.js} +11 -12
  31. package/dist/bin/{members-Y6XJVHHR.js → members-SPHU5F4M.js} +7 -7
  32. package/dist/bin/monthly-comparison-3FFJT63K.js +79 -0
  33. package/dist/bin/{order-cancel-QRTCNART.js → order-cancel-RW4NYHKN.js} +8 -18
  34. package/dist/bin/{order-confirm-LGQOMC4O.js → order-confirm-NXFL2EIQ.js} +7 -15
  35. package/dist/bin/{order-get-4XAQCRYV.js → order-get-QPSOY2RT.js} +11 -11
  36. package/dist/bin/{order-update-KZY4H2UR.js → order-update-7DWKEROO.js} +4 -4
  37. package/dist/bin/{output-NUOL7KJW.js → output-XFDIL3A6.js} +5 -1
  38. package/dist/bin/{payment-modes-DY2ZEMK7.js → payment-modes-Z5WV3E3O.js} +12 -27
  39. package/dist/bin/{profit-loss-5GJBG3PL.js → profit-loss-AOISAJ56.js} +14 -13
  40. package/dist/bin/{receivables-aging-6A7XJKDT.js → receivables-aging-5JHFECGB.js} +13 -66
  41. package/dist/bin/{remove-ZBX34TIQ.js → remove-TC4UWMOL.js} +7 -15
  42. package/dist/bin/{revoke-ZTAMW2Q2.js → revoke-QHLNPGI5.js} +7 -3
  43. package/dist/bin/{revoke-XDNOA2GJ.js → revoke-SXVNALYQ.js} +7 -15
  44. package/dist/bin/{revoke-all-365NRBOA.js → revoke-all-CYW6A5UE.js} +8 -4
  45. package/dist/bin/{revoke-invitation-PQH7XNYA.js → revoke-invitation-Z33EUJTS.js} +7 -3
  46. package/dist/bin/safety-TPD2P7I5.js +18 -0
  47. package/dist/bin/{sales-trend-D6PQ7MHY.js → sales-trend-WCW6X5BI.js} +16 -16
  48. package/dist/bin/sequence-HOQ4PQRK.js +56 -0
  49. package/dist/bin/{store-SVRZBUFO.js → store-DDMHTNTO.js} +15 -8
  50. package/dist/bin/{summary-H6U7O5GJ.js → summary-TYAL2D3Q.js} +7 -5
  51. package/dist/bin/{top-customers-ATBN6RDI.js → top-customers-GMIS6GC3.js} +13 -11
  52. package/dist/bin/{top-items-XXU6KYTC.js → top-items-BK54JO3G.js} +16 -14
  53. package/dist/bin/{top-outstanding-JTQNGGW4.js → top-outstanding-L4NRJ6NE.js} +9 -11
  54. package/dist/bin/{unpaid-invoices-BTNQFWCH.js → unpaid-invoices-CEUFEYH7.js} +8 -8
  55. package/dist/bin/{untracked-PAMEDJ6Y.js → untracked-T6DIDMDQ.js} +9 -9
  56. package/dist/bin/{update-EK4NJWU4.js → update-EPNB2U74.js} +4 -4
  57. package/dist/bin/{update-EGHPFXLK.js → update-I2DZRVLR.js} +10 -17
  58. package/dist/bin/{update-6ZMX2OYX.js → update-MFNOVS6D.js} +4 -4
  59. package/dist/bin/{update-role-24PDTNFK.js → update-role-D2ETEL2Q.js} +7 -4
  60. package/dist/bin/{update-settings-AASI6WZX.js → update-settings-UGXLQRYI.js} +15 -9
  61. package/package.json +8 -7
  62. package/dist/bin/chunk-NO4FIFMS.js +0 -176
  63. package/dist/bin/chunk-ZPYC767N.js +0 -157
  64. package/dist/bin/client-36JX5MR3.js +0 -11
  65. package/dist/bin/monthly-comparison-IAUZ6SBJ.js +0 -176
  66. package/dist/bin/sequence-KZWADVD7.js +0 -66
@@ -1,5 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ MAX_DOWNLOAD_BYTES,
4
+ confirmOrExit,
5
+ requireUuid,
6
+ safeFilename,
7
+ writeFileSafe
8
+ } from "./chunk-ALOHN6GR.js";
9
+ import {
10
+ InvalidTimeZoneError,
11
+ apiFrom,
12
+ apiTo,
3
13
  currentFY,
4
14
  deliveryMethodLabel,
5
15
  formatAmount,
@@ -10,34 +20,48 @@ import {
10
20
  monthEnd,
11
21
  monthStart,
12
22
  quarterRange,
23
+ setTimeZone,
24
+ toApiDateTime,
13
25
  todayISO
14
- } from "./chunk-ZPYC767N.js";
26
+ } from "./chunk-M7DVLVD5.js";
15
27
  import {
16
28
  HisaaboApiError,
17
- HisaaboClient
18
- } from "./chunk-WDN7RIE3.js";
29
+ HisaaboClient,
30
+ NOTIFICATION_CHANNELS,
31
+ requestTimeoutMs
32
+ } from "./chunk-VXEEFNIY.js";
19
33
  import {
20
34
  clearConfig,
21
35
  getConfig,
22
36
  getConfigPath,
23
37
  requireAuth,
24
- setConfig
25
- } from "./chunk-QUITS2FE.js";
38
+ setConfig,
39
+ validateApiUrl
40
+ } from "./chunk-ESX7V56A.js";
26
41
  import {
27
42
  EXIT,
43
+ bankAccountTypes,
44
+ deliveryMethods,
28
45
  fatalError,
29
46
  getWidthTier,
30
47
  hasColor,
48
+ installTerminalSanitizer,
49
+ itcBlockReasons,
50
+ money,
51
+ moneyStringSchema,
31
52
  outputCSV,
32
53
  outputIds,
33
54
  outputJSON,
34
55
  outputTSV,
35
56
  outputTable,
36
57
  paginationFooter,
58
+ paymentAllocationSchema,
59
+ sanitizeTerminal,
37
60
  success,
38
61
  termWidth,
62
+ units,
39
63
  warn
40
- } from "./chunk-NO4FIFMS.js";
64
+ } from "./chunk-2DDIXPNI.js";
41
65
 
42
66
  // src/bin/hisaabo.ts
43
67
  import { Command } from "commander";
@@ -45,14 +69,149 @@ import { Command } from "commander";
45
69
  // src/bin/registrars/auth.ts
46
70
  import * as readline from "readline";
47
71
 
48
- // src/auth.ts
49
- function validateApiUrl(url) {
50
- const parsed = new URL(url);
51
- if (!["http:", "https:"].includes(parsed.protocol)) {
52
- fatalError("API URL must use http:// or https://", EXIT.USAGE);
72
+ // src/native-login.ts
73
+ import { createHash, randomBytes } from "crypto";
74
+ import { spawn } from "child_process";
75
+ import { createServer } from "http";
76
+ var HOSTED_API_URL = "https://api.hisaabo.in";
77
+ var HOSTED_WEB_URL = "https://app.hisaabo.in";
78
+ var CALLBACK_TIMEOUT_MS = 5 * 6e4;
79
+ var CALLBACK_PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>Hisaabo CLI</title></head>
80
+ <body style="font-family:system-ui,sans-serif;text-align:center;padding:4rem 1rem">
81
+ <h1>Signed in</h1><p>You can close this tab and return to your terminal.</p></body></html>`;
82
+ function base64url(buf) {
83
+ return buf.toString("base64url");
84
+ }
85
+ function generatePkce() {
86
+ const verifier = base64url(randomBytes(32));
87
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
88
+ return { verifier, challenge };
89
+ }
90
+ function generateState() {
91
+ return base64url(randomBytes(24));
92
+ }
93
+ function redirectUriFor(port) {
94
+ return `http://127.0.0.1:${port}/callback`;
95
+ }
96
+ function buildAuthorizeUrl(webUrl, requestId) {
97
+ const base = webUrl.replace(/\/+$/, "");
98
+ return `${base}/auth/native?request=${encodeURIComponent(requestId)}`;
99
+ }
100
+ function normalizeWebUrl(raw) {
101
+ let u;
102
+ try {
103
+ u = new URL(raw);
104
+ } catch {
105
+ return null;
106
+ }
107
+ if (u.protocol !== "https:" && u.protocol !== "http:" || u.username || u.password) return null;
108
+ return u.origin + u.pathname.replace(/\/+$/, "");
109
+ }
110
+ function resolveWebUrl(apiUrl, flag, env = process.env) {
111
+ const explicit = flag || env["HISAABO_WEB_URL"];
112
+ if (explicit) return normalizeWebUrl(explicit);
113
+ if (apiUrl.replace(/\/+$/, "") === HOSTED_API_URL) return HOSTED_WEB_URL;
114
+ return null;
115
+ }
116
+ function browserCommand(url, platform = process.platform) {
117
+ if (!/^https?:\/\//i.test(url)) throw new Error("Refusing to open a non-http(s) URL");
118
+ if (platform === "darwin") return { cmd: "open", args: [url] };
119
+ if (platform === "win32") return { cmd: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
120
+ return { cmd: "xdg-open", args: [url] };
121
+ }
122
+ function openBrowser(url) {
123
+ return new Promise((resolve2) => {
124
+ let spec;
125
+ try {
126
+ spec = browserCommand(url);
127
+ } catch {
128
+ resolve2(false);
129
+ return;
130
+ }
131
+ try {
132
+ const child = spawn(spec.cmd, spec.args, { stdio: "ignore", detached: true });
133
+ child.once("error", () => resolve2(false));
134
+ child.once("spawn", () => {
135
+ child.unref();
136
+ resolve2(true);
137
+ });
138
+ } catch {
139
+ resolve2(false);
140
+ }
141
+ });
142
+ }
143
+ function parseCallback(method, rawUrl, host, port, expectedState) {
144
+ if (method !== "GET" || !rawUrl) return null;
145
+ if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) return null;
146
+ let u;
147
+ try {
148
+ u = new URL(rawUrl, `http://127.0.0.1:${port}`);
149
+ } catch {
150
+ return null;
53
151
  }
54
- return parsed.origin + parsed.pathname.replace(/\/$/, "");
152
+ if (u.pathname !== "/callback") return null;
153
+ const code = u.searchParams.get("code");
154
+ const state = u.searchParams.get("state");
155
+ if (!code || !state || code.length > 512 || state !== expectedState) return null;
156
+ return { code, state };
157
+ }
158
+ function startCallbackServer(expectedState, timeoutMs = CALLBACK_TIMEOUT_MS) {
159
+ return new Promise((resolveStart, rejectStart) => {
160
+ let settle;
161
+ const result = new Promise((resolve2, reject) => {
162
+ settle = { resolve: resolve2, reject };
163
+ });
164
+ result.catch(() => {
165
+ });
166
+ let done = false;
167
+ let timer;
168
+ let port = 0;
169
+ const server = createServer((req, res) => {
170
+ if (done) {
171
+ res.writeHead(404).end();
172
+ return;
173
+ }
174
+ const parsed = parseCallback(req.method, req.url, req.headers.host, port, expectedState);
175
+ if (!parsed) {
176
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
177
+ return;
178
+ }
179
+ done = true;
180
+ res.writeHead(200, {
181
+ "Content-Type": "text/html; charset=utf-8",
182
+ "Cache-Control": "no-store",
183
+ "Referrer-Policy": "no-referrer",
184
+ Connection: "close"
185
+ });
186
+ res.end(CALLBACK_PAGE, () => {
187
+ close();
188
+ settle.resolve(parsed);
189
+ });
190
+ });
191
+ function close() {
192
+ if (timer) clearTimeout(timer);
193
+ server.close();
194
+ server.closeAllConnections();
195
+ }
196
+ server.once("error", rejectStart);
197
+ server.listen(0, "127.0.0.1", () => {
198
+ port = server.address().port;
199
+ timer = setTimeout(() => {
200
+ if (done) return;
201
+ done = true;
202
+ close();
203
+ settle.reject(new Error("Timed out waiting for browser sign-in"));
204
+ }, timeoutMs);
205
+ timer.unref();
206
+ resolveStart({ port, result, close: () => {
207
+ done = true;
208
+ close();
209
+ } });
210
+ });
211
+ });
55
212
  }
213
+
214
+ // src/auth.ts
56
215
  async function loginWithToken(apiUrl, token) {
57
216
  const base = validateApiUrl(apiUrl);
58
217
  const client = new HisaaboClient({
@@ -73,13 +232,15 @@ async function loginWithToken(apiUrl, token) {
73
232
  fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
74
233
  return;
75
234
  }
76
- setConfig({ apiUrl: base, token });
77
- const authedClient = new HisaaboClient({
78
- apiUrl: base,
79
- token,
80
- tenantId: "",
81
- businessId: ""
82
- });
235
+ const businesses = await listBusinessesOrExit(base, token);
236
+ const selected = await selectBusiness(businesses);
237
+ persistSession(base, token, selected, user.tenantId);
238
+ success(`Authenticated as ${user.name ?? user.email} (${user.email}) via API key`);
239
+ console.log(" Active business: " + selected.name);
240
+ console.log(" Config saved to " + getConfigPath() + "\n");
241
+ }
242
+ async function listBusinessesOrExit(base, token) {
243
+ const authedClient = new HisaaboClient({ apiUrl: base, token, tenantId: "", businessId: "" });
83
244
  let businesses;
84
245
  try {
85
246
  businesses = await authedClient.business.list();
@@ -89,19 +250,24 @@ async function loginWithToken(apiUrl, token) {
89
250
  if (businesses.length === 0) {
90
251
  fatalError("No businesses found for this account.", EXIT.GENERAL);
91
252
  }
253
+ return businesses;
254
+ }
255
+ async function selectBusiness(businesses) {
92
256
  console.log("\n You have access to " + businesses.length + " business" + (businesses.length > 1 ? "es" : "") + ":\n");
93
257
  console.log(" # Business" + " ".repeat(22) + "GSTIN" + " ".repeat(15) + "Role");
94
258
  console.log(" " + "\u2500".repeat(58));
95
259
  businesses.forEach((b, i) => {
96
- const name = b.name.padEnd(26);
97
- const gstin = (b.gstin ?? "-").padEnd(19);
98
- console.log(` ${i + 1} ${name} ${gstin} ${b.gstRegistrationType ?? "member"}`);
260
+ const name = sanitizeTerminal(b.name).padEnd(26);
261
+ const gstin = sanitizeTerminal(b.gstin ?? "-").padEnd(19);
262
+ console.log(` ${i + 1} ${name} ${gstin} ${sanitizeTerminal(b.gstRegistrationType ?? "member")}`);
99
263
  });
100
264
  console.log();
101
265
  let selected = businesses[0];
102
- if (businesses.length > 1) {
103
- const readline14 = await import("readline");
104
- const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
266
+ if (businesses.length > 1 && !process.stdin.isTTY) {
267
+ warn(`Non-interactive login: using the first business (${sanitizeTerminal(businesses[0].name)}). Run "hisaabo switch" in a terminal to change.`);
268
+ } else if (businesses.length > 1) {
269
+ const readline8 = await import("readline");
270
+ const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
105
271
  const answer = await new Promise((resolve2) => {
106
272
  rl.question(" Select business [1]: ", resolve2);
107
273
  });
@@ -112,81 +278,71 @@ async function loginWithToken(apiUrl, token) {
112
278
  if (!selected) {
113
279
  fatalError("No business selected.", EXIT.GENERAL);
114
280
  }
281
+ return selected;
282
+ }
283
+ function persistSession(apiUrl, token, business, tenantId) {
284
+ clearConfig();
115
285
  setConfig({
116
- businessId: selected.id,
117
- businessName: selected.name,
118
- tenantId: selected.id,
286
+ apiUrl,
287
+ token,
288
+ businessId: business.id,
289
+ businessName: business.name,
290
+ // Only the tenant reported by the server; never guess from a business id.
291
+ tenantId: tenantId ?? void 0,
119
292
  tokenCreatedAt: Date.now()
120
293
  });
121
- success(`Authenticated as ${user.name ?? user.email} (${user.email}) via API key`);
122
- console.log(" Active business: " + selected.name);
123
- console.log(" Config saved to " + getConfigPath() + "\n");
124
294
  }
125
- async function login(apiUrl, email, password) {
126
- const base = validateApiUrl(apiUrl);
127
- const client = new HisaaboClient({
128
- apiUrl: base,
129
- token: "",
130
- tenantId: "",
131
- businessId: ""
295
+ async function loginWithBrowser(opts) {
296
+ const base = validateApiUrl(opts.apiUrl);
297
+ const webUrl = resolveWebUrl(base, opts.webUrl);
298
+ if (!webUrl) {
299
+ fatalError(
300
+ "Cannot determine the web app URL for this server. Pass --web-url <url> (or set HISAABO_WEB_URL).",
301
+ EXIT.USAGE
302
+ );
303
+ }
304
+ const { verifier, challenge } = generatePkce();
305
+ const state = generateState();
306
+ const listener = await startCallbackServer(state).catch((e) => {
307
+ return fatalError("Could not start the local callback server: " + String(e instanceof Error ? e.message : e), EXIT.GENERAL);
132
308
  });
309
+ const client = new HisaaboClient({ apiUrl: base, token: "", tenantId: "", businessId: "" });
133
310
  try {
134
- const result = await client.auth.login({ email, password });
135
- const authedClient = new HisaaboClient({
136
- apiUrl: base,
137
- token: result.sessionId,
138
- tenantId: "",
139
- businessId: ""
311
+ const started = await client.auth.nativeStart({
312
+ redirectUri: redirectUriFor(listener.port),
313
+ codeChallenge: challenge,
314
+ state
140
315
  });
141
- const businesses = await authedClient.business.list();
142
- if (businesses.length === 0) {
143
- fatalError("No businesses found for this account.", EXIT.GENERAL);
144
- }
145
- setConfig({
146
- apiUrl: base,
147
- token: result.sessionId
148
- });
149
- console.log("\n You have access to " + businesses.length + " business" + (businesses.length > 1 ? "es" : "") + ":\n");
150
- console.log(" # Business" + " ".repeat(22) + "GSTIN" + " ".repeat(15) + "Role");
151
- console.log(" " + "\u2500".repeat(58));
152
- businesses.forEach((b, i) => {
153
- const name = b.name.padEnd(26);
154
- const gstin = (b.gstin ?? "-").padEnd(19);
155
- console.log(` ${i + 1} ${name} ${gstin} ${b.gstRegistrationType ?? "member"}`);
156
- });
157
- console.log();
158
- let selected = businesses[0];
159
- if (businesses.length > 1) {
160
- const readline14 = await import("readline");
161
- const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
162
- const answer = await new Promise((resolve2) => {
163
- rl.question(" Select business [1]: ", resolve2);
164
- });
165
- rl.close();
166
- const idx = parseInt(answer.trim() || "1", 10) - 1;
167
- selected = businesses[Math.max(0, Math.min(idx, businesses.length - 1))];
168
- }
169
- if (!selected) {
170
- fatalError("No business selected.", EXIT.GENERAL);
171
- }
172
- setConfig({
173
- businessId: selected.id,
174
- businessName: selected.name,
175
- tenantId: selected.id,
176
- // fallback; real tenantId may differ
177
- tokenCreatedAt: Date.now()
316
+ const url = buildAuthorizeUrl(webUrl, started.requestId);
317
+ console.log("\n Opening your browser to sign in to Hisaabo...");
318
+ console.log(" If it does not open, visit this URL:\n\n " + url + "\n");
319
+ console.log(" Waiting for sign-in (times out in 5 minutes)...");
320
+ if (!await openBrowser(url)) warn("Could not open a browser automatically; open the URL above manually.");
321
+ const callback = await listener.result;
322
+ const session = await client.auth.nativeExchange({
323
+ requestId: started.requestId,
324
+ code: callback.code,
325
+ codeVerifier: verifier
178
326
  });
179
- success(`Active business: ${selected.name}`);
327
+ const token = session.sessionToken;
328
+ const me = await new HisaaboClient({ apiUrl: base, token, tenantId: "", businessId: "" }).auth.me().catch(() => void 0);
329
+ const businesses = await listBusinessesOrExit(base, token);
330
+ const selected = await selectBusiness(businesses);
331
+ persistSession(base, token, selected, me?.tenantId);
332
+ success(`Signed in as ${session.user.name ?? session.user.email} (${session.user.email})`);
333
+ console.log(" Active business: " + sanitizeTerminal(selected.name));
180
334
  console.log(" Config saved to " + getConfigPath());
181
335
  console.log("\n You can switch businesses anytime with:");
182
- console.log(" hisaabo business switch\n");
336
+ console.log(" hisaabo switch\n");
183
337
  } catch (e) {
184
338
  if (e instanceof HisaaboApiError) {
185
339
  const err = e.hisaaboError;
186
- if (err.code === "unauthorized") fatalError("Invalid email or password.", EXIT.AUTH);
187
340
  if (err.code === "network_error") fatalError("Cannot reach server: " + err.message, EXIT.NETWORK);
341
+ if (err.code === "validation_failed") fatalError("Sign-in was rejected. Run `hisaabo login` again.", EXIT.AUTH);
188
342
  }
189
343
  fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
344
+ } finally {
345
+ listener.close();
190
346
  }
191
347
  }
192
348
  async function logout() {
@@ -212,7 +368,7 @@ async function whoami(jsonMode) {
212
368
  outputJSON({ user, business: { id: cfg.businessId, name: cfg.businessName }, apiUrl: cfg.apiUrl });
213
369
  return;
214
370
  }
215
- console.log(` User: ${user.name} <${user.email}>`);
371
+ console.log(` User: ${user.name ?? "-"} <${user.email}>`);
216
372
  console.log(` Role: ${user.role}`);
217
373
  console.log(` Business: ${cfg.businessName} (${cfg.businessId})`);
218
374
  console.log(` API: ${cfg.apiUrl}`);
@@ -230,90 +386,38 @@ async function whoami(jsonMode) {
230
386
  function ask(rl, q) {
231
387
  return new Promise((res) => rl.question(q, res));
232
388
  }
233
- function askSecret(prompt6) {
234
- return new Promise((resolve2) => {
235
- const rl = readline.createInterface({ input: process.stdin, terminal: true });
236
- process.stdout.write(prompt6);
237
- const chars = [];
238
- const cleanup = () => {
239
- process.stdin.removeListener("data", onData);
240
- process.stdin.setRawMode?.(false);
241
- process.stdin.pause();
242
- };
243
- const onSignal = () => {
244
- cleanup();
245
- process.exit(130);
246
- };
247
- process.once("SIGTERM", onSignal);
248
- process.once("SIGHUP", onSignal);
249
- const onData = (key) => {
250
- const ch = key.toString();
251
- if (ch === "\n" || ch === "\r") {
252
- process.removeListener("SIGTERM", onSignal);
253
- process.removeListener("SIGHUP", onSignal);
254
- cleanup();
255
- process.stdout.write("\n");
256
- rl.close();
257
- const result = chars.join("");
258
- chars.length = 0;
259
- resolve2(result);
260
- } else if (ch === "\x7F" || ch === "\b") {
261
- if (chars.length > 0) {
262
- chars.pop();
263
- process.stdout.write("\b \b");
264
- }
265
- } else if (ch === "") {
266
- cleanup();
267
- process.stdout.write("\n");
268
- process.exit(130);
269
- } else if (ch.charCodeAt(0) >= 32) {
270
- chars.push(ch);
271
- process.stdout.write("*");
272
- }
273
- };
274
- if (process.stdin.isTTY) {
275
- process.stdin.setRawMode?.(true);
276
- process.stdin.resume();
277
- process.stdin.on("data", onData);
278
- } else {
279
- rl.question("", (answer) => {
280
- rl.close();
281
- resolve2(answer.trim());
282
- });
283
- }
284
- });
389
+ async function readSecretFromStdin(flag) {
390
+ if (process.stdin.isTTY) {
391
+ fatalError(`${flag} expects the value piped on stdin`, EXIT.USAGE);
392
+ }
393
+ const chunks = [];
394
+ for await (const chunk of process.stdin) {
395
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
396
+ }
397
+ const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
398
+ if (!value) fatalError(`No value received on stdin for ${flag}`, EXIT.USAGE);
399
+ return value;
285
400
  }
286
401
  function registerAuthCommands(program2) {
287
- program2.command("login").description("Authenticate and configure your Hisaabo server").option("--api-url <url>", "Server URL").option("--email <email>", "Email address").option("--password <password>", "Password (visible in shell history \u2014 prefer interactive prompt)").option("--token <token>", "API key (visible in shell history \u2014 prefer HISAABO_TOKEN env var)").action(async (opts) => {
288
- let apiUrl = opts.apiUrl;
289
- if (opts.token) {
290
- if (!apiUrl) {
291
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
292
- console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
293
- const u = await ask(rl, " Server URL [http://localhost:3000]: ");
294
- rl.close();
295
- apiUrl = u.trim() || "http://localhost:3000";
296
- }
297
- await loginWithToken(apiUrl, opts.token);
298
- return;
299
- }
300
- let email = opts.email;
301
- let password = opts.password;
302
- if (!apiUrl || !email || !password) {
402
+ program2.command("login").description("Sign in through your browser (or with an API key via --token-stdin)").option("--api-url <url>", "Server URL (env: HISAABO_API_URL)").option("--web-url <url>", "Web app URL used for browser sign-in (env: HISAABO_WEB_URL)").option("--token <token>", "API key (deprecated: visible in process list and shell history; use --token-stdin)").option("--token-stdin", "Read an API key from stdin instead of using the browser").action(async (opts) => {
403
+ let apiUrl = opts.apiUrl ?? process.env["HISAABO_API_URL"];
404
+ if (opts.token) warn("--token is deprecated (visible to other users via the process list). Use --token-stdin.");
405
+ if (opts.tokenStdin) {
406
+ if (!apiUrl) fatalError("--api-url is required with --token-stdin", EXIT.USAGE);
407
+ opts.token = await readSecretFromStdin("--token-stdin");
408
+ }
409
+ if (!apiUrl) {
303
410
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
304
411
  console.log("\n Hisaabo CLI\n " + "\u2500".repeat(11) + "\n");
305
- if (!apiUrl) {
306
- const u = await ask(rl, " Server URL [http://localhost:3000]: ");
307
- apiUrl = u.trim() || "http://localhost:3000";
308
- }
309
- if (!email) email = (await ask(rl, " Email: ")).trim();
412
+ const u = await ask(rl, " Server URL [http://localhost:3000]: ");
310
413
  rl.close();
311
- if (!password) {
312
- password = await askSecret(" Password: ");
313
- }
314
- console.log("\n Tip: Generate an API key at Settings \u2192 API Keys for passwordless CLI access.\n");
414
+ apiUrl = u.trim() || "http://localhost:3000";
315
415
  }
316
- await login(apiUrl, email, password);
416
+ if (opts.token) {
417
+ await loginWithToken(apiUrl, opts.token);
418
+ return;
419
+ }
420
+ await loginWithBrowser({ apiUrl, webUrl: opts.webUrl });
317
421
  });
318
422
  program2.command("logout").description("Log out and clear saved credentials").option("--all", "Invalidate all sessions across all devices").action(async (opts) => {
319
423
  if (opts.all) {
@@ -390,19 +494,19 @@ function registerAuthCommands(program2) {
390
494
  function registerDashboardCommands(program2) {
391
495
  const dash = program2.command("dashboard").alias("dash").description("Business dashboard & analytics");
392
496
  dash.command("summary").description("Financial summary overview (FY to date)").option("--json", "JSON output").action(async (opts) => {
393
- const { dashboardCommand } = await import("./summary-H6U7O5GJ.js");
497
+ const { dashboardCommand } = await import("./summary-TYAL2D3Q.js");
394
498
  await dashboardCommand({ json: opts.json });
395
499
  });
396
500
  dash.command("sales-trend").description("Sales trend over time").option("--months <n>", "Number of months to show", (v) => parseInt(v, 10)).option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--granularity <g>", "daily | weekly | monthly").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
397
- const { dashboardSalesTrendCommand } = await import("./sales-trend-D6PQ7MHY.js");
501
+ const { dashboardSalesTrendCommand } = await import("./sales-trend-WCW6X5BI.js");
398
502
  await dashboardSalesTrendCommand(opts);
399
503
  });
400
504
  dash.command("top-outstanding").description("Parties with highest outstanding balances").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
401
- const { dashboardTopOutstandingCommand } = await import("./top-outstanding-JTQNGGW4.js");
505
+ const { dashboardTopOutstandingCommand } = await import("./top-outstanding-L4NRJ6NE.js");
402
506
  await dashboardTopOutstandingCommand(opts);
403
507
  });
404
508
  dash.command("top-customers").description("Top customers by revenue").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
405
- const { dashboardTopCustomersCommand } = await import("./top-customers-ATBN6RDI.js");
509
+ const { dashboardTopCustomersCommand } = await import("./top-customers-GMIS6GC3.js");
406
510
  await dashboardTopCustomersCommand({
407
511
  limit: opts.limit,
408
512
  from: opts.from,
@@ -414,7 +518,7 @@ function registerDashboardCommands(program2) {
414
518
  });
415
519
  });
416
520
  dash.command("top-items").description("Top selling items by revenue and quantity").option("--limit <n>", "Max rows to show", (v) => parseInt(v, 10)).option("--type <type>", "Item type filter (product | service)").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
417
- const { dashboardTopItemsCommand } = await import("./top-items-XXU6KYTC.js");
521
+ const { dashboardTopItemsCommand } = await import("./top-items-BK54JO3G.js");
418
522
  await dashboardTopItemsCommand({
419
523
  limit: opts.limit,
420
524
  type: opts.type,
@@ -427,7 +531,7 @@ function registerDashboardCommands(program2) {
427
531
  });
428
532
  });
429
533
  const expensesCmd = dash.command("expenses").description("Expenses broken down by category").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
430
- const { dashboardExpensesCommand } = await import("./expenses-S2YVA5UT.js");
534
+ const { dashboardExpensesCommand } = await import("./expenses-CU6JGDVX.js");
431
535
  await dashboardExpensesCommand({
432
536
  from: opts.from,
433
537
  to: opts.to,
@@ -439,7 +543,7 @@ function registerDashboardCommands(program2) {
439
543
  });
440
544
  expensesCmd.alias("expenses-by-category");
441
545
  dash.command("invoice-breakdown").description("Invoice count and amounts by status").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").action(async (opts) => {
442
- const { dashboardInvoiceBreakdownCommand } = await import("./invoice-breakdown-32XXAZDP.js");
546
+ const { dashboardInvoiceBreakdownCommand } = await import("./invoice-breakdown-3XXSYA77.js");
443
547
  await dashboardInvoiceBreakdownCommand({
444
548
  from: opts.from,
445
549
  to: opts.to,
@@ -449,7 +553,7 @@ function registerDashboardCommands(program2) {
449
553
  });
450
554
  });
451
555
  const plCmd = dash.command("profit-loss").description("Profit & Loss statement").option("--from <date>", "Start date (YYYY-MM-DD, default: FY start)").option("--to <date>", "End date (YYYY-MM-DD, default: today)").option("--this-month", "Scope to current calendar month").option("--this-fy", "Scope to current financial year").option("--json", "JSON output").action(async (opts) => {
452
- const { dashboardProfitLossCommand } = await import("./profit-loss-5GJBG3PL.js");
556
+ const { dashboardProfitLossCommand } = await import("./profit-loss-AOISAJ56.js");
453
557
  await dashboardProfitLossCommand({
454
558
  from: opts.from,
455
559
  to: opts.to,
@@ -460,11 +564,11 @@ function registerDashboardCommands(program2) {
460
564
  });
461
565
  plCmd.alias("pl");
462
566
  dash.command("receivables-aging").description("Receivables aging buckets (current / 1-30 / 31-60 / 61-90 / 90+)").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
463
- const { dashboardReceivablesAgingCommand } = await import("./receivables-aging-6A7XJKDT.js");
567
+ const { dashboardReceivablesAgingCommand } = await import("./receivables-aging-5JHFECGB.js");
464
568
  await dashboardReceivablesAgingCommand({ json: opts.json, format: opts.format });
465
569
  });
466
570
  dash.command("payment-modes").description("Payment mode breakdown (cash / UPI / bank transfer / etc.)").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
467
- const { dashboardPaymentModesCommand } = await import("./payment-modes-DY2ZEMK7.js");
571
+ const { dashboardPaymentModesCommand } = await import("./payment-modes-Z5WV3E3O.js");
468
572
  await dashboardPaymentModesCommand({
469
573
  from: opts.from,
470
574
  to: opts.to,
@@ -475,7 +579,7 @@ function registerDashboardCommands(program2) {
475
579
  });
476
580
  });
477
581
  dash.command("collection-efficiency").description("Collection rate, DSO, and aging breakdown").option("--from <date>", "Start date (YYYY-MM-DD)").option("--to <date>", "End date (YYYY-MM-DD)").option("--this-month", "Filter to current calendar month").option("--this-fy", "Filter to current financial year").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
478
- const { dashboardCollectionEfficiencyCommand } = await import("./collection-efficiency-DA5RWG3V.js");
582
+ const { dashboardCollectionEfficiencyCommand } = await import("./collection-efficiency-UF3AJPQB.js");
479
583
  await dashboardCollectionEfficiencyCommand({
480
584
  from: opts.from,
481
585
  to: opts.to,
@@ -486,7 +590,7 @@ function registerDashboardCommands(program2) {
486
590
  });
487
591
  });
488
592
  dash.command("monthly-comparison").description("Month-over-month comparison of sales, expenses, profit, and collections").option("--json", "JSON output").option("--format <format>", "table | tsv | csv").action(async (opts) => {
489
- const { dashboardMonthlyComparisonCommand } = await import("./monthly-comparison-IAUZ6SBJ.js");
593
+ const { dashboardMonthlyComparisonCommand } = await import("./monthly-comparison-3FFJT63K.js");
490
594
  await dashboardMonthlyComparisonCommand({ json: opts.json, format: opts.format });
491
595
  });
492
596
  }
@@ -528,8 +632,8 @@ async function invoiceListCommand(opts) {
528
632
  type: opts.type ?? null,
529
633
  status: opts.status ?? null,
530
634
  partyId: opts.partyId ?? null,
531
- fromDate: from ?? null,
532
- toDate: to ?? null,
635
+ fromDate: apiFrom(from) ?? null,
636
+ toDate: apiTo(to) ?? null,
533
637
  search: opts.search ?? null,
534
638
  sortBy: opts.sortBy ?? null,
535
639
  sortDir: opts.sortDir ?? null,
@@ -558,18 +662,18 @@ async function invoiceListCommand(opts) {
558
662
  const standardCols = [
559
663
  { key: "invoiceNumber", header: "#", width: 10 },
560
664
  { key: "partyName", header: "Party", width: 18 },
561
- { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
665
+ { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(v) },
562
666
  { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
563
667
  { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
564
668
  ];
565
669
  const wideCols = [
566
670
  { key: "invoiceNumber", header: "#", width: 10 },
567
671
  { key: "partyName", header: "Party", width: 18 },
568
- { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
569
- { key: "dueDate", header: "Due", width: 12, format: (v) => formatDate(v ? String(v) : null) },
672
+ { key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(v) },
673
+ { key: "dueDate", header: "Due", width: 12, format: (v) => formatDate(v) },
570
674
  { key: "totalAmount", header: "Amount (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
571
675
  { key: "amountPaid", header: "Paid (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
572
- { key: "balanceDue", header: "Balance (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
676
+ { key: "totalAdjusted", header: "Balance (\u20B9)", align: "right", width: 12, format: (_v, r) => formatAmount(String(parseFloat(r.totalAmount) - parseFloat(r.amountPaid) - parseFloat(r.totalAdjusted))) },
573
677
  { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
574
678
  ];
575
679
  const cols = tier === "narrow" ? narrowCols : tier === "wide" ? wideCols : standardCols;
@@ -616,6 +720,7 @@ async function invoiceGetCommand(id, opts) {
616
720
  };
617
721
  var line = line2, divider = divider2;
618
722
  const inv = await client.invoice.get(id);
723
+ if (!inv) fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
619
724
  if (opts.json) {
620
725
  outputJSON(inv);
621
726
  return;
@@ -631,7 +736,7 @@ async function invoiceGetCommand(id, opts) {
631
736
  process.stdout.write(`\u2502 ${hasColor() ? chalk.bold(title) : title}${" ".repeat(topPad)}${statusBadge2} \u2502
632
737
  `);
633
738
  divider2();
634
- line2(`Party: ${inv.partyName}`);
739
+ line2(`Party: ${inv.party?.name ?? "-"}`);
635
740
  line2(`Date: ${formatDate(inv.invoiceDate)}`);
636
741
  if (inv.dueDate) line2(`Due: ${formatDate(inv.dueDate)}`);
637
742
  if (inv.createdByName) line2(`Created: ${inv.createdByName}${inv.createdAt ? ` (${formatDate(inv.createdAt)})` : ""}`);
@@ -645,22 +750,20 @@ async function invoiceGetCommand(id, opts) {
645
750
  `);
646
751
  inv.lineItems.forEach((item, i) => {
647
752
  const idx = String(i + 1).padStart(2);
648
- const desc = item.description.slice(0, 18).padEnd(18);
753
+ const desc = item.itemName.slice(0, 18).padEnd(18);
649
754
  const qty = item.quantity.padStart(5);
650
755
  const rate = formatAmount(item.unitPrice).padStart(10);
651
756
  const tax = `${item.taxPercent}%`.padStart(5);
652
- const amt = formatAmount(item.amount).padStart(12);
757
+ const amt = formatAmount(item.totalAmount).padStart(12);
653
758
  process.stdout.write(`\u2502 ${idx} ${desc} ${qty} ${rate} ${tax} ${amt} \u2502
654
759
  `);
655
760
  });
656
761
  process.stdout.write(`\u2502 \u2502
657
762
  `);
658
763
  divider2();
659
- const subtotal = inv.lineItems.reduce((s, i) => s + parseFloat(i.amount), 0);
660
- const _tax = parseFloat(inv.totalAmount) - subtotal - parseFloat(inv.roundOff ?? "0") + parseFloat(inv.invoiceDiscount ?? "0");
661
- line2(`Subtotal:`, formatAmount(String(subtotal)).padStart(16));
662
- if (parseFloat(inv.invoiceDiscount ?? "0") !== 0)
663
- line2(`Discount:`, ("-" + formatAmount(inv.invoiceDiscount)).padStart(16));
764
+ line2(`Subtotal:`, formatAmount(inv.subtotal).padStart(16));
765
+ if (parseFloat(inv.discountAmount) !== 0)
766
+ line2(`Discount:`, ("-" + formatAmount(inv.discountAmount)).padStart(16));
664
767
  if (inv.charges && inv.charges.length > 0) {
665
768
  inv.charges.forEach((c) => line2(`${c.label}:`, formatAmount(c.amount).padStart(16)));
666
769
  }
@@ -672,7 +775,9 @@ async function invoiceGetCommand(id, opts) {
672
775
  line2(`Paid:`, formatAmount(inv.amountPaid).padStart(16));
673
776
  if (inv.totalAdjusted && parseFloat(inv.totalAdjusted) > 0)
674
777
  line2(`Adjusted:`, ("-" + formatAmount(inv.totalAdjusted)).padStart(16));
675
- const balance = inv.totalAdjusted && parseFloat(inv.totalAdjusted) > 0 ? String(parseFloat(inv.totalAmount) - parseFloat(inv.amountPaid) - parseFloat(inv.totalAdjusted)) : inv.balanceDue;
778
+ const balance = String(
779
+ parseFloat(inv.totalAmount) - parseFloat(inv.amountPaid) - (inv.totalAdjusted ? parseFloat(inv.totalAdjusted) : 0)
780
+ );
676
781
  line2(`Balance:`, formatAmount(balance).padStart(16));
677
782
  if (inv.status === "adjusted")
678
783
  line2(`(Settled via credit note / sales return)`);
@@ -700,6 +805,9 @@ async function invoiceGetCommand(id, opts) {
700
805
 
701
806
  // src/commands/invoice/create.ts
702
807
  import * as readline2 from "readline";
808
+ function isDeliveryMethod(v) {
809
+ return deliveryMethods.includes(v);
810
+ }
703
811
  async function prompt(rl, question) {
704
812
  return new Promise((resolve2) => rl.question(question, resolve2));
705
813
  }
@@ -759,7 +867,7 @@ async function invoiceCreateCommand(opts) {
759
867
  unitPrice = items.data[0].salePrice;
760
868
  lineItems.push({
761
869
  itemId: items.data[0].id,
762
- description: items.data[0].name,
870
+ itemName: items.data[0].name,
763
871
  quantity: qty,
764
872
  unitPrice,
765
873
  taxPercent: items.data[0].taxPercent
@@ -773,13 +881,13 @@ async function invoiceCreateCommand(opts) {
773
881
  if (matched) {
774
882
  lineItems.push({
775
883
  itemId: matched.id,
776
- description: matched.name,
884
+ itemName: matched.name,
777
885
  quantity: qty,
778
886
  unitPrice,
779
887
  taxPercent: matched.taxPercent
780
888
  });
781
889
  } else {
782
- lineItems.push({ description: itemName, quantity: qty, unitPrice });
890
+ lineItems.push({ itemName, quantity: qty, unitPrice });
783
891
  }
784
892
  }
785
893
  }
@@ -825,7 +933,7 @@ async function invoiceCreateCommand(opts) {
825
933
  const amount = parseFloat(qty) * parseFloat(unitPrice) * (1 + parseFloat(taxPercent) / 100) * (1 - parseFloat(discountPercent) / 100);
826
934
  console.log(` > ${description} x${qty} @${formatAmount(unitPrice)} ${taxPercent}% tax = ${formatAmount(String(amount))}
827
935
  `);
828
- lineItems.push({ itemId, description, quantity: qty, unitPrice, taxPercent, discountPercent });
936
+ lineItems.push({ itemId, itemName: description, quantity: qty, unitPrice, taxPercent, discountPercent });
829
937
  itemNum++;
830
938
  }
831
939
  rl.close();
@@ -874,6 +982,9 @@ async function invoiceCreateCommand(opts) {
874
982
  process.exit(EXIT.SUCCESS);
875
983
  }
876
984
  }
985
+ if (deliveryMethod !== void 0 && !isDeliveryMethod(deliveryMethod)) {
986
+ fatalError(`--delivery must be one of: ${deliveryMethods.join(", ")}.`, EXIT.USAGE);
987
+ }
877
988
  const invoice = await client.invoice.create({
878
989
  partyId,
879
990
  type: invoiceType,
@@ -913,6 +1024,7 @@ async function invoiceStatusCommand(id, status, opts) {
913
1024
  }
914
1025
  try {
915
1026
  const before = await client.invoice.get(id);
1027
+ if (!before) fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
916
1028
  const updated = await client.invoice.updateStatus(id, status);
917
1029
  if (opts.json) {
918
1030
  outputJSON(updated);
@@ -938,14 +1050,16 @@ async function invoiceStatusCommand(id, status, opts) {
938
1050
  import * as fs from "fs";
939
1051
  import * as path from "path";
940
1052
  async function invoicePdfCommand(id, opts) {
1053
+ requireUuid(id, "invoice id");
941
1054
  const cfg = requireAuth();
942
1055
  const client = new HisaaboClient(cfg);
943
1056
  let invoiceNumber = id;
944
1057
  try {
945
1058
  const inv = await client.invoice.get(id);
946
- invoiceNumber = inv.invoiceNumber;
1059
+ if (inv) invoiceNumber = inv.invoiceNumber;
947
1060
  } catch {
948
1061
  }
1062
+ const fileName = `${safeFilename(invoiceNumber, "invoice")}.pdf`;
949
1063
  const pdfUrl = `${cfg.apiUrl}/api/invoice/${id}/pdf`;
950
1064
  try {
951
1065
  const res = await fetch(pdfUrl, {
@@ -954,24 +1068,33 @@ async function invoicePdfCommand(id, opts) {
954
1068
  "x-business-id": cfg.businessId,
955
1069
  "x-tenant-id": cfg.tenantId,
956
1070
  "x-client-type": "cli"
957
- }
1071
+ },
1072
+ signal: AbortSignal.timeout(requestTimeoutMs())
958
1073
  });
959
1074
  if (!res.ok) {
960
1075
  fatalError(`Failed to download PDF: HTTP ${res.status}`, EXIT.GENERAL);
961
1076
  }
1077
+ const contentType = res.headers.get("content-type") ?? "";
1078
+ if (!/^application\/pdf\b/i.test(contentType)) {
1079
+ fatalError(`Unexpected response type: ${contentType || "none"} (expected application/pdf)`, EXIT.GENERAL);
1080
+ }
1081
+ const declared = Number(res.headers.get("content-length") ?? "0");
1082
+ if (declared > MAX_DOWNLOAD_BYTES) {
1083
+ fatalError("PDF too large to download", EXIT.GENERAL);
1084
+ }
962
1085
  const buffer = await res.arrayBuffer();
963
1086
  const bytes = Buffer.from(buffer);
964
1087
  let outputPath;
965
1088
  if (opts.output) {
966
1089
  if (fs.existsSync(opts.output) && fs.statSync(opts.output).isDirectory()) {
967
- outputPath = path.join(opts.output, `${invoiceNumber}.pdf`);
1090
+ outputPath = path.join(opts.output, fileName);
968
1091
  } else {
969
1092
  outputPath = opts.output;
970
1093
  }
971
1094
  } else {
972
- outputPath = `${invoiceNumber}.pdf`;
1095
+ outputPath = fileName;
973
1096
  }
974
- fs.writeFileSync(outputPath, bytes);
1097
+ writeFileSafe(outputPath, bytes, { magic: "%PDF-" });
975
1098
  success(`Saved: ${outputPath} (${Math.round(bytes.length / 1024)} KB)`);
976
1099
  if (opts.open) {
977
1100
  const openPkg = await import("open");
@@ -989,23 +1112,13 @@ async function invoicePdfCommand(id, opts) {
989
1112
  }
990
1113
 
991
1114
  // src/commands/invoice/delete.ts
992
- import * as readline3 from "readline";
993
1115
  async function invoiceDeleteCommand(id, opts) {
994
1116
  const cfg = requireAuth();
995
1117
  const client = new HisaaboClient(cfg);
996
1118
  try {
997
1119
  const inv = await client.invoice.get(id);
998
- if (!opts.yes && process.stdin.isTTY) {
999
- const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1000
- const answer = await new Promise((resolve2) => {
1001
- rl.question(` Delete ${inv.invoiceNumber} (${inv.partyName}, ${inv.totalAmount})? (y/N): `, resolve2);
1002
- });
1003
- rl.close();
1004
- if (answer.trim().toLowerCase() !== "y") {
1005
- console.log(" Cancelled.");
1006
- process.exit(0);
1007
- }
1008
- }
1120
+ if (!inv) fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
1121
+ await confirmOrExit(` Delete ${inv.invoiceNumber} (${inv.party?.name ?? "-"}, ${inv.totalAmount})?`, opts);
1009
1122
  const result = await client.invoice.delete(id);
1010
1123
  if (opts.json) {
1011
1124
  outputJSON(result);
@@ -1131,6 +1244,7 @@ async function partyGetCommand(id, opts) {
1131
1244
  const client = new HisaaboClient(cfg);
1132
1245
  try {
1133
1246
  const party = await client.party.get(id);
1247
+ if (!party) fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1134
1248
  if (opts.json) {
1135
1249
  outputJSON(party);
1136
1250
  return;
@@ -1162,7 +1276,7 @@ async function partyGetCommand(id, opts) {
1162
1276
  }
1163
1277
 
1164
1278
  // src/commands/party/create.ts
1165
- import * as readline4 from "readline";
1279
+ import * as readline3 from "readline";
1166
1280
  async function prompt2(rl, q) {
1167
1281
  return new Promise((resolve2) => rl.question(q, resolve2));
1168
1282
  }
@@ -1178,7 +1292,7 @@ async function partyCreateCommand(opts) {
1178
1292
  let city = opts.city;
1179
1293
  let category = opts.category;
1180
1294
  if (!isNonInteractive) {
1181
- const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1295
+ const rl = readline3.createInterface({ input: process.stdin, output: process.stdout });
1182
1296
  console.log("\n New Party\n " + "\u2500".repeat(30) + "\n");
1183
1297
  if (!type) {
1184
1298
  const t = await prompt2(rl, " Type (customer/supplier) [customer]: ");
@@ -1228,23 +1342,13 @@ async function partyCreateCommand(opts) {
1228
1342
  }
1229
1343
 
1230
1344
  // src/commands/party/delete.ts
1231
- import * as readline5 from "readline";
1232
1345
  async function partyDeleteCommand(id, opts) {
1233
1346
  const cfg = requireAuth();
1234
1347
  const client = new HisaaboClient(cfg);
1235
1348
  try {
1236
1349
  const party = await client.party.get(id);
1237
- if (!opts.yes && process.stdin.isTTY) {
1238
- const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1239
- const answer = await new Promise((resolve2) => {
1240
- rl.question(` Delete ${party.name}? (y/N): `, resolve2);
1241
- });
1242
- rl.close();
1243
- if (answer.trim().toLowerCase() !== "y") {
1244
- console.log(" Cancelled.");
1245
- process.exit(0);
1246
- }
1247
- }
1350
+ if (!party) fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1351
+ await confirmOrExit(` Delete ${party.name}?`, opts);
1248
1352
  const result = await client.party.delete(id);
1249
1353
  if (opts.json) {
1250
1354
  outputJSON(result);
@@ -1269,8 +1373,8 @@ async function partyLedgerCommand(partyId, opts) {
1269
1373
  const client = new HisaaboClient(cfg);
1270
1374
  try {
1271
1375
  const result = await client.party.ledger(partyId, {
1272
- fromDate: opts.from,
1273
- toDate: opts.to,
1376
+ fromDate: apiFrom(opts.from),
1377
+ toDate: apiTo(opts.to),
1274
1378
  page: opts.page ?? 1,
1275
1379
  limit: opts.limit ?? 50
1276
1380
  });
@@ -1279,23 +1383,203 @@ async function partyLedgerCommand(partyId, opts) {
1279
1383
  return;
1280
1384
  }
1281
1385
  console.log(`
1282
- Ledger: ${result.partyName} (${result.partyType})`);
1386
+ Ledger: ${partyId}`);
1283
1387
  console.log(" " + "\u2550".repeat(60));
1284
1388
  console.log(` Opening Balance: ${formatINR(result.openingBalance)}
1285
1389
  `);
1286
1390
  const cols = [
1287
1391
  { key: "date", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
1288
- { key: "description", header: "Description", width: 25 },
1392
+ { key: "documentNumber", header: "Number", width: 25 },
1289
1393
  { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1290
1394
  { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1291
- { key: "balance", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1292
- { key: "referenceType", header: "Type", width: 10 }
1395
+ { key: "runningBalance", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
1396
+ { key: "type", header: "Type", width: 10 }
1293
1397
  ];
1294
- if (opts.format === "tsv") outputTSV(result.entries, cols);
1295
- else if (opts.format === "csv") outputCSV(result.entries, cols);
1296
- else outputTable(result.entries, cols);
1398
+ if (opts.format === "tsv") outputTSV(result.data, cols);
1399
+ else if (opts.format === "csv") outputCSV(result.data, cols);
1400
+ else outputTable(result.data, cols);
1401
+ const closingBalance = result.data[result.data.length - 1]?.runningBalance ?? result.openingBalance;
1402
+ console.log(`
1403
+ Closing Balance: ${formatINR(closingBalance)}
1404
+ `);
1405
+ } catch (e) {
1406
+ if (e instanceof HisaaboApiError) {
1407
+ const err = e.hisaaboError;
1408
+ if (err.code === "not_found") fatalError(`Party not found: ${partyId}`, EXIT.NOT_FOUND);
1409
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1410
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1411
+ }
1412
+ fatalError(String(e instanceof Error ? e.message : e));
1413
+ }
1414
+ }
1415
+
1416
+ // src/commands/party/update.ts
1417
+ async function partyUpdateCommand(id, opts) {
1418
+ const cfg = requireAuth();
1419
+ const client = new HisaaboClient(cfg);
1420
+ const data = {};
1421
+ if (opts.name !== void 0) data.name = opts.name;
1422
+ if (opts.phone !== void 0) data.phone = opts.phone;
1423
+ if (opts.email !== void 0) data.email = opts.email;
1424
+ if (opts.gstin !== void 0) data.gstin = opts.gstin;
1425
+ if (opts.billingAddress !== void 0) data.billingAddress = opts.billingAddress;
1426
+ if (opts.city !== void 0) data.city = opts.city;
1427
+ if (opts.state !== void 0) data.state = opts.state;
1428
+ if (opts.pincode !== void 0) data.pincode = opts.pincode;
1429
+ if (opts.category !== void 0) data.category = opts.category;
1430
+ if (opts.creditPeriod !== void 0) data.creditPeriodDays = parseInt(opts.creditPeriod, 10);
1431
+ if (opts.creditLimit !== void 0) data.creditLimit = opts.creditLimit;
1432
+ if (Object.keys(data).length === 0) {
1433
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
1434
+ }
1435
+ try {
1436
+ const result = await client.party.update(id, data);
1437
+ if (opts.json) {
1438
+ outputJSON(result);
1439
+ return;
1440
+ }
1441
+ success(`Updated party: ${result.name}`);
1442
+ console.log(` ID: ${result.id}
1443
+ `);
1444
+ } catch (e) {
1445
+ if (e instanceof HisaaboApiError) {
1446
+ const err = e.hisaaboError;
1447
+ if (err.code === "not_found") fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1448
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1449
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1450
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1451
+ }
1452
+ fatalError(String(e instanceof Error ? e.message : e));
1453
+ }
1454
+ }
1455
+
1456
+ // src/commands/party/stats.ts
1457
+ async function partyStatsCommand(id, opts) {
1458
+ const cfg = requireAuth();
1459
+ const client = new HisaaboClient(cfg);
1460
+ try {
1461
+ const result = await client.party.getStats({ id });
1462
+ if (opts.json) {
1463
+ outputJSON(result);
1464
+ return;
1465
+ }
1466
+ console.log(`
1467
+ Party Stats: ${id}`);
1468
+ console.log(" " + "\u2500".repeat(40));
1469
+ console.log(` Invoices: ${result.invoiceCount}`);
1470
+ console.log(` Payments: ${result.paymentCount}`);
1471
+ console.log();
1472
+ } catch (e) {
1473
+ if (e instanceof HisaaboApiError) {
1474
+ const err = e.hisaaboError;
1475
+ if (err.code === "not_found") fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1476
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1477
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1478
+ }
1479
+ fatalError(String(e instanceof Error ? e.message : e));
1480
+ }
1481
+ }
1482
+
1483
+ // src/commands/party/top-items.ts
1484
+ async function partyTopItemsCommand(id, opts) {
1485
+ const cfg = requireAuth();
1486
+ const client = new HisaaboClient(cfg);
1487
+ try {
1488
+ const result = await client.party.topItems({ partyId: id });
1489
+ if (opts.json) {
1490
+ outputJSON(result);
1491
+ return;
1492
+ }
1493
+ const items = result;
1494
+ console.log(`
1495
+ Top Items for Party: ${id}
1496
+ `);
1497
+ const cols = [
1498
+ { key: "itemName", header: "Item", width: 30 },
1499
+ { key: "totalQuantity", header: "Quantity", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
1500
+ { key: "totalAmount", header: "Revenue (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) }
1501
+ ];
1502
+ if (opts.format === "tsv") outputTSV(items, cols);
1503
+ else if (opts.format === "csv") outputCSV(items, cols);
1504
+ else outputTable(items, cols);
1505
+ console.log();
1506
+ } catch (e) {
1507
+ if (e instanceof HisaaboApiError) {
1508
+ const err = e.hisaaboError;
1509
+ if (err.code === "not_found") fatalError(`Party not found: ${id}`, EXIT.NOT_FOUND);
1510
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1511
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1512
+ }
1513
+ fatalError(String(e instanceof Error ? e.message : e));
1514
+ }
1515
+ }
1516
+
1517
+ // src/commands/party/merge.ts
1518
+ async function partyMergeCommand(sourceId, targetId, opts) {
1519
+ const cfg = requireAuth();
1520
+ const client = new HisaaboClient(cfg);
1521
+ await confirmOrExit(` Merge party ${sourceId} into ${targetId}? All invoices and payments will be moved. This cannot be undone.`, opts);
1522
+ try {
1523
+ const result = await client.party.merge({ sourceId, targetId });
1524
+ if (opts.json) {
1525
+ outputJSON(result);
1526
+ return;
1527
+ }
1528
+ success(`Merged into ${targetId}`);
1529
+ } catch (e) {
1530
+ if (e instanceof HisaaboApiError) {
1531
+ const err = e.hisaaboError;
1532
+ if (err.code === "not_found") fatalError(`Party not found`, EXIT.NOT_FOUND);
1533
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1534
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1535
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1536
+ }
1537
+ fatalError(String(e instanceof Error ? e.message : e));
1538
+ }
1539
+ }
1540
+
1541
+ // src/commands/party/ledger-report.ts
1542
+ async function partyLedgerReportCommand(partyId, opts) {
1543
+ const cfg = requireAuth();
1544
+ const client = new HisaaboClient(cfg);
1545
+ let from = opts.from;
1546
+ let to = opts.to;
1547
+ if (opts.thisFy) {
1548
+ from = fyStart();
1549
+ to = todayISO();
1550
+ } else if (opts.thisMonth) {
1551
+ from = monthStart();
1552
+ to = monthEnd();
1553
+ }
1554
+ try {
1555
+ const result = await client.party.ledgerReport({ partyId, fromDate: apiFrom(from), toDate: apiTo(to) });
1556
+ if (!result) fatalError(`Party not found: ${partyId}`, EXIT.NOT_FOUND);
1557
+ if (opts.json) {
1558
+ outputJSON(result);
1559
+ return;
1560
+ }
1561
+ const entries = result.entries;
1297
1562
  console.log(`
1298
- Closing Balance: ${formatINR(result.closingBalance)}
1563
+ Ledger Report: ${result.party.name}`);
1564
+ if (from || to) {
1565
+ console.log(` Period: ${from ?? "start"} \u2192 ${to ?? "today"}`);
1566
+ }
1567
+ console.log(" " + "\u2550".repeat(72) + "\n");
1568
+ const cols = [
1569
+ { key: "date", header: "Date", width: 13, format: (v) => formatDate(String(v ?? "")) },
1570
+ { key: "type", header: "Type", width: 12 },
1571
+ { key: "number", header: "Number", width: 14 },
1572
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1573
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
1574
+ { key: "runningBalance", header: "Balance (\u20B9)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) }
1575
+ ];
1576
+ if (opts.format === "tsv") outputTSV(entries, cols);
1577
+ else if (opts.format === "csv") outputCSV(entries, cols);
1578
+ else outputTable(entries, cols);
1579
+ console.log();
1580
+ console.log(` Total Debit: \u20B9${formatAmount(result.summary.totalDebit)}`);
1581
+ console.log(` Total Credit: \u20B9${formatAmount(result.summary.totalCredit)}`);
1582
+ console.log(` Closing Balance: \u20B9${formatAmount(result.summary.closingBalance)}
1299
1583
  `);
1300
1584
  } catch (e) {
1301
1585
  if (e instanceof HisaaboApiError) {
@@ -1334,6 +1618,21 @@ function registerPartyCommands(program2) {
1334
1618
  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) => {
1335
1619
  await partyLedgerCommand(partyId, opts);
1336
1620
  });
1621
+ party.command("update <id>").description("Update a party (only the options you pass are changed)").option("--json", "JSON output").option("--name <name>", "Party name").option("--phone <phone>", "Phone number").option("--email <email>", "Email address").option("--gstin <gstin>", "GSTIN").option("--billing-address <address>", "Billing address").option("--city <city>", "City").option("--state <state>", "State").option("--pincode <pincode>", "Pincode").option("--category <cat>", "Category").option("--credit-period <days>", "Credit period in days").option("--credit-limit <amount>", "Credit limit").action(async (id, opts) => {
1622
+ await partyUpdateCommand(id, opts);
1623
+ });
1624
+ party.command("stats <id>").description("Show invoice and payment counts for a party").option("--json", "JSON output").action(async (id, opts) => {
1625
+ await partyStatsCommand(id, { json: opts.json });
1626
+ });
1627
+ party.command("top-items <id>").description("Show the items a party buys most").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (id, opts) => {
1628
+ await partyTopItemsCommand(id, { json: opts.json, format: opts.format });
1629
+ });
1630
+ party.command("merge <sourceId> <targetId>").description("Merge one party into another (moves all invoices and payments)").option("--json", "JSON output").option("-y, --yes", "Skip confirmation").action(async (sourceId, targetId, opts) => {
1631
+ await partyMergeCommand(sourceId, targetId, { yes: opts.yes, json: opts.json });
1632
+ });
1633
+ party.command("ledger-report <partyId>").description("Detailed party ledger report with running balance and totals").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--from <date>", "From date (YYYY-MM-DD)").option("--to <date>", "To date (YYYY-MM-DD)").option("--this-month", "Current month").option("--this-fy", "Current financial year to date").action(async (partyId, opts) => {
1634
+ await partyLedgerReportCommand(partyId, opts);
1635
+ });
1337
1636
  }
1338
1637
 
1339
1638
  // src/commands/item/list.ts
@@ -1405,7 +1704,10 @@ async function itemListCommand(opts) {
1405
1704
  }
1406
1705
 
1407
1706
  // src/commands/item/create.ts
1408
- import * as readline6 from "readline";
1707
+ import * as readline4 from "readline";
1708
+ function isUnit(v) {
1709
+ return units.includes(v);
1710
+ }
1409
1711
  async function prompt3(rl, q) {
1410
1712
  return new Promise((resolve2) => rl.question(q, resolve2));
1411
1713
  }
@@ -1423,7 +1725,7 @@ async function itemCreateCommand(opts) {
1423
1725
  let category = opts.category;
1424
1726
  let itemType = opts.type ?? "product";
1425
1727
  if (!isNonInteractive) {
1426
- const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
1728
+ const rl = readline4.createInterface({ input: process.stdin, output: process.stdout });
1427
1729
  console.log("\n New Item\n " + "\u2500".repeat(30) + "\n");
1428
1730
  if (!name) name = (await prompt3(rl, " Name: ")).trim();
1429
1731
  const typeStr = await prompt3(rl, " Type (product/service) [product]: ");
@@ -1447,6 +1749,7 @@ async function itemCreateCommand(opts) {
1447
1749
  rl.close();
1448
1750
  }
1449
1751
  if (!name) fatalError("--name is required", EXIT.USAGE);
1752
+ if (!isUnit(unit)) fatalError(`--unit must be one of: ${units.join(", ")}.`, EXIT.USAGE);
1450
1753
  try {
1451
1754
  const item = await client.item.create({
1452
1755
  name,
@@ -1478,23 +1781,13 @@ async function itemCreateCommand(opts) {
1478
1781
  }
1479
1782
 
1480
1783
  // src/commands/item/delete.ts
1481
- import * as readline7 from "readline";
1482
1784
  async function itemDeleteCommand(id, opts) {
1483
1785
  const cfg = requireAuth();
1484
1786
  const client = new HisaaboClient(cfg);
1485
1787
  try {
1486
1788
  const item = await client.item.get(id);
1487
- if (!opts.yes && process.stdin.isTTY) {
1488
- const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
1489
- const answer = await new Promise((resolve2) => {
1490
- rl.question(` Delete ${item.name}? (y/N): `, resolve2);
1491
- });
1492
- rl.close();
1493
- if (answer.trim().toLowerCase() !== "y") {
1494
- console.log(" Cancelled.");
1495
- process.exit(0);
1496
- }
1497
- }
1789
+ if (!item) fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1790
+ await confirmOrExit(` Delete ${item.name}?`, opts);
1498
1791
  const result = await client.item.delete(id);
1499
1792
  if (opts.json) {
1500
1793
  outputJSON(result);
@@ -1523,7 +1816,7 @@ async function itemStockCommand(id, adjustment, opts) {
1523
1816
  try {
1524
1817
  const updated = await client.item.adjustStock({
1525
1818
  itemId: id,
1526
- adjustment,
1819
+ quantity: adjustment,
1527
1820
  reason: opts.reason
1528
1821
  });
1529
1822
  if (opts.json) {
@@ -1532,7 +1825,7 @@ async function itemStockCommand(id, adjustment, opts) {
1532
1825
  }
1533
1826
  const adj = parseFloat(adjustment);
1534
1827
  const dir = adj >= 0 ? "+" : "";
1535
- success(`Stock adjusted: ${updated.name} ${dir}${formatAmount(adjustment)} \u2192 ${formatAmount(updated.stockQuantity)}`);
1828
+ success(`Stock adjusted: ${id} ${dir}${formatAmount(adjustment)} \u2192 ${formatAmount(updated.newStock)}`);
1536
1829
  } catch (e) {
1537
1830
  if (e instanceof HisaaboApiError) {
1538
1831
  const err = e.hisaaboError;
@@ -1545,11 +1838,545 @@ async function itemStockCommand(id, adjustment, opts) {
1545
1838
  }
1546
1839
  }
1547
1840
 
1548
- // src/bin/registrars/item.ts
1549
- function registerItemCommands(program2) {
1550
- const item = program2.command("item").description("Item / product management");
1551
- 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) => {
1552
- await itemListCommand({
1841
+ // src/commands/item/update.ts
1842
+ async function itemUpdateCommand(id, opts) {
1843
+ const cfg = requireAuth();
1844
+ const client = new HisaaboClient(cfg);
1845
+ const data = {};
1846
+ if (opts.name !== void 0) data.name = opts.name;
1847
+ if (opts.salePrice !== void 0) data.salePrice = opts.salePrice;
1848
+ if (opts.purchasePrice !== void 0) data.purchasePrice = opts.purchasePrice;
1849
+ if (opts.taxPercent !== void 0) data.taxPercent = opts.taxPercent;
1850
+ if (opts.hsn !== void 0) data.hsn = opts.hsn;
1851
+ if (opts.unit !== void 0) {
1852
+ if (!units.includes(opts.unit)) {
1853
+ fatalError(`--unit must be one of: ${units.join(", ")}.`, EXIT.USAGE);
1854
+ }
1855
+ data.unit = opts.unit;
1856
+ }
1857
+ if (opts.category !== void 0) data.category = opts.category;
1858
+ if (opts.sku !== void 0) data.sku = opts.sku;
1859
+ if (opts.lowStockAlert !== void 0) data.lowStockAlert = opts.lowStockAlert;
1860
+ if (Object.keys(data).length === 0) {
1861
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
1862
+ }
1863
+ try {
1864
+ const result = await client.item.update(id, data);
1865
+ if (opts.json) {
1866
+ outputJSON(result);
1867
+ return;
1868
+ }
1869
+ success(`Updated item: ${result.name}`);
1870
+ console.log(` ID: ${result.id}
1871
+ `);
1872
+ } catch (e) {
1873
+ if (e instanceof HisaaboApiError) {
1874
+ const err = e.hisaaboError;
1875
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1876
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1877
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1878
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1879
+ }
1880
+ fatalError(String(e instanceof Error ? e.message : e));
1881
+ }
1882
+ }
1883
+
1884
+ // src/commands/item/merge.ts
1885
+ async function itemMergeCommand(sourceId, targetId, opts) {
1886
+ const cfg = requireAuth();
1887
+ const client = new HisaaboClient(cfg);
1888
+ await confirmOrExit(` Merge ${sourceId} into ${targetId}? Invoice history will be moved.`, opts);
1889
+ const conversionFactor = opts.conversionFactor ? parseFloat(opts.conversionFactor) : void 0;
1890
+ try {
1891
+ const result = await client.item.merge({ sourceId, targetId, stockConversionFactor: conversionFactor });
1892
+ if (opts.json) {
1893
+ outputJSON(result);
1894
+ return;
1895
+ }
1896
+ success(`Merged ${sourceId} into ${targetId}`);
1897
+ } catch (e) {
1898
+ if (e instanceof HisaaboApiError) {
1899
+ const err = e.hisaaboError;
1900
+ if (err.code === "not_found") fatalError(`Item not found`, EXIT.NOT_FOUND);
1901
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1902
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
1903
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1904
+ }
1905
+ fatalError(String(e instanceof Error ? e.message : e));
1906
+ }
1907
+ }
1908
+
1909
+ // src/commands/item/history-options.ts
1910
+ var HISTORY_PERIODS = ["6m", "1y", "all"];
1911
+ function parsePeriod(value) {
1912
+ if (value === void 0) return void 0;
1913
+ if (HISTORY_PERIODS.includes(value)) return value;
1914
+ throw new Error(`Invalid --period "${value}". Use one of: ${HISTORY_PERIODS.join(", ")}`);
1915
+ }
1916
+
1917
+ // src/commands/item/price-history.ts
1918
+ async function itemPriceHistoryCommand(id, opts) {
1919
+ const cfg = requireAuth();
1920
+ const client = new HisaaboClient(cfg);
1921
+ try {
1922
+ const result = await client.item.priceHistory({ id, period: parsePeriod(opts.period), limit: opts.limit });
1923
+ if (opts.json) {
1924
+ outputJSON(result);
1925
+ return;
1926
+ }
1927
+ const entries = result;
1928
+ console.log(`
1929
+ Price History: ${id}
1930
+ `);
1931
+ const cols = [
1932
+ { key: "invoiceDate", header: "Date", width: 13, format: (v) => formatDate(v) },
1933
+ { key: "invoiceNumber", header: "Invoice", width: 16 },
1934
+ { key: "invoiceType", header: "Type", width: 10 },
1935
+ { key: "unitPrice", header: "Unit Price (\u20B9)", align: "right", width: 16, format: (v) => v ? formatAmount(String(v)) : "-" },
1936
+ { key: "partyName", header: "Party", width: 18 }
1937
+ ];
1938
+ if (opts.format === "tsv") outputTSV(entries, cols);
1939
+ else if (opts.format === "csv") outputCSV(entries, cols);
1940
+ else outputTable(entries, cols);
1941
+ console.log();
1942
+ } catch (e) {
1943
+ if (e instanceof HisaaboApiError) {
1944
+ const err = e.hisaaboError;
1945
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1946
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1947
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1948
+ }
1949
+ fatalError(String(e instanceof Error ? e.message : e));
1950
+ }
1951
+ }
1952
+
1953
+ // src/commands/item/price-summary.ts
1954
+ async function itemPriceSummaryCommand(id, opts) {
1955
+ const cfg = requireAuth();
1956
+ const client = new HisaaboClient(cfg);
1957
+ if (opts.type !== void 0 && opts.type !== "sale" && opts.type !== "purchase") {
1958
+ fatalError(`Invalid --type "${opts.type}". Use: sale, purchase`, EXIT.USAGE);
1959
+ }
1960
+ try {
1961
+ const result = await client.item.priceSummary({
1962
+ id,
1963
+ period: parsePeriod(opts.period),
1964
+ unit: opts.unit,
1965
+ invoiceType: opts.type
1966
+ });
1967
+ if (opts.json) {
1968
+ outputJSON(result);
1969
+ return;
1970
+ }
1971
+ const { stats } = result;
1972
+ const money2 = (v) => v === null ? "-" : formatINR(v);
1973
+ console.log(`
1974
+ Price Summary: ${id}`);
1975
+ console.log(" " + "\u2500".repeat(40));
1976
+ console.log(` Series: ${result.invoiceType} prices per ${result.unit}, period ${result.period}`);
1977
+ console.log(` Lines: ${stats.count}`);
1978
+ console.log(` Latest: ${money2(stats.latest)}`);
1979
+ console.log(` Min: ${money2(stats.min)}`);
1980
+ console.log(` Max: ${money2(stats.max)}`);
1981
+ console.log(` Average: ${money2(stats.avg)}`);
1982
+ console.log();
1983
+ } catch (e) {
1984
+ if (e instanceof HisaaboApiError) {
1985
+ const err = e.hisaaboError;
1986
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1987
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
1988
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
1989
+ }
1990
+ fatalError(String(e instanceof Error ? e.message : e));
1991
+ }
1992
+ }
1993
+
1994
+ // src/commands/item/stock-movements.ts
1995
+ async function itemStockMovementsCommand(id, opts) {
1996
+ const cfg = requireAuth();
1997
+ const client = new HisaaboClient(cfg);
1998
+ try {
1999
+ const result = await client.item.stockMovements({ id, period: parsePeriod(opts.period), limit: opts.limit });
2000
+ if (opts.json) {
2001
+ outputJSON(result);
2002
+ return;
2003
+ }
2004
+ const entries = result;
2005
+ console.log(`
2006
+ Stock Movements: ${id}
2007
+ `);
2008
+ const cols = [
2009
+ { key: "invoiceDate", header: "Date", width: 13, format: (v) => formatDate(v) },
2010
+ { key: "invoiceNumber", header: "Invoice", width: 16 },
2011
+ { key: "direction", header: "Dir", width: 5 },
2012
+ { key: "quantity", header: "Qty", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
2013
+ { key: "partyName", header: "Party", width: 18 }
2014
+ ];
2015
+ if (opts.format === "tsv") outputTSV(entries, cols);
2016
+ else if (opts.format === "csv") outputCSV(entries, cols);
2017
+ else outputTable(entries, cols);
2018
+ console.log();
2019
+ } catch (e) {
2020
+ if (e instanceof HisaaboApiError) {
2021
+ const err = e.hisaaboError;
2022
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2023
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2024
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2025
+ }
2026
+ fatalError(String(e instanceof Error ? e.message : e));
2027
+ }
2028
+ }
2029
+
2030
+ // src/commands/item/stock-summary.ts
2031
+ async function itemStockSummaryCommand(id, opts) {
2032
+ const cfg = requireAuth();
2033
+ const client = new HisaaboClient(cfg);
2034
+ try {
2035
+ const result = await client.item.stockSummary({
2036
+ id,
2037
+ period: parsePeriod(opts.period),
2038
+ unit: opts.unit
2039
+ });
2040
+ if (opts.json) {
2041
+ outputJSON(result);
2042
+ return;
2043
+ }
2044
+ const { stats } = result;
2045
+ console.log(`
2046
+ Stock Summary: ${id}`);
2047
+ console.log(" " + "\u2500".repeat(40));
2048
+ console.log(` Unit: ${result.unit}, period ${result.period}`);
2049
+ console.log(` Movements: ${stats.count}`);
2050
+ console.log(` Total In: ${formatAmount(stats.totalIn)}`);
2051
+ console.log(` Total Out: ${formatAmount(stats.totalOut)}`);
2052
+ console.log(` Net: ${formatAmount(stats.net)}`);
2053
+ console.log();
2054
+ } catch (e) {
2055
+ if (e instanceof HisaaboApiError) {
2056
+ const err = e.hisaaboError;
2057
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2058
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2059
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2060
+ }
2061
+ fatalError(String(e instanceof Error ? e.message : e));
2062
+ }
2063
+ }
2064
+
2065
+ // src/commands/item/rename-unit.ts
2066
+ async function itemRenameUnitCommand(id, opts) {
2067
+ const cfg = requireAuth();
2068
+ const client = new HisaaboClient(cfg);
2069
+ if (!opts.old) fatalError("--old is required", EXIT.USAGE);
2070
+ if (!opts.new) fatalError("--new is required", EXIT.USAGE);
2071
+ try {
2072
+ const result = await client.item.renameUnit({ id, oldUnit: opts.old, newUnit: opts.new });
2073
+ if (opts.json) {
2074
+ outputJSON(result);
2075
+ return;
2076
+ }
2077
+ success(`Renamed unit '${opts.old}' to '${opts.new}' for item ${id}`);
2078
+ console.log();
2079
+ } catch (e) {
2080
+ if (e instanceof HisaaboApiError) {
2081
+ const err = e.hisaaboError;
2082
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2083
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2084
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2085
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2086
+ }
2087
+ fatalError(String(e instanceof Error ? e.message : e));
2088
+ }
2089
+ }
2090
+
2091
+ // src/commands/item/sales-stats.ts
2092
+ async function itemSalesStatsCommand(id, opts) {
2093
+ const cfg = requireAuth();
2094
+ const client = new HisaaboClient(cfg);
2095
+ try {
2096
+ const result = await client.item.salesStats({ id });
2097
+ if (opts.json) {
2098
+ outputJSON(result);
2099
+ return;
2100
+ }
2101
+ console.log(`
2102
+ Sales Stats: ${id}`);
2103
+ console.log(" " + "\u2500".repeat(40));
2104
+ console.log(` Total Sold: ${formatAmount(result.totalSaleQty)} units`);
2105
+ console.log(` Total Revenue: ${formatINR(result.totalSaleAmount)}`);
2106
+ console.log(` Avg Price: ${formatINR(result.avgNetPrice)}`);
2107
+ console.log(` Invoices: ${result.saleInvoiceCount}`);
2108
+ console.log();
2109
+ } catch (e) {
2110
+ if (e instanceof HisaaboApiError) {
2111
+ const err = e.hisaaboError;
2112
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2113
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2114
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2115
+ }
2116
+ fatalError(String(e instanceof Error ? e.message : e));
2117
+ }
2118
+ }
2119
+
2120
+ // src/commands/item/stock-history.ts
2121
+ async function itemStockHistoryCommand(id, opts) {
2122
+ const cfg = requireAuth();
2123
+ const client = new HisaaboClient(cfg);
2124
+ const page = opts.page ?? 1;
2125
+ const limit = opts.limit ?? 20;
2126
+ try {
2127
+ const result = await client.item.stockAdjustmentHistory({ itemId: id, page, limit });
2128
+ if (opts.json) {
2129
+ outputJSON(result);
2130
+ return;
2131
+ }
2132
+ const entries = result.data;
2133
+ const total = result.total;
2134
+ console.log(`
2135
+ Stock History: ${id}
2136
+ `);
2137
+ const cols = [
2138
+ { key: "adjustmentDate", header: "Date", width: 13, format: (v) => formatDate(v) },
2139
+ { key: "quantity", header: "Adjustment", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
2140
+ { key: "newStock", header: "Balance After", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
2141
+ { key: "reason", header: "Reason", width: 25 },
2142
+ { key: "createdByName", header: "By", width: 16 }
2143
+ ];
2144
+ if (opts.format === "tsv") outputTSV(entries, cols);
2145
+ else if (opts.format === "csv") outputCSV(entries, cols);
2146
+ else {
2147
+ outputTable(entries, cols);
2148
+ paginationFooter(page, limit, total);
2149
+ }
2150
+ console.log();
2151
+ } catch (e) {
2152
+ if (e instanceof HisaaboApiError) {
2153
+ const err = e.hisaaboError;
2154
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2155
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2156
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2157
+ }
2158
+ fatalError(String(e instanceof Error ? e.message : e));
2159
+ }
2160
+ }
2161
+
2162
+ // src/commands/item/switch-base-unit.ts
2163
+ async function itemSwitchBaseUnitCommand(id, opts) {
2164
+ const cfg = requireAuth();
2165
+ const client = new HisaaboClient(cfg);
2166
+ if (!opts.unit) {
2167
+ fatalError("--unit is required", EXIT.USAGE);
2168
+ }
2169
+ if (!opts.conversionFactor) {
2170
+ fatalError("--conversion-factor is required", EXIT.USAGE);
2171
+ }
2172
+ const conversionFactor = parseFloat(opts.conversionFactor);
2173
+ try {
2174
+ const result = await client.item.switchBaseUnit({ id, newUnit: opts.unit, conversionFactor });
2175
+ if (opts.json) {
2176
+ outputJSON(result);
2177
+ return;
2178
+ }
2179
+ success(`Switched base unit for item ${id} to: ${opts.unit}`);
2180
+ console.log();
2181
+ } catch (e) {
2182
+ if (e instanceof HisaaboApiError) {
2183
+ const err = e.hisaaboError;
2184
+ if (err.code === "not_found") fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
2185
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2186
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2187
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2188
+ }
2189
+ fatalError(String(e instanceof Error ? e.message : e));
2190
+ }
2191
+ }
2192
+
2193
+ // src/commands/item/low-stock-count.ts
2194
+ async function itemLowStockCountCommand(opts) {
2195
+ const cfg = requireAuth();
2196
+ const client = new HisaaboClient(cfg);
2197
+ try {
2198
+ const result = await client.item.lowStockCount();
2199
+ if (opts.json) {
2200
+ outputJSON(result);
2201
+ return;
2202
+ }
2203
+ const count = result;
2204
+ process.stdout.write(`
2205
+ ${count} item${count === 1 ? "" : "s"} below low-stock threshold
2206
+
2207
+ `);
2208
+ } catch (e) {
2209
+ if (e instanceof HisaaboApiError) {
2210
+ const err = e.hisaaboError;
2211
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2212
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2213
+ }
2214
+ fatalError(String(e instanceof Error ? e.message : e));
2215
+ }
2216
+ }
2217
+
2218
+ // src/commands/item/variants-list.ts
2219
+ async function itemVariantsListCommand(itemId, opts) {
2220
+ const cfg = requireAuth();
2221
+ const client = new HisaaboClient(cfg);
2222
+ try {
2223
+ const result = await client.item.listVariants({ itemId });
2224
+ if (opts.json) {
2225
+ outputJSON(result);
2226
+ return;
2227
+ }
2228
+ const variants = result;
2229
+ console.log(`
2230
+ Variants for item: ${itemId}
2231
+ `);
2232
+ const cols = [
2233
+ { key: "id", header: "ID", width: 12 },
2234
+ { key: "sku", header: "SKU", width: 14 },
2235
+ { key: "salePrice", header: "Sale (\u20B9)", align: "right", width: 12, format: (v) => v ? formatAmount(String(v)) : "-" },
2236
+ { key: "purchasePrice", header: "Purchase (\u20B9)", align: "right", width: 14, format: (v) => v ? formatAmount(String(v)) : "-" },
2237
+ { key: "stockQuantity", header: "Stock", align: "right", width: 10, format: (v) => formatAmount(String(v ?? "0")) },
2238
+ { key: "attributeValues", header: "Attributes", width: 20, format: (v) => v ? JSON.stringify(v) : "-" }
2239
+ ];
2240
+ if (opts.format === "tsv") outputTSV(variants, cols);
2241
+ else if (opts.format === "csv") outputCSV(variants, cols);
2242
+ else outputTable(variants, cols);
2243
+ console.log();
2244
+ } catch (e) {
2245
+ if (e instanceof HisaaboApiError) {
2246
+ const err = e.hisaaboError;
2247
+ if (err.code === "not_found") fatalError(`Item not found: ${itemId}`, EXIT.NOT_FOUND);
2248
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2249
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2250
+ }
2251
+ fatalError(String(e instanceof Error ? e.message : e));
2252
+ }
2253
+ }
2254
+
2255
+ // src/commands/item/variants-create.ts
2256
+ async function itemVariantsCreateCommand(itemId, opts) {
2257
+ const cfg = requireAuth();
2258
+ const client = new HisaaboClient(cfg);
2259
+ let parsedAttributes;
2260
+ if (opts.attributes) {
2261
+ try {
2262
+ const raw = JSON.parse(opts.attributes);
2263
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw) || !Object.values(raw).every((v) => typeof v === "string")) {
2264
+ throw new Error("not a string map");
2265
+ }
2266
+ parsedAttributes = raw;
2267
+ } catch {
2268
+ fatalError(`--attributes must be a JSON object of string values, e.g. '{"size":"M"}'`, EXIT.USAGE);
2269
+ }
2270
+ }
2271
+ if (parsedAttributes === void 0) {
2272
+ fatalError(`--attributes is required (JSON object, e.g. '{"size":"M"}')`, EXIT.USAGE);
2273
+ }
2274
+ try {
2275
+ const result = await client.item.createVariant({
2276
+ itemId,
2277
+ variant: {
2278
+ attributeValues: parsedAttributes,
2279
+ sku: opts.sku,
2280
+ salePrice: opts.salePrice,
2281
+ purchasePrice: opts.purchasePrice,
2282
+ stockQuantity: opts.stock,
2283
+ lowStockAlert: opts.lowStockAlert
2284
+ }
2285
+ });
2286
+ if (opts.json) {
2287
+ outputJSON(result);
2288
+ return;
2289
+ }
2290
+ success(`Created variant: ${result.id}`);
2291
+ if (result.sku) console.log(` SKU: ${result.sku}`);
2292
+ console.log();
2293
+ } catch (e) {
2294
+ if (e instanceof HisaaboApiError) {
2295
+ const err = e.hisaaboError;
2296
+ if (err.code === "not_found") fatalError(`Item not found: ${itemId}`, EXIT.NOT_FOUND);
2297
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2298
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2299
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2300
+ }
2301
+ fatalError(String(e instanceof Error ? e.message : e));
2302
+ }
2303
+ }
2304
+
2305
+ // src/commands/item/variants-update.ts
2306
+ async function itemVariantsUpdateCommand(variantId, opts) {
2307
+ const cfg = requireAuth();
2308
+ const client = new HisaaboClient(cfg);
2309
+ let parsedAttributes;
2310
+ if (opts.attributes) {
2311
+ try {
2312
+ const raw = JSON.parse(opts.attributes);
2313
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw) || !Object.values(raw).every((v) => typeof v === "string")) {
2314
+ throw new Error("not a string map");
2315
+ }
2316
+ parsedAttributes = raw;
2317
+ } catch {
2318
+ fatalError(`--attributes must be a JSON object of string values, e.g. '{"size":"M"}'`, EXIT.USAGE);
2319
+ }
2320
+ }
2321
+ const data = {};
2322
+ if (opts.sku !== void 0) data.sku = opts.sku;
2323
+ if (opts.salePrice !== void 0) data.salePrice = opts.salePrice;
2324
+ if (opts.purchasePrice !== void 0) data.purchasePrice = opts.purchasePrice;
2325
+ if (opts.stock !== void 0) data.stockQuantity = opts.stock;
2326
+ if (opts.lowStockAlert !== void 0) data.lowStockAlert = opts.lowStockAlert;
2327
+ if (parsedAttributes !== void 0) data.attributeValues = parsedAttributes;
2328
+ if (Object.keys(data).length === 0) {
2329
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
2330
+ }
2331
+ try {
2332
+ const result = await client.item.updateVariant({ variantId, data });
2333
+ if (opts.json) {
2334
+ outputJSON(result);
2335
+ return;
2336
+ }
2337
+ success(`Updated variant: ${variantId}`);
2338
+ console.log();
2339
+ } catch (e) {
2340
+ if (e instanceof HisaaboApiError) {
2341
+ const err = e.hisaaboError;
2342
+ if (err.code === "not_found") fatalError(`Variant not found: ${variantId}`, EXIT.NOT_FOUND);
2343
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2344
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
2345
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2346
+ }
2347
+ fatalError(String(e instanceof Error ? e.message : e));
2348
+ }
2349
+ }
2350
+
2351
+ // src/commands/item/variants-delete.ts
2352
+ async function itemVariantsDeleteCommand(variantId, opts) {
2353
+ const cfg = requireAuth();
2354
+ const client = new HisaaboClient(cfg);
2355
+ await confirmOrExit(` Delete variant ${variantId}?`, opts);
2356
+ try {
2357
+ const result = await client.item.deleteVariant({ variantId });
2358
+ if (opts.json) {
2359
+ outputJSON(result);
2360
+ return;
2361
+ }
2362
+ success(`Deleted variant: ${variantId}`);
2363
+ } catch (e) {
2364
+ if (e instanceof HisaaboApiError) {
2365
+ const err = e.hisaaboError;
2366
+ if (err.code === "not_found") fatalError(`Variant not found: ${variantId}`, EXIT.NOT_FOUND);
2367
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2368
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
2369
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2370
+ }
2371
+ fatalError(String(e instanceof Error ? e.message : e));
2372
+ }
2373
+ }
2374
+
2375
+ // src/bin/registrars/item.ts
2376
+ function registerItemCommands(program2) {
2377
+ const item = program2.command("item").description("Item / product management");
2378
+ 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) => {
2379
+ await itemListCommand({
1553
2380
  json: opts.json,
1554
2381
  format: opts.format,
1555
2382
  search: opts.search,
@@ -1565,6 +2392,7 @@ function registerItemCommands(program2) {
1565
2392
  const client = new HisaaboClient(cfg);
1566
2393
  try {
1567
2394
  const it = await client.item.get(id);
2395
+ if (!it) fatalError(`Item not found: ${id}`, EXIT.NOT_FOUND);
1568
2396
  if (opts.json) {
1569
2397
  outputJSON(it);
1570
2398
  return;
@@ -1606,6 +2434,63 @@ function registerItemCommands(program2) {
1606
2434
  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) => {
1607
2435
  await itemStockCommand(id, adjustment, { json: opts.json, reason: opts.reason });
1608
2436
  });
2437
+ item.command("update <id>").description("Update an item (only the options you pass are changed)").option("--json", "JSON output").option("--name <name>", "Item name").option("--sale-price <price>", "Sale price").option("--purchase-price <price>", "Purchase price").option("--tax <percent>", "Tax percentage").option("--hsn <code>", "HSN code").option("--unit <unit>", "Unit (pcs, kg, etc.)").option("--category <cat>", "Category").option("--sku <sku>", "SKU").option("--low-stock-alert <qty>", "Low-stock alert threshold").action(async (id, opts) => {
2438
+ await itemUpdateCommand(id, {
2439
+ json: opts.json,
2440
+ name: opts.name,
2441
+ salePrice: opts.salePrice,
2442
+ purchasePrice: opts.purchasePrice,
2443
+ taxPercent: opts.tax,
2444
+ hsn: opts.hsn,
2445
+ unit: opts.unit,
2446
+ category: opts.category,
2447
+ sku: opts.sku,
2448
+ lowStockAlert: opts.lowStockAlert
2449
+ });
2450
+ });
2451
+ item.command("merge <sourceId> <targetId>").description("Merge one item into another (moves invoice history)").option("--json", "JSON output").option("--conversion-factor <n>", "Stock conversion factor from source to target unit").option("-y, --yes", "Skip confirmation").action(async (sourceId, targetId, opts) => {
2452
+ await itemMergeCommand(sourceId, targetId, { conversionFactor: opts.conversionFactor, yes: opts.yes, json: opts.json });
2453
+ });
2454
+ item.command("price-history <id>").description("Show past invoiced prices for an item").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--period <period>", "Time window: 6m, 1y, all (default: all)").option("--limit <n>", "Max lines to return (1-500, default 50)", parseInt).action(async (id, opts) => {
2455
+ await itemPriceHistoryCommand(id, { json: opts.json, format: opts.format, period: opts.period, limit: opts.limit });
2456
+ });
2457
+ item.command("price-summary <id>").description("Min / max / average / latest invoiced price over a whole period").option("--json", "JSON output").option("--period <period>", "Time window: 6m, 1y, all (default: all)").option("--unit <unit>", "Display unit (base or alt unit; default: base unit)").option("--type <type>", "Price series: sale or purchase (default: sale)").action(async (id, opts) => {
2458
+ await itemPriceSummaryCommand(id, { json: opts.json, period: opts.period, unit: opts.unit, type: opts.type });
2459
+ });
2460
+ item.command("stock-movements <id>").description("Show invoice-driven stock movements (in/out) for an item").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--period <period>", "Time window: 6m, 1y, all (default: all)").option("--limit <n>", "Max movements to return (1-500, default 50)", parseInt).action(async (id, opts) => {
2461
+ await itemStockMovementsCommand(id, { json: opts.json, format: opts.format, period: opts.period, limit: opts.limit });
2462
+ });
2463
+ item.command("stock-summary <id>").description("Total stock in / out / net change over a whole period").option("--json", "JSON output").option("--period <period>", "Time window: 6m, 1y, all (default: all)").option("--unit <unit>", "Display unit (base or alt unit; default: base unit)").action(async (id, opts) => {
2464
+ await itemStockSummaryCommand(id, { json: opts.json, period: opts.period, unit: opts.unit });
2465
+ });
2466
+ item.command("rename-unit <id>").description("Rename one of an item's units").option("--json", "JSON output").requiredOption("--old <unit>", "Current unit name").requiredOption("--new <unit>", "New unit name").action(async (id, opts) => {
2467
+ await itemRenameUnitCommand(id, { old: opts.old, new: opts.new, json: opts.json });
2468
+ });
2469
+ item.command("sales-stats <id>").description("Show lifetime sales totals for an item").option("--json", "JSON output").action(async (id, opts) => {
2470
+ await itemSalesStatsCommand(id, { json: opts.json });
2471
+ });
2472
+ item.command("stock-history <id>").description("Show stock adjustment history for an item").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 (id, opts) => {
2473
+ await itemStockHistoryCommand(id, { json: opts.json, format: opts.format, page: opts.page, limit: opts.limit });
2474
+ });
2475
+ item.command("switch-base-unit <id>").description("Switch an item's base unit").option("--json", "JSON output").requiredOption("--unit <unit>", "New base unit").requiredOption("--conversion-factor <n>", "How many new base units make one old base unit").action(async (id, opts) => {
2476
+ await itemSwitchBaseUnitCommand(id, { unit: opts.unit, conversionFactor: opts.conversionFactor, json: opts.json });
2477
+ });
2478
+ item.command("low-stock-count").description("Count items below their low-stock threshold").option("--json", "JSON output").action(async (opts) => {
2479
+ await itemLowStockCountCommand({ json: opts.json });
2480
+ });
2481
+ const variants = item.command("variants").description("Item variant management");
2482
+ variants.command("list <itemId>").description("List an item's variants").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").action(async (itemId, opts) => {
2483
+ await itemVariantsListCommand(itemId, { json: opts.json, format: opts.format });
2484
+ });
2485
+ variants.command("create <itemId>").description("Create a variant").option("--json", "JSON output").requiredOption("--attributes <json>", `Attributes as a JSON object of strings, e.g. '{"size":"M"}'`).option("--sku <sku>", "SKU").option("--sale-price <price>", "Sale price").option("--purchase-price <price>", "Purchase price").option("--stock <qty>", "Opening stock quantity").option("--low-stock-alert <qty>", "Low-stock alert threshold").action(async (itemId, opts) => {
2486
+ await itemVariantsCreateCommand(itemId, opts);
2487
+ });
2488
+ variants.command("update <variantId>").description("Update a variant (only the options you pass are changed)").option("--json", "JSON output").option("--attributes <json>", "Attributes as a JSON object of strings").option("--sku <sku>", "SKU").option("--sale-price <price>", "Sale price").option("--purchase-price <price>", "Purchase price").option("--stock <qty>", "Stock quantity").option("--low-stock-alert <qty>", "Low-stock alert threshold").action(async (variantId, opts) => {
2489
+ await itemVariantsUpdateCommand(variantId, opts);
2490
+ });
2491
+ variants.command("delete <variantId>").description("Delete a variant").option("--json", "JSON output").option("-y, --yes", "Skip confirmation").action(async (variantId, opts) => {
2492
+ await itemVariantsDeleteCommand(variantId, { yes: opts.yes, json: opts.json });
2493
+ });
1609
2494
  }
1610
2495
 
1611
2496
  // src/commands/payment/list.ts
@@ -1617,8 +2502,8 @@ async function paymentListCommand(opts) {
1617
2502
  try {
1618
2503
  const result = await client.payment.list({
1619
2504
  partyId: opts.partyId ?? null,
1620
- fromDate: opts.from ?? null,
1621
- toDate: opts.to ?? null,
2505
+ fromDate: apiFrom(opts.from) ?? null,
2506
+ toDate: apiTo(opts.to) ?? null,
1622
2507
  page,
1623
2508
  limit
1624
2509
  });
@@ -1655,11 +2540,87 @@ async function paymentListCommand(opts) {
1655
2540
  }
1656
2541
 
1657
2542
  // src/commands/payment/create.ts
1658
- import * as readline8 from "readline";
2543
+ import * as readline5 from "readline";
2544
+
2545
+ // src/resolve-party.ts
2546
+ var PAGE_SIZE = 100;
2547
+ var MAX_LISTED = 10;
2548
+ var norm = (s) => s.trim().toLowerCase();
2549
+ function partyOptionError(opts) {
2550
+ if (opts.partyId !== void 0 && opts.party !== void 0) {
2551
+ return "--party-id and --party are mutually exclusive; pass only one";
2552
+ }
2553
+ if (opts.party !== void 0 && norm(opts.party) === "") {
2554
+ return "--party must not be empty";
2555
+ }
2556
+ return null;
2557
+ }
2558
+ async function resolvePartyByName(client, name) {
2559
+ const wanted = norm(name);
2560
+ if (wanted === "") return { ok: false, reason: "usage", message: "--party must not be empty" };
2561
+ const matches = [];
2562
+ let seen = 0;
2563
+ for (let page = 1; ; page++) {
2564
+ const res = await client.party.list({ search: name.trim(), limit: PAGE_SIZE, page });
2565
+ for (const p of res.data) if (norm(p.name) === wanted) matches.push({ id: p.id, name: p.name });
2566
+ seen += res.data.length;
2567
+ if (res.data.length < PAGE_SIZE || seen >= res.total) break;
2568
+ }
2569
+ if (matches.length === 1) return { ok: true, party: matches[0] };
2570
+ if (matches.length === 0) {
2571
+ return {
2572
+ ok: false,
2573
+ reason: "not_found",
2574
+ message: `No party named "${name.trim()}". Check the spelling, or pass --party-id (find one with: hisaabo party list --search <text>)`
2575
+ };
2576
+ }
2577
+ const listed = matches.slice(0, MAX_LISTED).map((p) => ` ${p.name} ${p.id}`);
2578
+ if (matches.length > MAX_LISTED) listed.push(` ...and ${matches.length - MAX_LISTED} more`);
2579
+ return {
2580
+ ok: false,
2581
+ reason: "usage",
2582
+ message: `${matches.length} parties are named "${name.trim()}"; pass --party-id to choose one:
2583
+ ${listed.join("\n")}`
2584
+ };
2585
+ }
2586
+
2587
+ // src/commands/payment/create.ts
1659
2588
  async function prompt4(rl, q) {
1660
2589
  return new Promise((resolve2) => rl.question(q, resolve2));
1661
2590
  }
2591
+ function buildTdsAllocations(opts, netAmount) {
2592
+ if (opts.tdsAmount === void 0) {
2593
+ if (opts.tdsSection !== void 0 || opts.tdsRate !== void 0) {
2594
+ fatalError("--tds-section and --tds-rate require --tds-amount", EXIT.USAGE);
2595
+ }
2596
+ return void 0;
2597
+ }
2598
+ if (!opts.invoiceId) {
2599
+ fatalError("--invoice-id is required when recording TDS", EXIT.USAGE);
2600
+ }
2601
+ if (!moneyStringSchema.safeParse(netAmount).success || !money.isPositive(netAmount)) {
2602
+ fatalError("--amount must be a positive amount with at most 2 decimals (e.g. 9000.00)", EXIT.USAGE);
2603
+ }
2604
+ if (!moneyStringSchema.safeParse(opts.tdsAmount).success || !money.isPositive(opts.tdsAmount)) {
2605
+ fatalError("--tds-amount must be a positive amount with at most 2 decimals (e.g. 1000.00)", EXIT.USAGE);
2606
+ }
2607
+ const allocation = {
2608
+ invoiceId: opts.invoiceId,
2609
+ amount: money.add(netAmount, opts.tdsAmount),
2610
+ tdsAmount: opts.tdsAmount,
2611
+ tdsSectionCode: opts.tdsSection,
2612
+ tdsRate: opts.tdsRate
2613
+ };
2614
+ const parsed = paymentAllocationSchema.safeParse(allocation);
2615
+ if (!parsed.success) {
2616
+ const problems = parsed.error.issues.map((issue) => `${issue.path.join(".") || "allocation"}: ${issue.message}`).join("; ");
2617
+ fatalError(`Invalid TDS options: ${problems}`, EXIT.USAGE);
2618
+ }
2619
+ return [allocation];
2620
+ }
1662
2621
  async function paymentCreateCommand(opts) {
2622
+ const partyOptError = partyOptionError(opts);
2623
+ if (partyOptError) fatalError(partyOptError, EXIT.USAGE);
1663
2624
  const cfg = requireAuth();
1664
2625
  const client = new HisaaboClient(cfg);
1665
2626
  const isNonInteractive = !process.stdin.isTTY || opts.yes;
@@ -1670,8 +2631,13 @@ async function paymentCreateCommand(opts) {
1670
2631
  let paymentDate = opts.date ?? todayISO();
1671
2632
  let notes = opts.notes;
1672
2633
  try {
2634
+ if (opts.party !== void 0) {
2635
+ const resolved = await resolvePartyByName(client, opts.party);
2636
+ if (!resolved.ok) fatalError(resolved.message, resolved.reason === "not_found" ? EXIT.NOT_FOUND : EXIT.USAGE);
2637
+ partyId = resolved.party.id;
2638
+ }
1673
2639
  if (!isNonInteractive) {
1674
- const rl = readline8.createInterface({ input: process.stdin, output: process.stdout });
2640
+ const rl = readline5.createInterface({ input: process.stdin, output: process.stdout });
1675
2641
  console.log("\n Record Payment\n " + "\u2500".repeat(30) + "\n");
1676
2642
  if (!partyId) {
1677
2643
  const search = await prompt4(rl, " Select Party:\n > Search: ");
@@ -1729,9 +2695,10 @@ async function paymentCreateCommand(opts) {
1729
2695
  rl.close();
1730
2696
  }
1731
2697
  }
1732
- if (!partyId) fatalError("--party-id is required", EXIT.USAGE);
2698
+ if (!partyId) fatalError("--party-id or --party is required", EXIT.USAGE);
1733
2699
  if (!amount) fatalError("--amount is required", EXIT.USAGE);
1734
2700
  if (!mode) mode = "cash";
2701
+ const allocations = buildTdsAllocations(opts, amount);
1735
2702
  const payment = await client.payment.create({
1736
2703
  partyId,
1737
2704
  amount,
@@ -1739,7 +2706,8 @@ async function paymentCreateCommand(opts) {
1739
2706
  referenceNumber,
1740
2707
  paymentDate,
1741
2708
  notes,
1742
- invoiceId: opts.invoiceId
2709
+ invoiceId: opts.invoiceId,
2710
+ allocations
1743
2711
  });
1744
2712
  if (opts.json) {
1745
2713
  outputJSON(payment);
@@ -1758,24 +2726,13 @@ async function paymentCreateCommand(opts) {
1758
2726
  }
1759
2727
 
1760
2728
  // src/commands/payment/delete.ts
1761
- import * as readline9 from "readline";
1762
2729
  async function paymentDeleteCommand(id, opts) {
1763
2730
  const cfg = requireAuth();
1764
2731
  const client = new HisaaboClient(cfg);
1765
2732
  try {
1766
2733
  const payment = await client.payment.getById(id);
1767
2734
  if (!payment) fatalError(`Payment not found: ${id}`, EXIT.NOT_FOUND);
1768
- if (!opts.yes && process.stdin.isTTY) {
1769
- const rl = readline9.createInterface({ input: process.stdin, output: process.stdout });
1770
- const answer = await new Promise((resolve2) => {
1771
- rl.question(` Delete ${payment.paymentNumber} (${formatINR(payment.amount)})? (y/N): `, resolve2);
1772
- });
1773
- rl.close();
1774
- if (answer.trim().toLowerCase() !== "y") {
1775
- console.log(" Cancelled.");
1776
- process.exit(0);
1777
- }
1778
- }
2735
+ await confirmOrExit(` Delete ${payment.paymentNumber} (${formatINR(payment.amount)})?`, opts);
1779
2736
  const result = await client.payment.delete(id);
1780
2737
  if (opts.json) {
1781
2738
  outputJSON(result);
@@ -1800,7 +2757,7 @@ function registerPaymentCommands(program2) {
1800
2757
  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) => {
1801
2758
  await paymentListCommand(opts);
1802
2759
  });
1803
- 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) => {
2760
+ payment.command("create").description("Record a payment").option("--json", "JSON output").option("--party-id <id>", "Party UUID (not with --party)").option("--party <name>", "Party name, exact match ignoring case; fails if none or several match (not with --party-id)").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("--tds-amount <amount>", "TDS the customer withheld (--amount is then the NET cash received; needs --invoice-id)").option("--tds-section <code>", "TDS section code, e.g. 1023 or 1027 (see: hisaabo tds-section list)").option("--tds-rate <rate>", "TDS rate in percent, up to 2 decimals (e.g. 1 or 10.50); recorded as metadata").option("-y, --yes", "Skip confirmation").action(async (opts) => {
1804
2761
  await paymentCreateCommand({
1805
2762
  json: opts.json,
1806
2763
  partyId: opts.partyId,
@@ -1811,6 +2768,9 @@ function registerPaymentCommands(program2) {
1811
2768
  reference: opts.reference,
1812
2769
  date: opts.date,
1813
2770
  notes: opts.notes,
2771
+ tdsAmount: opts.tdsAmount,
2772
+ tdsSection: opts.tdsSection,
2773
+ tdsRate: opts.tdsRate,
1814
2774
  yes: opts.yes
1815
2775
  });
1816
2776
  });
@@ -1818,11 +2778,11 @@ function registerPaymentCommands(program2) {
1818
2778
  await paymentDeleteCommand(id, { yes: opts.yes, json: opts.json });
1819
2779
  });
1820
2780
  payment.command("get <id>").description("Get payment details").option("--json", "JSON output").action(async (id, opts) => {
1821
- const { paymentGetCommand } = await import("./get-ZV3SC2VY.js");
2781
+ const { paymentGetCommand } = await import("./get-KAOGGRJR.js");
1822
2782
  await paymentGetCommand(id, { json: opts.json });
1823
2783
  });
1824
2784
  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) => {
1825
- const { paymentUpdateCommand } = await import("./update-EK4NJWU4.js");
2785
+ const { paymentUpdateCommand } = await import("./update-EPNB2U74.js");
1826
2786
  await paymentUpdateCommand(id, {
1827
2787
  json: opts.json,
1828
2788
  amount: opts.amount,
@@ -1833,22 +2793,71 @@ function registerPaymentCommands(program2) {
1833
2793
  });
1834
2794
  });
1835
2795
  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) => {
1836
- const { paymentUnpaidInvoicesCommand } = await import("./unpaid-invoices-BTNQFWCH.js");
2796
+ const { paymentUnpaidInvoicesCommand } = await import("./unpaid-invoices-CEUFEYH7.js");
1837
2797
  await paymentUnpaidInvoicesCommand(partyId, { json: opts.json, format: opts.format });
1838
2798
  });
1839
2799
  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) => {
1840
- const { paymentUntrackedCommand } = await import("./untracked-PAMEDJ6Y.js");
2800
+ const { paymentUntrackedCommand } = await import("./untracked-T6DIDMDQ.js");
1841
2801
  await paymentUntrackedCommand({
1842
2802
  json: opts.json,
1843
2803
  format: opts.format,
1844
- page: opts.page,
1845
- limit: opts.limit
2804
+ page: opts.page,
2805
+ limit: opts.limit
2806
+ });
2807
+ });
2808
+ 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) => {
2809
+ const { paymentDefaultAccountCommand } = await import("./default-account-MR6O5LPT.js");
2810
+ await paymentDefaultAccountCommand({ json: opts.json, partyId: opts.partyId });
2811
+ });
2812
+ }
2813
+
2814
+ // src/commands/tds-section/list.ts
2815
+ async function tdsSectionListCommand(opts) {
2816
+ const cfg = requireAuth();
2817
+ const client = new HisaaboClient(cfg);
2818
+ try {
2819
+ const sections = await client.tdsSection.list({ includeInactive: opts.includeInactive ?? false });
2820
+ if (opts.json) {
2821
+ outputJSON(sections);
2822
+ return;
2823
+ }
2824
+ const cols = [
2825
+ { key: "sectionCode", header: "Code", width: 8 },
2826
+ { key: "sectionLabel", header: "Section", width: 70 },
2827
+ { key: "effectiveFrom", header: "Effective from", width: 15, format: (v) => formatDate(v) },
2828
+ { key: "status", header: "Status", width: 9 },
2829
+ { key: "version", header: "Ver", align: "right", width: 4 }
2830
+ ];
2831
+ if (opts.format === "tsv") outputTSV(sections, cols);
2832
+ else if (opts.format === "csv") outputCSV(sections, cols);
2833
+ else {
2834
+ console.log(`
2835
+ TDS sections (${sections.length})
2836
+ `);
2837
+ outputTable(sections, cols);
2838
+ console.log();
2839
+ }
2840
+ } catch (e) {
2841
+ if (e instanceof HisaaboApiError) {
2842
+ const err = e.hisaaboError;
2843
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
2844
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
2845
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
2846
+ }
2847
+ fatalError(String(e instanceof Error ? e.message : e));
2848
+ }
2849
+ }
2850
+
2851
+ // src/bin/registrars/tds-section.ts
2852
+ function registerTdsSectionCommands(program2) {
2853
+ const tdsSection = program2.command("tds-section").description("TDS sections available when recording customer receipts");
2854
+ tdsSection.command("list").description("List TDS section codes (use with: payment create --tds-section <code>)").option("--json", "JSON output").option("--format <format>", "Output format: table, tsv, csv").option("--include-inactive", "Include inactive sections").action(async (opts) => {
2855
+ await tdsSectionListCommand({
2856
+ json: opts.json,
2857
+ format: opts.format,
2858
+ includeInactive: opts.includeInactive
1846
2859
  });
1847
2860
  });
1848
- 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) => {
1849
- const { paymentDefaultAccountCommand } = await import("./default-account-2GMQ7ZA4.js");
1850
- await paymentDefaultAccountCommand({ json: opts.json, partyId: opts.partyId });
1851
- });
1852
2861
  }
1853
2862
 
1854
2863
  // src/commands/expense/list.ts
@@ -1859,9 +2868,9 @@ async function expenseListCommand(opts) {
1859
2868
  const limit = opts.limit ?? 20;
1860
2869
  try {
1861
2870
  const result = await client.expense.list({
1862
- category: opts.category ?? null,
1863
- fromDate: opts.from ?? null,
1864
- toDate: opts.to ?? null,
2871
+ category: opts.category,
2872
+ fromDate: apiFrom(opts.from),
2873
+ toDate: apiTo(opts.to),
1865
2874
  page,
1866
2875
  limit
1867
2876
  });
@@ -1929,23 +2938,12 @@ async function expenseCreateCommand(opts) {
1929
2938
  }
1930
2939
 
1931
2940
  // src/commands/expense/delete.ts
1932
- import * as readline10 from "readline";
1933
2941
  async function expenseDeleteCommand(id, opts) {
1934
2942
  const cfg = requireAuth();
1935
2943
  const client = new HisaaboClient(cfg);
1936
2944
  try {
1937
2945
  const _list = await client.expense.list({ page: 1, limit: 1 });
1938
- if (!opts.yes && process.stdin.isTTY) {
1939
- const rl = readline10.createInterface({ input: process.stdin, output: process.stdout });
1940
- const answer = await new Promise((resolve2) => {
1941
- rl.question(` Delete expense ${id}? (y/N): `, resolve2);
1942
- });
1943
- rl.close();
1944
- if (answer.trim().toLowerCase() !== "y") {
1945
- console.log(" Cancelled.");
1946
- process.exit(0);
1947
- }
1948
- }
2946
+ await confirmOrExit(` Delete expense ${id}?`, opts);
1949
2947
  const result = await client.expense.delete(id);
1950
2948
  if (opts.json) {
1951
2949
  outputJSON(result);
@@ -1985,7 +2983,7 @@ function registerExpenseCommands(program2) {
1985
2983
  await expenseDeleteCommand(id, { yes: opts.yes, json: opts.json });
1986
2984
  });
1987
2985
  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) => {
1988
- const { expenseUpdateCommand } = await import("./update-6ZMX2OYX.js");
2986
+ const { expenseUpdateCommand } = await import("./update-MFNOVS6D.js");
1989
2987
  await expenseUpdateCommand(id, {
1990
2988
  json: opts.json,
1991
2989
  amount: opts.amount,
@@ -1997,13 +2995,12 @@ function registerExpenseCommands(program2) {
1997
2995
  });
1998
2996
  });
1999
2997
  expense.command("categories").description("List all expense categories").option("--json", "JSON output").action(async (opts) => {
2000
- const { expenseCategoriesCommand } = await import("./categories-O6TODPAH.js");
2998
+ const { expenseCategoriesCommand } = await import("./categories-JJDTOT5T.js");
2001
2999
  await expenseCategoriesCommand({ json: opts.json });
2002
3000
  });
2003
3001
  }
2004
3002
 
2005
3003
  // src/commands/gst/index.ts
2006
- import * as fs2 from "fs";
2007
3004
  function resolveMonthYear(opts) {
2008
3005
  if (opts.quarter) {
2009
3006
  const range = quarterRange(opts.quarter);
@@ -2030,12 +3027,9 @@ async function gstR1Command(opts) {
2030
3027
  GSTR-1 Summary ${quarterLabel}FY ${year}-${String(year + 1).slice(2)}`);
2031
3028
  console.log(` ${"\u2550".repeat(60)}
2032
3029
  `);
2033
- if (report.summary && typeof report.summary === "object") {
2034
- const s = report.summary;
2035
- if (s["totalTaxableValue"]) console.log(` Total Taxable: ${formatAmount(String(s["totalTaxableValue"]))}`);
2036
- if (s["totalTax"]) console.log(` Total Tax: ${formatAmount(String(s["totalTax"]))}`);
2037
- if (s["totalInvoices"]) console.log(` Total Invoices: ${s["totalInvoices"]}`);
2038
- }
3030
+ console.log(` Total Taxable: ${formatAmount(report.totalTaxableValue)}`);
3031
+ console.log(` Total Tax: ${formatAmount(report.totalTax)}`);
3032
+ console.log(` Total Invoices: ${report.invoiceCount}`);
2039
3033
  console.log();
2040
3034
  console.log(" Use --json for full report data.");
2041
3035
  console.log(" Use: hisaabo gst r1-csv to download GSTN-compatible CSV.\n");
@@ -2062,11 +3056,16 @@ async function gstR3bCommand(opts) {
2062
3056
  GSTR-3B Summary ${month}/${year}`);
2063
3057
  console.log(` ${"\u2550".repeat(60)}
2064
3058
  `);
2065
- if (report.summary && typeof report.summary === "object") {
2066
- const s = report.summary;
2067
- Object.entries(s).forEach(([k, v]) => {
2068
- console.log(` ${k.padEnd(28)}: ${String(v ?? "-")}`);
2069
- });
3059
+ const rows = [
3060
+ ["Outward taxable value", report.outwardSupplies.taxable.taxableValue],
3061
+ ["Outward tax (IGST)", report.outwardSupplies.taxable.igst],
3062
+ ["Outward tax (CGST)", report.outwardSupplies.taxable.cgst],
3063
+ ["Outward tax (SGST)", report.outwardSupplies.taxable.sgst],
3064
+ ["Eligible ITC (total)", report.itc.total],
3065
+ ["Net tax payable (total)", report.netTax.total]
3066
+ ];
3067
+ for (const [label, value] of rows) {
3068
+ console.log(` ${label.padEnd(28)}: ${formatAmount(value)}`);
2070
3069
  }
2071
3070
  console.log();
2072
3071
  } catch (e) {
@@ -2084,8 +3083,8 @@ async function gstR1CsvCommand(opts) {
2084
3083
  const { month, year } = resolveMonthYear(opts);
2085
3084
  try {
2086
3085
  const result = await client.gst.gstr1CSV({ month, year });
2087
- const outputPath = opts.output ?? result.filename;
2088
- fs2.writeFileSync(outputPath, result.csv);
3086
+ const outputPath = opts.output ?? safeFilename(result.filename, "gstr1.csv");
3087
+ writeFileSafe(outputPath, result.csv);
2089
3088
  console.log(` Saved: ${outputPath}`);
2090
3089
  } catch (e) {
2091
3090
  if (e instanceof HisaaboApiError) {
@@ -2099,8 +3098,12 @@ async function gstR1CsvCommand(opts) {
2099
3098
  async function gstR9Command(financialYear, opts) {
2100
3099
  const cfg = requireAuth();
2101
3100
  const client = new HisaaboClient(cfg);
3101
+ const startYear = /^\d{4}(-\d{2})?$/.test(financialYear) ? Number(financialYear.slice(0, 4)) : NaN;
3102
+ if (!Number.isInteger(startYear)) {
3103
+ fatalError("Financial year must look like 2023-24.", EXIT.USAGE);
3104
+ }
2102
3105
  try {
2103
- const report = await client.gst.gstr9({ financialYear });
3106
+ const report = await client.gst.gstr9({ financialYear: startYear });
2104
3107
  if (opts.json) {
2105
3108
  outputJSON(report);
2106
3109
  return;
@@ -2109,13 +3112,11 @@ async function gstR9Command(financialYear, opts) {
2109
3112
  GSTR-9 Annual Return \u2014 FY ${financialYear}`);
2110
3113
  console.log(` ${"\u2550".repeat(60)}
2111
3114
  `);
2112
- const r = report;
2113
- if (r["summary"] && typeof r["summary"] === "object") {
2114
- const s = r["summary"];
2115
- if (s["totalTurnover"]) console.log(` Total Turnover: ${formatAmount(String(s["totalTurnover"]))}`);
2116
- if (s["totalTax"]) console.log(` Total Tax: ${formatAmount(String(s["totalTax"]))}`);
2117
- if (s["totalITC"]) console.log(` Total ITC: ${formatAmount(String(s["totalITC"]))}`);
2118
- }
3115
+ const t = report.partIITotals;
3116
+ const itc = report.table6.netItc;
3117
+ console.log(` Total Turnover: ${formatAmount(t.taxableValue)}`);
3118
+ console.log(` Total Tax: ${formatAmount(t.cgst + t.sgst + t.igst + t.cess)}`);
3119
+ console.log(` Total ITC: ${formatAmount(itc.cgst + itc.sgst + itc.igst + itc.cess)}`);
2119
3120
  console.log();
2120
3121
  console.log(" Use --json for full GSTR-9 data.\n");
2121
3122
  } catch (e) {
@@ -2136,7 +3137,7 @@ async function gstr2bUploadsCommand(opts) {
2136
3137
  outputJSON(result);
2137
3138
  return;
2138
3139
  }
2139
- const uploads = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
3140
+ const uploads = result.uploads;
2140
3141
  console.log("\n GSTR-2B Uploads\n");
2141
3142
  console.log(` ${"\u2550".repeat(60)}
2142
3143
  `);
@@ -2145,10 +3146,10 @@ async function gstr2bUploadsCommand(opts) {
2145
3146
  return;
2146
3147
  }
2147
3148
  for (const up of uploads) {
2148
- const id = String(up["id"] ?? "-").slice(0, 8);
2149
- const period = String(up["period"] ?? up["returnPeriod"] ?? "-").padEnd(10);
2150
- const date = formatDate(String(up["uploadedAt"] ?? up["createdAt"] ?? ""));
2151
- const records = String(up["totalRecords"] ?? up["records"] ?? "-").padStart(8);
3149
+ const id = up.id.slice(0, 8);
3150
+ const period = up.returnPeriod.padEnd(10);
3151
+ const date = formatDate(up.uploadedAt);
3152
+ const records = String(up.totalRecords).padStart(8);
2152
3153
  console.log(` ${id} ${period} ${date.padEnd(13)} Records: ${records}`);
2153
3154
  }
2154
3155
  console.log();
@@ -2204,7 +3205,7 @@ async function reportDaybookCommand(opts) {
2204
3205
  console.log(` ${"\u2550".repeat(70)}
2205
3206
  `);
2206
3207
  const cols = [
2207
- { key: "time", header: "Time", width: 20, format: (v) => formatDate(String(v ?? "")) },
3208
+ { key: "time", header: "Time", width: 20, format: (v) => formatDate(v) },
2208
3209
  { key: "entryType", header: "Type", width: 10 },
2209
3210
  { key: "number", header: "#", width: 12, format: (v) => String(v ?? "-") },
2210
3211
  { key: "partyOrCategory", header: "Party / Category", width: 22 },
@@ -2247,16 +3248,16 @@ async function reportOutstandingCommand(opts) {
2247
3248
  }
2248
3249
  console.log("\n Outstanding Report\n");
2249
3250
  console.log(" " + "\u2550".repeat(60) + "\n");
2250
- if (result.receivables && Array.isArray(result.receivables)) {
3251
+ if (result.receivables) {
2251
3252
  console.log(" Receivables:");
2252
- result.receivables.forEach((row) => {
2253
- console.log(` ${String(row["partyName"] ?? "").padEnd(25)} ${formatAmount(String(row["balance"] ?? "0")).padStart(14)}`);
3253
+ result.receivables.parties.forEach((row) => {
3254
+ console.log(` ${row.partyName.padEnd(25)} ${formatAmount(row.total).padStart(14)}`);
2254
3255
  });
2255
3256
  }
2256
- if (result.payables && Array.isArray(result.payables)) {
3257
+ if (result.payables) {
2257
3258
  console.log("\n Payables:");
2258
- result.payables.forEach((row) => {
2259
- console.log(` ${String(row["partyName"] ?? "").padEnd(25)} ${formatAmount(String(row["balance"] ?? "0")).padStart(14)}`);
3259
+ result.payables.parties.forEach((row) => {
3260
+ console.log(` ${row.partyName.padEnd(25)} ${formatAmount(row.total).padStart(14)}`);
2260
3261
  });
2261
3262
  }
2262
3263
  console.log();
@@ -2274,7 +3275,7 @@ async function reportTaxSummaryCommand(opts) {
2274
3275
  const client = new HisaaboClient(cfg);
2275
3276
  const { from, to } = resolveRange(opts);
2276
3277
  try {
2277
- const result = await client.reports.taxSummary({ fromDate: from, toDate: to });
3278
+ const result = await client.reports.taxSummary({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end") });
2278
3279
  if (opts.json) {
2279
3280
  outputJSON(result);
2280
3281
  return;
@@ -2283,14 +3284,20 @@ async function reportTaxSummaryCommand(opts) {
2283
3284
  Tax Summary ${from} \u2192 ${to}
2284
3285
  `);
2285
3286
  console.log(" " + "\u2550".repeat(60) + "\n");
2286
- if (Array.isArray(result.rows)) {
2287
- result.rows.forEach((row) => {
2288
- const rate = String(row["taxPercent"] ?? row["rate"] ?? "-");
2289
- const taxable = formatAmount(String(row["taxableAmount"] ?? "0"));
2290
- const tax = formatAmount(String(row["taxAmount"] ?? "0"));
2291
- console.log(` ${rate.padEnd(6)}% Taxable: ${taxable.padStart(14)} Tax: ${tax.padStart(12)}`);
3287
+ const printBreakdown = (label, rows) => {
3288
+ console.log(` ${label}:`);
3289
+ rows.forEach((row) => {
3290
+ const taxable = formatAmount(row.taxableAmount);
3291
+ const tax = formatAmount(row.taxAmount);
3292
+ console.log(` ${row.taxPercent.padEnd(6)}% Taxable: ${taxable.padStart(14)} Tax: ${tax.padStart(12)}`);
2292
3293
  });
2293
- }
3294
+ };
3295
+ printBreakdown("Sales", result.salesBreakdown);
3296
+ printBreakdown("Purchases", result.purchaseBreakdown);
3297
+ console.log(`
3298
+ Tax collected: ${formatAmount(result.summary.totalTaxCollected).padStart(14)}`);
3299
+ console.log(` Tax paid: ${formatAmount(result.summary.totalTaxPaid).padStart(14)}`);
3300
+ console.log(` Net liability: ${formatAmount(result.summary.netTaxLiability).padStart(14)}`);
2294
3301
  console.log();
2295
3302
  } catch (e) {
2296
3303
  if (e instanceof HisaaboApiError) {
@@ -2306,7 +3313,7 @@ async function reportItemSalesCommand(opts) {
2306
3313
  const client = new HisaaboClient(cfg);
2307
3314
  const { from, to } = resolveRange(opts);
2308
3315
  try {
2309
- const result = await client.reports.itemSales({ fromDate: from, toDate: to });
3316
+ const result = await client.reports.itemSales({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end") });
2310
3317
  if (opts.json) {
2311
3318
  outputJSON(result);
2312
3319
  return;
@@ -2315,14 +3322,12 @@ async function reportItemSalesCommand(opts) {
2315
3322
  Item Sales ${from} \u2192 ${to}
2316
3323
  `);
2317
3324
  console.log(" " + "\u2550".repeat(70) + "\n");
2318
- if (Array.isArray(result.rows)) {
2319
- result.rows.slice(0, 50).forEach((row) => {
2320
- const name = String(row["itemName"] ?? row["name"] ?? "-").padEnd(25);
2321
- const qty = String(row["totalQuantity"] ?? row["qty"] ?? "-").padStart(8);
2322
- const rev = formatAmount(String(row["totalRevenue"] ?? row["revenue"] ?? "0")).padStart(14);
2323
- console.log(` ${name} ${qty} ${rev}`);
2324
- });
2325
- }
3325
+ result.rows.slice(0, 50).forEach((row) => {
3326
+ const name = row.itemName.padEnd(25);
3327
+ const qty = row.soldQty.padStart(8);
3328
+ const rev = formatAmount(row.totalRevenue).padStart(14);
3329
+ console.log(` ${name} ${qty} ${rev}`);
3330
+ });
2326
3331
  console.log();
2327
3332
  } catch (e) {
2328
3333
  if (e instanceof HisaaboApiError) {
@@ -2344,14 +3349,18 @@ async function reportStockSummaryCommand(opts) {
2344
3349
  }
2345
3350
  console.log("\n Stock Summary\n");
2346
3351
  console.log(" " + "\u2550".repeat(60) + "\n");
2347
- if (Array.isArray(result.rows)) {
2348
- result.rows.forEach((row) => {
2349
- const name = String(row["itemName"] ?? row["name"] ?? "-").padEnd(25);
2350
- const stock = String(row["stockQuantity"] ?? row["stock"] ?? "-").padStart(10);
2351
- const val = formatAmount(String(row["stockValue"] ?? row["value"] ?? "0")).padStart(14);
2352
- console.log(` ${name} ${stock} ${val}`);
2353
- });
2354
- }
3352
+ result.simpleItems.forEach((row) => {
3353
+ const name = row.itemName.padEnd(25);
3354
+ const stock = row.currentStock.padStart(10);
3355
+ const val = formatAmount(row.stockValue).padStart(14);
3356
+ console.log(` ${name} ${stock} ${val}`);
3357
+ });
3358
+ result.variantItems.forEach((row) => {
3359
+ const name = row.itemName.padEnd(25);
3360
+ const stock = row.totalStock.padStart(10);
3361
+ const val = formatAmount(row.totalValue).padStart(14);
3362
+ console.log(` ${name} ${stock} ${val}`);
3363
+ });
2355
3364
  console.log();
2356
3365
  } catch (e) {
2357
3366
  if (e instanceof HisaaboApiError) {
@@ -2367,7 +3376,7 @@ async function reportSalesRegisterCommand(opts) {
2367
3376
  const client = new HisaaboClient(cfg);
2368
3377
  const { from, to } = resolveRange(opts);
2369
3378
  try {
2370
- const result = await client.reports.salesRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
3379
+ const result = await client.reports.salesRegister({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end"), partyId: opts.partyId });
2371
3380
  if (opts.json) {
2372
3381
  outputJSON(result);
2373
3382
  return;
@@ -2377,23 +3386,22 @@ async function reportSalesRegisterCommand(opts) {
2377
3386
  `);
2378
3387
  console.log(` ${"\u2550".repeat(80)}
2379
3388
  `);
2380
- const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
3389
+ const rows = result.rows;
2381
3390
  const cols = [
2382
- { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2383
- { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2384
- { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2385
- { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2386
- { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2387
- { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2388
- { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
3391
+ { key: "invoiceDate", header: "Date", width: 13, format: (v) => formatDate(v) },
3392
+ { key: "invoiceNumber", header: "Invoice #", width: 14 },
3393
+ { key: "customerName", header: "Party", width: 22 },
3394
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
3395
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
3396
+ { key: "totalAmount", header: "Total (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
3397
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
2389
3398
  ];
2390
3399
  if (opts.format === "tsv") outputTSV(rows, cols);
2391
3400
  else if (opts.format === "csv") outputCSV(rows, cols);
2392
3401
  else outputTable(rows, cols);
2393
3402
  if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2394
- const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2395
3403
  console.log(`
2396
- Total: ${formatAmount(String(total)).padStart(14)}
3404
+ Total: ${formatAmount(result.summary.totalAmount).padStart(14)}
2397
3405
  `);
2398
3406
  }
2399
3407
  } catch (e) {
@@ -2410,7 +3418,7 @@ async function reportPurchaseRegisterCommand(opts) {
2410
3418
  const client = new HisaaboClient(cfg);
2411
3419
  const { from, to } = resolveRange(opts);
2412
3420
  try {
2413
- const result = await client.reports.purchaseRegister({ fromDate: from, toDate: to, partyId: opts.partyId });
3421
+ const result = await client.reports.purchaseRegister({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end"), partyId: opts.partyId });
2414
3422
  if (opts.json) {
2415
3423
  outputJSON(result);
2416
3424
  return;
@@ -2420,23 +3428,22 @@ async function reportPurchaseRegisterCommand(opts) {
2420
3428
  `);
2421
3429
  console.log(` ${"\u2550".repeat(80)}
2422
3430
  `);
2423
- const rows = Array.isArray(result) ? result : Array.isArray(result.rows) ? result.rows : Array.isArray(result.invoices) ? result.invoices : [];
3431
+ const rows = result.rows;
2424
3432
  const cols = [
2425
- { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? r.invoiceDate ?? v ?? "")) },
2426
- { key: "invoiceNumber", header: "Invoice #", width: 14, format: (v, r) => String(r.invoiceNumber ?? r.number ?? v ?? "-") },
2427
- { key: "partyName", header: "Party", width: 22, format: (v, r) => String(r.partyName ?? r.party ?? v ?? "-") },
2428
- { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.subtotal ?? v ?? "0")) },
2429
- { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v, r) => formatAmount(String(r.taxAmount ?? r.tax ?? v ?? "0")) },
2430
- { key: "total", header: "Total (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.total ?? r.totalAmount ?? v ?? "0")) },
2431
- { key: "status", header: "Status", width: 10, format: (v, r) => formatStatus(String(r.status ?? v ?? "")) }
3433
+ { key: "invoiceDate", header: "Date", width: 13, format: (v) => formatDate(v) },
3434
+ { key: "invoiceNumber", header: "Invoice #", width: 14 },
3435
+ { key: "supplierName", header: "Party", width: 22 },
3436
+ { key: "subtotal", header: "Subtotal (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
3437
+ { key: "taxAmount", header: "Tax (\u20B9)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
3438
+ { key: "totalAmount", header: "Total (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) },
3439
+ { key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) }
2432
3440
  ];
2433
3441
  if (opts.format === "tsv") outputTSV(rows, cols);
2434
3442
  else if (opts.format === "csv") outputCSV(rows, cols);
2435
3443
  else outputTable(rows, cols);
2436
3444
  if (rows.length > 0 && opts.format !== "tsv" && opts.format !== "csv") {
2437
- const total = rows.reduce((sum, r) => sum + parseFloat(String(r.total ?? r.totalAmount ?? "0")), 0);
2438
3445
  console.log(`
2439
- Total: ${formatAmount(String(total)).padStart(14)}
3446
+ Total: ${formatAmount(result.summary.totalAmount).padStart(14)}
2440
3447
  `);
2441
3448
  }
2442
3449
  } catch (e) {
@@ -2458,32 +3465,29 @@ async function reportPartyStatementCommand(partyId, opts) {
2458
3465
  outputJSON(result);
2459
3466
  return;
2460
3467
  }
2461
- const res = result;
2462
- const partyName = String(res["partyName"] ?? res["party"] ?? partyId);
3468
+ if (!result) fatalError(`Party not found: ${partyId}`, EXIT.NOT_FOUND);
2463
3469
  console.log(`
2464
- Party Statement \u2014 ${partyName} ${from} \u2192 ${to}
3470
+ Party Statement \u2014 ${result.party.name} ${from} \u2192 ${to}
2465
3471
  `);
2466
3472
  console.log(` ${"\u2550".repeat(75)}
2467
3473
  `);
2468
- const openingBalance = String(res["openingBalance"] ?? "0");
2469
- console.log(` Opening Balance: ${formatAmount(openingBalance).padStart(14)}
3474
+ console.log(` Opening Balance: ${formatAmount(result.party.openingBalance).padStart(14)}
2470
3475
  `);
2471
- const rows = Array.isArray(res["entries"]) ? res["entries"] : Array.isArray(res["rows"]) ? res["rows"] : [];
3476
+ const rows = result.entries;
2472
3477
  const cols = [
2473
- { key: "date", header: "Date", width: 13, format: (v, r) => formatDate(String(r.date ?? v ?? "")) },
2474
- { key: "type", header: "Type", width: 12, format: (v, r) => String(r.type ?? r.entryType ?? v ?? "-") },
2475
- { key: "number", header: "Number", width: 14, format: (v, r) => String(r.number ?? r.invoiceNumber ?? v ?? "-") },
2476
- { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.debit ?? v ?? "0")) !== 0 ? formatAmount(String(r.debit ?? v)) : "-" },
2477
- { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v, r) => parseFloat(String(r.credit ?? v ?? "0")) !== 0 ? formatAmount(String(r.credit ?? v)) : "-" },
2478
- { key: "balance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v, r) => formatAmount(String(r.balance ?? r.runningBalance ?? v ?? "0")) }
3478
+ { key: "date", header: "Date", width: 13, format: (v) => formatDate(v) },
3479
+ { key: "type", header: "Type", width: 12 },
3480
+ { key: "number", header: "Number", width: 14 },
3481
+ { key: "debit", header: "Debit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
3482
+ { key: "credit", header: "Credit (\u20B9)", align: "right", width: 13, format: (v) => parseFloat(String(v ?? "0")) !== 0 ? formatAmount(String(v)) : "-" },
3483
+ { key: "runningBalance", header: "Balance (\u20B9)", align: "right", width: 14, format: (v) => formatAmount(String(v ?? "0")) }
2479
3484
  ];
2480
3485
  if (opts.format === "tsv") outputTSV(rows, cols);
2481
3486
  else if (opts.format === "csv") outputCSV(rows, cols);
2482
3487
  else outputTable(rows, cols);
2483
3488
  if (opts.format !== "tsv" && opts.format !== "csv") {
2484
- const closingBalance = String(res["closingBalance"] ?? res["balance"] ?? "0");
2485
3489
  console.log(`
2486
- Closing Balance: ${formatAmount(closingBalance).padStart(14)}
3490
+ Closing Balance: ${formatAmount(result.summary.closingBalance).padStart(14)}
2487
3491
  `);
2488
3492
  }
2489
3493
  } catch (e) {
@@ -2501,36 +3505,29 @@ async function reportPaymentSummaryCommand(opts) {
2501
3505
  const { from, to } = resolveRange(opts);
2502
3506
  try {
2503
3507
  const result = await client.reports.paymentSummary({
2504
- fromDate: from,
2505
- toDate: to,
3508
+ fromDate: toApiDateTime(from, "start"),
3509
+ toDate: toApiDateTime(to, "end"),
2506
3510
  type: opts.type ?? "both"
2507
3511
  });
2508
3512
  if (opts.json) {
2509
3513
  outputJSON(result);
2510
3514
  return;
2511
3515
  }
2512
- const res = result;
2513
3516
  console.log(`
2514
3517
  Payment Summary ${from} \u2192 ${to}
2515
3518
  `);
2516
3519
  console.log(" " + "\u2550".repeat(60) + "\n");
2517
- const received = String(res["totalReceived"] ?? res["received"] ?? "0");
2518
- const made = String(res["totalMade"] ?? res["made"] ?? "0");
2519
- const net = String(res["net"] ?? res["netCash"] ?? "0");
2520
- console.log(` Total Received: ${formatAmount(received).padStart(14)}`);
2521
- console.log(` Total Made: ${formatAmount(made).padStart(14)}`);
2522
- console.log(` Net: ${formatAmount(net).padStart(14)}`);
2523
- const breakdown = res["breakdown"] ?? res["byMode"] ?? res["modes"];
2524
- if (breakdown && Array.isArray(breakdown)) {
2525
- console.log(`
3520
+ console.log(` Total Received: ${formatAmount(result.summary.totalReceived).padStart(14)}`);
3521
+ console.log(` Total Made: ${formatAmount(result.summary.totalMade).padStart(14)}`);
3522
+ console.log(` Net: ${formatAmount(result.summary.netCashMovement).padStart(14)}`);
3523
+ console.log(`
2526
3524
  By Payment Mode:
2527
3525
  `);
2528
- breakdown.forEach((row) => {
2529
- const mode = String(row["mode"] ?? row["paymentMode"] ?? "-").padEnd(18);
2530
- const amount = formatAmount(String(row["amount"] ?? row["total"] ?? "0")).padStart(14);
2531
- console.log(` ${mode} ${amount}`);
2532
- });
2533
- }
3526
+ result.byMode.forEach((row) => {
3527
+ const mode = row.mode.padEnd(18);
3528
+ const amount = formatAmount(row.totalAmount).padStart(14);
3529
+ console.log(` ${mode} ${amount}`);
3530
+ });
2534
3531
  console.log();
2535
3532
  } catch (e) {
2536
3533
  if (e instanceof HisaaboApiError) {
@@ -2545,41 +3542,21 @@ async function reportCashFlowCommand(opts) {
2545
3542
  const cfg = requireAuth();
2546
3543
  const client = new HisaaboClient(cfg);
2547
3544
  try {
2548
- const result = await client.reports.cashFlowForecast();
3545
+ const result = await client.reports.cashFlowForecast({});
2549
3546
  if (opts.json) {
2550
3547
  outputJSON(result);
2551
3548
  return;
2552
3549
  }
2553
- const res = result;
2554
3550
  console.log("\n Cash Flow Forecast\n");
2555
3551
  console.log(" " + "\u2550".repeat(60) + "\n");
2556
- const currentBalance = String(res["currentBalance"] ?? res["balance"] ?? "0");
2557
- const avgDailyExpenses = String(res["avgDailyExpenses"] ?? res["dailyBurn"] ?? "0");
2558
- console.log(` Current Balance: ${formatAmount(currentBalance).padStart(14)}`);
2559
- console.log(` Avg Daily Expenses: ${formatAmount(avgDailyExpenses).padStart(14)}`);
2560
- const forecasts = res["forecasts"] ?? res["forecast"];
2561
- if (forecasts && Array.isArray(forecasts)) {
2562
- console.log(`
2563
- Forecast:
2564
- `);
2565
- forecasts.forEach((f) => {
2566
- const days = String(f["days"] ?? f["day"] ?? "-");
2567
- const balance = formatAmount(String(f["balance"] ?? f["amount"] ?? "0")).padStart(14);
2568
- console.log(` ${`${days}d`.padEnd(6)} ${balance}`);
2569
- });
2570
- } else {
2571
- const current = parseFloat(currentBalance);
2572
- const daily = parseFloat(avgDailyExpenses);
2573
- if (!isNaN(current) && !isNaN(daily)) {
2574
- console.log(`
2575
- Forecast:
3552
+ console.log(` Current Balance: ${formatAmount(result.currentBankBalance).padStart(14)}`);
3553
+ console.log(` Avg Daily Expenses: ${formatAmount(result.avgDailyExpenses).padStart(14)}`);
3554
+ console.log(`
3555
+ Forecast (expected):
2576
3556
  `);
2577
- for (const days of [7, 14, 30]) {
2578
- const projected = current - daily * days;
2579
- console.log(` ${`${days}d`.padEnd(6)} ${formatAmount(String(projected)).padStart(14)}`);
2580
- }
2581
- }
2582
- }
3557
+ result.forecast.forEach((f) => {
3558
+ console.log(` ${`${f.days}d`.padEnd(6)} ${formatAmount(f.expected).padStart(14)}`);
3559
+ });
2583
3560
  console.log();
2584
3561
  } catch (e) {
2585
3562
  if (e instanceof HisaaboApiError) {
@@ -2595,7 +3572,7 @@ async function reportTrialBalanceCommand(opts) {
2595
3572
  const client = new HisaaboClient(cfg);
2596
3573
  const { from: _from, to } = resolveRange(opts);
2597
3574
  try {
2598
- const result = await client.reports.trialBalance({ asOfDate: to });
3575
+ const result = await client.reports.trialBalance({ asOfDate: toApiDateTime(to, "end") });
2599
3576
  if (opts.json) {
2600
3577
  outputJSON(result);
2601
3578
  return;
@@ -2605,11 +3582,10 @@ async function reportTrialBalanceCommand(opts) {
2605
3582
  `);
2606
3583
  console.log(` ${"\u2550".repeat(70)}
2607
3584
  `);
2608
- const rows = Array.isArray(result?.accounts) ? result.accounts : Array.isArray(result?.rows) ? result.rows : Array.isArray(result) ? result : [];
2609
- for (const row of rows) {
2610
- const name = String(row["accountName"] ?? row["name"] ?? "-").padEnd(30);
2611
- const debit = String(row["debit"] ?? "0");
2612
- const credit = String(row["credit"] ?? "0");
3585
+ for (const row of result.accounts) {
3586
+ const name = row.accountName.padEnd(30);
3587
+ const debit = row.debit;
3588
+ const credit = row.credit;
2613
3589
  const dr = parseFloat(debit) !== 0 ? formatAmount(debit) : "-";
2614
3590
  const cr = parseFloat(credit) !== 0 ? formatAmount(credit) : "-";
2615
3591
  console.log(` ${name} ${dr.padStart(14)} ${cr.padStart(14)}`);
@@ -2629,20 +3605,19 @@ async function reportBalanceSheetCommand(opts) {
2629
3605
  const client = new HisaaboClient(cfg);
2630
3606
  const { to } = resolveRange(opts);
2631
3607
  try {
2632
- const result = await client.reports.balanceSheet({ asOfDate: to });
3608
+ const result = await client.reports.balanceSheet({ asOfDate: toApiDateTime(to, "end") });
2633
3609
  if (opts.json) {
2634
3610
  outputJSON(result);
2635
3611
  return;
2636
3612
  }
2637
- const r = result;
2638
3613
  console.log(`
2639
3614
  Balance Sheet as of ${to}
2640
3615
  `);
2641
3616
  console.log(` ${"\u2550".repeat(60)}
2642
3617
  `);
2643
- const assets = String(r["totalAssets"] ?? r["assets"] ?? "0");
2644
- const liabilities = String(r["totalLiabilities"] ?? r["liabilities"] ?? "0");
2645
- const equity = String(r["totalEquity"] ?? r["equity"] ?? "0");
3618
+ const assets = result.totalAssets;
3619
+ const liabilities = result.totalLiabilities;
3620
+ const equity = result.totalEquity;
2646
3621
  console.log(` Total Assets: ${formatAmount(assets).padStart(14)}`);
2647
3622
  console.log(` Total Liabilities: ${formatAmount(liabilities).padStart(14)}`);
2648
3623
  console.log(` Total Equity: ${formatAmount(equity).padStart(14)}`);
@@ -2662,21 +3637,20 @@ async function reportCashFlowStatementCommand(opts) {
2662
3637
  const client = new HisaaboClient(cfg);
2663
3638
  const { from, to } = resolveRange(opts);
2664
3639
  try {
2665
- const result = await client.reports.cashFlowStatement({ fromDate: from, toDate: to });
3640
+ const result = await client.reports.cashFlowStatement({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end") });
2666
3641
  if (opts.json) {
2667
3642
  outputJSON(result);
2668
3643
  return;
2669
3644
  }
2670
- const r = result;
2671
3645
  console.log(`
2672
3646
  Cash Flow Statement ${from} \u2192 ${to}
2673
3647
  `);
2674
3648
  console.log(` ${"\u2550".repeat(60)}
2675
3649
  `);
2676
- const operating = String(r["operatingActivities"] ?? r["operations"] ?? "0");
2677
- const investing = String(r["investingActivities"] ?? r["investing"] ?? "0");
2678
- const financing = String(r["financingActivities"] ?? r["financing"] ?? "0");
2679
- const net = String(r["netCashFlow"] ?? r["net"] ?? "0");
3650
+ const operating = result.operating.totalOperating;
3651
+ const investing = result.investing.totalInvesting;
3652
+ const financing = result.financing.totalFinancing;
3653
+ const net = result.netCashFlow;
2680
3654
  console.log(` Operating Activities: ${formatAmount(operating).padStart(14)}`);
2681
3655
  console.log(` Investing Activities: ${formatAmount(investing).padStart(14)}`);
2682
3656
  console.log(` Financing Activities: ${formatAmount(financing).padStart(14)}`);
@@ -2696,33 +3670,26 @@ async function reportGeneralLedgerCommand(accountId, opts) {
2696
3670
  const client = new HisaaboClient(cfg);
2697
3671
  const { from, to } = resolveRange(opts);
2698
3672
  try {
2699
- const result = await client.reports.generalLedger({ accountId, fromDate: from, toDate: to });
3673
+ const result = await client.reports.generalLedger({ accountId, fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end") });
2700
3674
  if (opts.json) {
2701
3675
  outputJSON(result);
2702
3676
  return;
2703
3677
  }
2704
- const r = result;
2705
- const accountName = String(r["accountName"] ?? r["account"] ?? accountId);
2706
3678
  console.log(`
2707
- General Ledger \u2014 ${accountName} ${from} \u2192 ${to}
3679
+ General Ledger \u2014 ${result.accountName} ${from} \u2192 ${to}
2708
3680
  `);
2709
3681
  console.log(` ${"\u2550".repeat(75)}
2710
3682
  `);
2711
- const opening = String(r["openingBalance"] ?? "0");
2712
- console.log(` Opening Balance: ${formatAmount(opening).padStart(14)}
2713
- `);
2714
- const entries = Array.isArray(r["entries"]) ? r["entries"] : Array.isArray(r["rows"]) ? r["rows"] : [];
2715
- for (const entry of entries) {
2716
- const date = formatDate(String(entry["date"] ?? "")).padEnd(13);
2717
- const narration = String(entry["narration"] ?? entry["description"] ?? "-").slice(0, 25).padEnd(25);
2718
- const debit = parseFloat(String(entry["debit"] ?? "0")) !== 0 ? formatAmount(String(entry["debit"])) : "-";
2719
- const credit = parseFloat(String(entry["credit"] ?? "0")) !== 0 ? formatAmount(String(entry["credit"])) : "-";
2720
- const balance = formatAmount(String(entry["balance"] ?? "0"));
3683
+ for (const entry of result.entries) {
3684
+ const date = formatDate(entry.date).padEnd(13);
3685
+ const narration = (entry.narration || "-").slice(0, 25).padEnd(25);
3686
+ const debit = parseFloat(entry.debit) !== 0 ? formatAmount(entry.debit) : "-";
3687
+ const credit = parseFloat(entry.credit) !== 0 ? formatAmount(entry.credit) : "-";
3688
+ const balance = formatAmount(entry.balance);
2721
3689
  console.log(` ${date} ${narration} ${debit.padStart(12)} ${credit.padStart(12)} ${balance.padStart(14)}`);
2722
3690
  }
2723
- const closing = String(r["closingBalance"] ?? r["balance"] ?? "0");
2724
3691
  console.log(`
2725
- Closing Balance: ${formatAmount(closing).padStart(14)}
3692
+ Closing Balance: ${formatAmount(result.closingBalance).padStart(14)}
2726
3693
  `);
2727
3694
  } catch (e) {
2728
3695
  if (e instanceof HisaaboApiError) {
@@ -2738,26 +3705,22 @@ async function reportCollectionEfficiencyCommand(opts) {
2738
3705
  const client = new HisaaboClient(cfg);
2739
3706
  const { from, to } = resolveRange(opts);
2740
3707
  try {
2741
- const result = await client.reports.collectionEfficiency({ fromDate: from, toDate: to });
3708
+ const result = await client.reports.collectionEfficiency({ fromDate: toApiDateTime(from, "start"), toDate: toApiDateTime(to, "end") });
2742
3709
  if (opts.json) {
2743
3710
  outputJSON(result);
2744
3711
  return;
2745
3712
  }
2746
- const res = result;
2747
3713
  console.log(`
2748
3714
  Collection Efficiency ${from} \u2192 ${to}
2749
3715
  `);
2750
3716
  console.log(" " + "\u2550".repeat(60) + "\n");
2751
- const rate = String(res["collectionRate"] ?? res["rate"] ?? "0");
2752
- const dso = String(res["dso"] ?? res["daysSalesOutstanding"] ?? "-");
2753
- const paidOnTime = String(res["paidOnTime"] ?? res["onTimeCount"] ?? "-");
2754
- const totalInvoiced = String(res["totalInvoiced"] ?? res["invoiced"] ?? "-");
2755
- console.log(` Collection Rate: ${parseFloat(rate).toFixed(1).padStart(8)}%`);
3717
+ const ce = result.collectionEfficiency;
3718
+ const dso = result.dso.dsoDays ?? "-";
3719
+ console.log(` On-Time Rate: ${parseFloat(ce.onTimeRate).toFixed(1).padStart(8)}%`);
2756
3720
  console.log(` DSO (Days): ${dso.padStart(8)}`);
2757
- console.log(` Paid On Time: ${paidOnTime.padStart(8)}`);
2758
- if (totalInvoiced !== "-") {
2759
- console.log(` Total Invoiced: ${formatAmount(totalInvoiced).padStart(14)}`);
2760
- }
3721
+ console.log(` Paid On Time: ${String(ce.paidOnTime).padStart(8)}`);
3722
+ console.log(` Paid Late: ${String(ce.paidLate).padStart(8)}`);
3723
+ console.log(` Total Invoices: ${String(ce.totalInvoices).padStart(8)}`);
2761
3724
  console.log();
2762
3725
  } catch (e) {
2763
3726
  if (e instanceof HisaaboApiError) {
@@ -2820,7 +3783,7 @@ function registerReportCommands(program2) {
2820
3783
  }
2821
3784
 
2822
3785
  // src/commands/bank/index.ts
2823
- import * as readline11 from "readline";
3786
+ import * as readline6 from "readline";
2824
3787
  async function prompt5(rl, q) {
2825
3788
  return new Promise((resolve2) => rl.question(q, resolve2));
2826
3789
  }
@@ -2900,9 +3863,9 @@ async function bankCreateCommand(opts) {
2900
3863
  let ifsc = opts.ifsc;
2901
3864
  let openingBalance = opts.openingBalance;
2902
3865
  if (!isNonInteractive) {
2903
- const rl = readline11.createInterface({ input: process.stdin, output: process.stdout });
3866
+ const rl = readline6.createInterface({ input: process.stdin, output: process.stdout });
2904
3867
  if (!name) name = (await prompt5(rl, " Account Name: ")).trim();
2905
- const typeStr = await prompt5(rl, " Type (savings/current/cash/credit/other) [current]: ");
3868
+ const typeStr = await prompt5(rl, " Type (savings/current/cash/upi/credit_card/payment_gateway) [current]: ");
2906
3869
  accountType = typeStr.trim() || "current";
2907
3870
  const bankStr = await prompt5(rl, " Bank Name: ");
2908
3871
  if (bankStr.trim()) bankName = bankStr.trim();
@@ -2915,6 +3878,9 @@ async function bankCreateCommand(opts) {
2915
3878
  rl.close();
2916
3879
  }
2917
3880
  if (!name) fatalError("--name is required", EXIT.USAGE);
3881
+ if (!bankAccountTypes.includes(accountType)) {
3882
+ fatalError(`--type must be one of: ${bankAccountTypes.join(", ")}.`, EXIT.USAGE);
3883
+ }
2918
3884
  try {
2919
3885
  const account = await client.bankAccount.create({
2920
3886
  accountName: name,
@@ -2979,8 +3945,8 @@ async function bankTransactionsCommand(accountId, opts) {
2979
3945
  try {
2980
3946
  const result = await client.bankAccount.listTransactions({
2981
3947
  bankAccountId: accountId,
2982
- fromDate: opts.from,
2983
- toDate: opts.to,
3948
+ fromDate: apiFrom(opts.from),
3949
+ toDate: apiTo(opts.to),
2984
3950
  page,
2985
3951
  limit
2986
3952
  });
@@ -3127,7 +4093,7 @@ function registerBankCommands(program2) {
3127
4093
  bank.command("get <id>").description("Get bank account details").option("--json", "JSON output").action(async (id, opts) => {
3128
4094
  await bankGetCommand(id, { json: opts.json });
3129
4095
  });
3130
- 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) => {
4096
+ bank.command("create").description("Create a new bank account").option("--json", "JSON output").option("--name <name>", "Account name").option("--type <type>", "savings/current/cash/upi/credit_card/payment_gateway").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) => {
3131
4097
  await bankCreateCommand({
3132
4098
  json: opts.json,
3133
4099
  name: opts.name,
@@ -3339,6 +4305,14 @@ function registerShipmentCommands(program2) {
3339
4305
  }
3340
4306
 
3341
4307
  // src/commands/target/index.ts
4308
+ var targetTypes = ["order_count", "order_value", "item_quantity"];
4309
+ var targetPeriodTypes = ["daily", "weekly", "monthly", "quarterly", "custom"];
4310
+ function isTargetType(v) {
4311
+ return v !== void 0 && targetTypes.includes(v);
4312
+ }
4313
+ function isPeriodType(v) {
4314
+ return targetPeriodTypes.includes(v);
4315
+ }
3342
4316
  async function targetListCommand(opts) {
3343
4317
  const cfg = requireAuth();
3344
4318
  const client = new HisaaboClient(cfg);
@@ -3351,11 +4325,11 @@ async function targetListCommand(opts) {
3351
4325
  console.log("\n Sales Targets\n");
3352
4326
  const cols = [
3353
4327
  { key: "id", header: "ID", width: 10, format: (v) => String(v ?? "").slice(0, 8) + "..." },
3354
- { key: "type", header: "Type", width: 14 },
3355
- { key: "period", header: "Period", width: 12 },
4328
+ { key: "targetType", header: "Type", width: 14 },
4329
+ { key: "periodType", header: "Period", width: 12 },
3356
4330
  { key: "targetValue", header: "Target", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
3357
- { key: "startDate", header: "Start", width: 13, format: (v) => formatDate(String(v ?? "")) },
3358
- { key: "endDate", header: "End", width: 13, format: (v) => formatDate(v ? String(v) : null) }
4331
+ { key: "periodStart", header: "Start", width: 13, format: (v) => formatDate(v) },
4332
+ { key: "periodEnd", header: "End", width: 13, format: (v) => formatDate(v) }
3359
4333
  ];
3360
4334
  outputTable(targets, cols);
3361
4335
  } catch (e) {
@@ -3379,10 +4353,11 @@ async function targetMyCommand(opts) {
3379
4353
  console.log("\n My Targets\n");
3380
4354
  console.log(" " + "\u2550".repeat(60) + "\n");
3381
4355
  targets.forEach((t) => {
3382
- const pct = Math.round(t.percentComplete);
3383
- const bar = "\u2588".repeat(Math.floor(pct / 5)) + "\u2591".repeat(20 - Math.floor(pct / 5));
3384
- console.log(` ${t.type} (${t.period})`);
3385
- console.log(` Target: ${formatAmount(t.targetValue)} Current: ${formatAmount(t.currentValue)} ${pct}%`);
4356
+ const pct = Math.round(t.progress.percentage);
4357
+ const filled = Math.max(0, Math.min(20, Math.floor(pct / 5)));
4358
+ const bar = "\u2588".repeat(filled) + "\u2591".repeat(20 - filled);
4359
+ console.log(` ${t.targetType} (${t.periodType})`);
4360
+ console.log(` Target: ${formatAmount(t.targetValue)} Current: ${formatAmount(t.progress.current)} ${pct}%`);
3386
4361
  console.log(` [${bar}]
3387
4362
  `);
3388
4363
  });
@@ -3401,20 +4376,26 @@ async function targetCreateCommand(opts) {
3401
4376
  if (!opts.type) fatalError("--type is required (order_count/order_value/item_quantity)", EXIT.USAGE);
3402
4377
  if (!opts.value) fatalError("--value is required", EXIT.USAGE);
3403
4378
  if (!opts.startDate) fatalError("--start-date is required", EXIT.USAGE);
4379
+ if (!opts.endDate) fatalError("--end-date is required", EXIT.USAGE);
4380
+ if (!isTargetType(opts.type)) fatalError(`--type must be one of: ${targetTypes.join(", ")}`, EXIT.USAGE);
4381
+ const period = opts.period ?? "monthly";
4382
+ if (!isPeriodType(period)) fatalError(`--period must be one of: ${targetPeriodTypes.join(", ")}`, EXIT.USAGE);
3404
4383
  try {
4384
+ const userId = opts.userId ?? (await client.auth.me()).id;
3405
4385
  const target = await client.target.create({
3406
- type: opts.type,
3407
- period: opts.period ?? "monthly",
4386
+ userId,
4387
+ targetType: opts.type,
4388
+ periodType: period,
3408
4389
  targetValue: opts.value,
3409
- startDate: opts.startDate,
3410
- endDate: opts.endDate,
4390
+ periodStart: toApiDateTime(opts.startDate, "start"),
4391
+ periodEnd: toApiDateTime(opts.endDate, "end"),
3411
4392
  notes: opts.notes
3412
4393
  });
3413
4394
  if (opts.json) {
3414
4395
  outputJSON(target);
3415
4396
  return;
3416
4397
  }
3417
- success(`Target created: ${target.type} ${target.period} ${formatAmount(target.targetValue)}`);
4398
+ success(`Target created: ${target.targetType} ${target.periodType} ${formatAmount(target.targetValue)}`);
3418
4399
  } catch (e) {
3419
4400
  if (e instanceof HisaaboApiError) {
3420
4401
  const err = e.hisaaboError;
@@ -3435,7 +4416,7 @@ function registerTargetCommands(program2) {
3435
4416
  target.command("my").description("Show my target progress").option("--json", "JSON output").action(async (opts) => {
3436
4417
  await targetMyCommand({ json: opts.json });
3437
4418
  });
3438
- 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) => {
4419
+ 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("--user-id <id>", "User the target applies to (default: you)").option("--notes <text>", "Notes").action(async (opts) => {
3439
4420
  await targetCreateCommand({
3440
4421
  json: opts.json,
3441
4422
  type: opts.type,
@@ -3443,33 +4424,196 @@ function registerTargetCommands(program2) {
3443
4424
  value: opts.value,
3444
4425
  startDate: opts.startDate,
3445
4426
  endDate: opts.endDate,
4427
+ userId: opts.userId,
3446
4428
  notes: opts.notes
3447
4429
  });
3448
4430
  });
3449
4431
  }
3450
4432
 
4433
+ // src/commands/notification/index.ts
4434
+ var DELIVERIES = ["push", "inbox", "digest", "off"];
4435
+ var SCOPES = ["mine", "everyone"];
4436
+ function isChannel(v) {
4437
+ return v !== void 0 && NOTIFICATION_CHANNELS.includes(v);
4438
+ }
4439
+ function handleApiError(e) {
4440
+ if (e instanceof HisaaboApiError) {
4441
+ const err = e.hisaaboError;
4442
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
4443
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
4444
+ }
4445
+ fatalError(String(e instanceof Error ? e.message : e));
4446
+ }
4447
+ async function notificationListCommand(opts) {
4448
+ const cfg = requireAuth();
4449
+ const client = new HisaaboClient(cfg);
4450
+ if (opts.channel && !isChannel(opts.channel)) {
4451
+ fatalError(`--channel must be one of: ${NOTIFICATION_CHANNELS.join(", ")}`, EXIT.USAGE);
4452
+ }
4453
+ const limit = opts.limit ? Number(opts.limit) : 30;
4454
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) fatalError("--limit must be 1\u2013100", EXIT.USAGE);
4455
+ try {
4456
+ const page = await client.notification.list({
4457
+ limit,
4458
+ unreadOnly: !!opts.unread,
4459
+ channel: opts.channel
4460
+ });
4461
+ if (opts.json) {
4462
+ outputJSON(page);
4463
+ return;
4464
+ }
4465
+ console.log("\n Notifications\n");
4466
+ const cols = [
4467
+ { key: "readAt", header: "", width: 2, format: (v) => v ? " " : "\u25CF" },
4468
+ { key: "createdAt", header: "Date", width: 12, format: (v) => formatDate(v) },
4469
+ { key: "channel", header: "Channel", width: 12 },
4470
+ { key: "title", header: "Title", width: 48 },
4471
+ { key: "id", header: "ID", width: 10, format: (v) => String(v ?? "").slice(0, 8) + "..." }
4472
+ ];
4473
+ outputTable(page.items, cols);
4474
+ } catch (e) {
4475
+ handleApiError(e);
4476
+ }
4477
+ }
4478
+ async function notificationReadCommand(ids, opts) {
4479
+ const cfg = requireAuth();
4480
+ const client = new HisaaboClient(cfg);
4481
+ if (!opts.all && ids.length === 0) fatalError("Pass notification ids, or --all", EXIT.USAGE);
4482
+ try {
4483
+ let updated;
4484
+ if (opts.all) {
4485
+ updated = (await client.notification.markAllRead()).updated;
4486
+ } else {
4487
+ const full = ids.some((id) => id.length < 36) ? await resolveIds(client, ids) : ids;
4488
+ updated = (await client.notification.markRead(full)).updated;
4489
+ }
4490
+ if (opts.json) outputJSON({ updated });
4491
+ else success(`Marked ${updated} notification${updated === 1 ? "" : "s"} as read`);
4492
+ } catch (e) {
4493
+ handleApiError(e);
4494
+ }
4495
+ }
4496
+ async function resolveIds(client, ids) {
4497
+ const page = await client.notification.list({ limit: 100 });
4498
+ return ids.map((id) => {
4499
+ const matches = page.items.filter((n) => n.id.startsWith(id.replace(/\.+$/, "")));
4500
+ if (matches.length !== 1) fatalError(`Could not resolve notification id "${id}"`, EXIT.USAGE);
4501
+ return matches[0].id;
4502
+ });
4503
+ }
4504
+ async function notificationPrefsCommand(opts) {
4505
+ const cfg = requireAuth();
4506
+ const client = new HisaaboClient(cfg);
4507
+ try {
4508
+ const prefs = await client.notification.getPreferences(opts.business ?? null);
4509
+ if (opts.json) {
4510
+ outputJSON(prefs);
4511
+ return;
4512
+ }
4513
+ console.log(`
4514
+ Notification preferences (${opts.business ? "this business" : "organization default"}, role: ${prefs.role})
4515
+ `);
4516
+ const cols = [
4517
+ { key: "channel", header: "Channel", width: 12 },
4518
+ { key: "name", header: "Name", width: 26 },
4519
+ { key: "preference", header: "Delivery", width: 9, format: (_v, row) => row.available ? row.preference.delivery : "\u2014" },
4520
+ { key: "preference", header: "Scope", width: 9, format: (_v, row) => row.scopeable ? row.preference.scope : "" },
4521
+ { key: "locked", header: "Locked", width: 7, format: (v) => v ? "yes" : "" },
4522
+ { key: "source", header: "From", width: 13 }
4523
+ ];
4524
+ outputTable(prefs.channels, cols);
4525
+ } catch (e) {
4526
+ handleApiError(e);
4527
+ }
4528
+ }
4529
+ async function notificationSetCommand(channel, opts) {
4530
+ const cfg = requireAuth();
4531
+ const client = new HisaaboClient(cfg);
4532
+ if (!isChannel(channel)) fatalError(`Channel must be one of: ${NOTIFICATION_CHANNELS.join(", ")}`, EXIT.USAGE);
4533
+ if (opts.delivery && !DELIVERIES.includes(opts.delivery)) {
4534
+ fatalError(`--delivery must be one of: ${DELIVERIES.join(", ")}`, EXIT.USAGE);
4535
+ }
4536
+ if (opts.scope && !SCOPES.includes(opts.scope)) {
4537
+ fatalError(`--scope must be one of: ${SCOPES.join(", ")}`, EXIT.USAGE);
4538
+ }
4539
+ let thresholdPaise;
4540
+ if (opts.threshold !== void 0) {
4541
+ if (opts.threshold === "none") thresholdPaise = null;
4542
+ else {
4543
+ const rupees = Number(opts.threshold);
4544
+ if (!Number.isFinite(rupees) || rupees < 0) fatalError("--threshold must be an amount in rupees, or 'none'", EXIT.USAGE);
4545
+ thresholdPaise = Math.round(rupees * 100);
4546
+ }
4547
+ }
4548
+ if (!opts.reset && !opts.delivery && !opts.scope && thresholdPaise === void 0 && opts.email === void 0) {
4549
+ fatalError("Nothing to change: pass --delivery, --scope, --threshold, --email/--no-email or --reset", EXIT.USAGE);
4550
+ }
4551
+ try {
4552
+ await client.notification.updatePreference({
4553
+ businessId: opts.business ?? null,
4554
+ channel,
4555
+ delivery: opts.delivery,
4556
+ scope: opts.scope,
4557
+ thresholdPaise,
4558
+ email: opts.email,
4559
+ reset: opts.reset
4560
+ });
4561
+ if (opts.json) outputJSON({ ok: true });
4562
+ else success(opts.reset ? `Reset ${channel} preference` : `Updated ${channel} preference`);
4563
+ } catch (e) {
4564
+ handleApiError(e);
4565
+ }
4566
+ }
4567
+
4568
+ // src/bin/registrars/notification.ts
4569
+ function registerNotificationCommands(program2) {
4570
+ const notifications = program2.command("notifications").description("Notification inbox and preferences");
4571
+ notifications.command("list").description("List notifications for the active business").option("--json", "JSON output").option("--unread", "Only unread notifications").option("--channel <channel>", "Only one channel (money_in, collections, store, compliance, security, \u2026)").option("--limit <n>", "Number of notifications (1\u2013100)", "30").action(async (opts) => {
4572
+ await notificationListCommand({ json: opts.json, unread: opts.unread, channel: opts.channel, limit: opts.limit });
4573
+ });
4574
+ notifications.command("read").description("Mark notifications as read").argument("[ids...]", "Notification ids (full or the short prefix shown by `list`)").option("--all", "Mark everything in the active business as read").option("--json", "JSON output").action(async (ids, opts) => {
4575
+ await notificationReadCommand(ids, { all: opts.all, json: opts.json });
4576
+ });
4577
+ notifications.command("prefs").description("Show your notification preferences per channel").option("--business <id>", "Preferences for one business (default: organization-wide)").option("--json", "JSON output").action(async (opts) => {
4578
+ await notificationPrefsCommand({ json: opts.json, business: opts.business });
4579
+ });
4580
+ notifications.command("set").description("Change your preference for one channel").argument("<channel>", "Channel id, e.g. sales").option("--delivery <mode>", "push, inbox, digest or off").option("--scope <scope>", "mine or everyone").option("--threshold <rupees>", "Push only at or above this amount ('none' to clear)").option("--email", "Also send an email copy").option("--no-email", "Stop email copies").option("--business <id>", "Only for this business (default: organization-wide)").option("--reset", "Remove your override for this channel").option("--json", "JSON output").action(async (channel, opts) => {
4581
+ await notificationSetCommand(channel, {
4582
+ json: opts.json,
4583
+ business: opts.business,
4584
+ delivery: opts.delivery,
4585
+ scope: opts.scope,
4586
+ threshold: opts.threshold,
4587
+ // commander sets email=true by default when --no-email is declared; only pass it when given
4588
+ email: process.argv.includes("--email") ? true : process.argv.includes("--no-email") ? false : void 0,
4589
+ reset: opts.reset
4590
+ });
4591
+ });
4592
+ }
4593
+
3451
4594
  // src/bin/registrars/store.ts
3452
4595
  function registerStoreCommands(program2) {
3453
4596
  const store = program2.command("store").description("Online store management");
3454
4597
  store.command("settings").description("Show store settings").option("--json", "JSON output").action(async (opts) => {
3455
- const { storeSettingsCommand } = await import("./store-SVRZBUFO.js");
4598
+ const { storeSettingsCommand } = await import("./store-DDMHTNTO.js");
3456
4599
  await storeSettingsCommand({ json: opts.json });
3457
4600
  });
3458
- 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) => {
3459
- const { storeUpdateSettingsCommand } = await import("./update-settings-AASI6WZX.js");
4601
+ store.command("update-settings").description("Update store settings").option("--slug <slug>", "Store URL slug (can only be set once)").option("--tagline <text>", "Store tagline / description").option("--enabled <bool>", "Enable or disable store (true/false)").option("--require-phone-otp <bool>", "Require customers to verify their phone by SMS code (true/false; needs an SMS provider on the server)").option("--json", "JSON output").action(async (opts) => {
4602
+ const { storeUpdateSettingsCommand } = await import("./update-settings-UGXLQRYI.js");
3460
4603
  await storeUpdateSettingsCommand({
3461
4604
  slug: opts.slug,
3462
4605
  tagline: opts.tagline,
3463
4606
  enabled: opts.enabled,
4607
+ requirePhoneOtp: opts.requirePhoneOtp,
3464
4608
  json: opts.json
3465
4609
  });
3466
4610
  });
3467
4611
  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) => {
3468
- const { storeItemsCommand } = await import("./items-6NOIMH6B.js");
4612
+ const { storeItemsCommand } = await import("./items-PJPN6ZX3.js");
3469
4613
  await storeItemsCommand({ json: opts.json, format: opts.format });
3470
4614
  });
3471
4615
  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) => {
3472
- const { storeItemsToggleCommand } = await import("./items-toggle-L6W6QKQD.js");
4616
+ const { storeItemsToggleCommand } = await import("./items-toggle-53C35MJU.js");
3473
4617
  await storeItemsToggleCommand({
3474
4618
  enable: opts.enable,
3475
4619
  disable: opts.disable,
@@ -3477,7 +4621,7 @@ function registerStoreCommands(program2) {
3477
4621
  });
3478
4622
  });
3479
4623
  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) => {
3480
- const { storeOrdersCommand } = await import("./store-SVRZBUFO.js");
4624
+ const { storeOrdersCommand } = await import("./store-DDMHTNTO.js");
3481
4625
  await storeOrdersCommand({
3482
4626
  json: opts.json,
3483
4627
  status: opts.status,
@@ -3486,15 +4630,15 @@ function registerStoreCommands(program2) {
3486
4630
  });
3487
4631
  });
3488
4632
  store.command("order-get <id>").description("Get order details").option("--json", "JSON output").action(async (id, opts) => {
3489
- const { storeOrderGetCommand } = await import("./order-get-4XAQCRYV.js");
4633
+ const { storeOrderGetCommand } = await import("./order-get-QPSOY2RT.js");
3490
4634
  await storeOrderGetCommand(id, { json: opts.json });
3491
4635
  });
3492
4636
  store.command("order-confirm <id>").description("Confirm a pending order").option("-y, --yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
3493
- const { storeOrderConfirmCommand } = await import("./order-confirm-LGQOMC4O.js");
4637
+ const { storeOrderConfirmCommand } = await import("./order-confirm-NXFL2EIQ.js");
3494
4638
  await storeOrderConfirmCommand(id, { json: opts.json, yes: opts.yes });
3495
4639
  });
3496
4640
  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) => {
3497
- const { storeOrderCancelCommand } = await import("./order-cancel-QRTCNART.js");
4641
+ const { storeOrderCancelCommand } = await import("./order-cancel-RW4NYHKN.js");
3498
4642
  await storeOrderCancelCommand(id, {
3499
4643
  json: opts.json,
3500
4644
  yes: opts.yes,
@@ -3502,38 +4646,124 @@ function registerStoreCommands(program2) {
3502
4646
  });
3503
4647
  });
3504
4648
  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) => {
3505
- const { storeOrderUpdateCommand } = await import("./order-update-KZY4H2UR.js");
4649
+ const { storeOrderUpdateCommand } = await import("./order-update-7DWKEROO.js");
3506
4650
  await storeOrderUpdateCommand(id, { json: opts.json, status: opts.status });
3507
4651
  });
3508
4652
  store.command("check-slug <slug>").description("Check store slug availability").option("--json", "JSON output").action(async (slug, opts) => {
3509
- const { storeCheckSlugCommand } = await import("./check-slug-P7RFU6OP.js");
4653
+ const { storeCheckSlugCommand } = await import("./check-slug-5L2VDAEN.js");
3510
4654
  await storeCheckSlugCommand(slug, { json: opts.json });
3511
4655
  });
3512
4656
  }
3513
4657
 
3514
4658
  // src/commands/import/index.ts
3515
- import * as fs3 from "fs";
4659
+ import * as fs2 from "fs";
3516
4660
  import * as path2 from "path";
3517
- function readJsonFile(filePath) {
4661
+
4662
+ // src/csv.ts
4663
+ function parseCsv(text) {
4664
+ const src = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
4665
+ const rows = [];
4666
+ let row = [];
4667
+ let field = "";
4668
+ let inQuotes = false;
4669
+ let i = 0;
4670
+ const endRow = () => {
4671
+ row.push(field);
4672
+ field = "";
4673
+ if (!(row.length === 1 && row[0] === "")) rows.push(row);
4674
+ row = [];
4675
+ };
4676
+ while (i < src.length) {
4677
+ const ch = src[i];
4678
+ if (inQuotes) {
4679
+ if (ch === '"') {
4680
+ if (src[i + 1] === '"') {
4681
+ field += '"';
4682
+ i += 2;
4683
+ continue;
4684
+ }
4685
+ inQuotes = false;
4686
+ i++;
4687
+ continue;
4688
+ }
4689
+ field += ch;
4690
+ i++;
4691
+ continue;
4692
+ }
4693
+ if (ch === '"' && field === "") {
4694
+ inQuotes = true;
4695
+ i++;
4696
+ } else if (ch === ",") {
4697
+ row.push(field);
4698
+ field = "";
4699
+ i++;
4700
+ } else if (ch === "\r" || ch === "\n") {
4701
+ if (ch === "\r" && src[i + 1] === "\n") i++;
4702
+ endRow();
4703
+ i++;
4704
+ } else {
4705
+ field += ch;
4706
+ i++;
4707
+ }
4708
+ }
4709
+ if (inQuotes) throw new Error("Unterminated quoted field in CSV");
4710
+ if (field !== "" || row.length > 0) endRow();
4711
+ return rows;
4712
+ }
4713
+
4714
+ // src/commands/import/index.ts
4715
+ var MAX_FILE_BYTES = 10 * 1024 * 1024;
4716
+ var MAX_ROWS = 5e3;
4717
+ var DEFAULT_SOURCE = "hisaabo";
4718
+ function readInputFile(filePath) {
3518
4719
  const abs = path2.resolve(filePath);
3519
- if (!fs3.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
3520
- const raw = fs3.readFileSync(abs, "utf-8");
4720
+ let fd;
4721
+ try {
4722
+ fd = fs2.openSync(abs, fs2.constants.O_RDONLY);
4723
+ } catch {
4724
+ return fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
4725
+ }
4726
+ try {
4727
+ const st = fs2.fstatSync(fd);
4728
+ if (!st.isFile()) fatalError(`Not a regular file: ${abs}`, EXIT.USAGE);
4729
+ if (st.size > MAX_FILE_BYTES) {
4730
+ fatalError(`File too large (${Math.round(st.size / 1024 / 1024)} MB; max ${MAX_FILE_BYTES / 1024 / 1024} MB)`, EXIT.USAGE);
4731
+ }
4732
+ const buf = Buffer.alloc(MAX_FILE_BYTES + 1);
4733
+ let len = 0;
4734
+ for (; ; ) {
4735
+ const n = fs2.readSync(fd, buf, len, buf.length - len, null);
4736
+ if (n === 0) break;
4737
+ len += n;
4738
+ if (len > MAX_FILE_BYTES) {
4739
+ fatalError(`File too large (max ${MAX_FILE_BYTES / 1024 / 1024} MB)`, EXIT.USAGE);
4740
+ }
4741
+ }
4742
+ return buf.toString("utf-8", 0, len);
4743
+ } finally {
4744
+ fs2.closeSync(fd);
4745
+ }
4746
+ }
4747
+ function readJsonFile(filePath) {
4748
+ const raw = readInputFile(filePath);
3521
4749
  try {
3522
4750
  const parsed = JSON.parse(raw);
3523
4751
  if (!Array.isArray(parsed)) fatalError("Expected a JSON array", EXIT.USAGE);
3524
4752
  return parsed;
3525
4753
  } catch {
3526
- fatalError(`Invalid JSON in file: ${abs}`, EXIT.USAGE);
4754
+ return fatalError(`Invalid JSON in file: ${path2.resolve(filePath)}`, EXIT.USAGE);
3527
4755
  }
3528
4756
  }
3529
4757
  function readCsvFile(filePath) {
3530
- const abs = path2.resolve(filePath);
3531
- if (!fs3.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
3532
- const lines = fs3.readFileSync(abs, "utf-8").split("\n").filter((l) => l.trim());
3533
- if (lines.length < 2) fatalError("CSV must have at least a header row and one data row", EXIT.USAGE);
3534
- const headers = (lines[0] ?? "").split(",").map((h) => h.trim().replace(/^"|"$/g, ""));
3535
- return lines.slice(1).map((line) => {
3536
- const vals = line.split(",").map((v) => v.trim().replace(/^"|"$/g, ""));
4758
+ let rows;
4759
+ try {
4760
+ rows = parseCsv(readInputFile(filePath));
4761
+ } catch (e) {
4762
+ return fatalError(`Invalid CSV: ${e instanceof Error ? e.message : String(e)}`, EXIT.USAGE);
4763
+ }
4764
+ if (rows.length < 2) fatalError("CSV must have at least a header row and one data row", EXIT.USAGE);
4765
+ const headers = (rows[0] ?? []).map((h) => h.trim());
4766
+ return rows.slice(1).map((vals) => {
3537
4767
  const obj = {};
3538
4768
  headers.forEach((h, i) => {
3539
4769
  obj[h] = vals[i] ?? "";
@@ -3541,71 +4771,35 @@ function readCsvFile(filePath) {
3541
4771
  return obj;
3542
4772
  });
3543
4773
  }
3544
- async function importPartiesCommand(filePath, opts) {
3545
- const cfg = requireAuth();
3546
- const client = new HisaaboClient(cfg);
3547
- const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
4774
+ function loadRows(filePath, opts) {
4775
+ const fmt = opts.format ?? (filePath.toLowerCase().endsWith(".csv") ? "csv" : "json");
4776
+ if (fmt !== "csv" && fmt !== "json") fatalError("--format must be json or csv", EXIT.USAGE);
3548
4777
  const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3549
- console.log(` Importing ${data.length} parties...`);
3550
- try {
3551
- const result = await client.import.importParties({ parties: data });
3552
- if (opts.json) {
3553
- outputJSON(result);
3554
- return;
3555
- }
3556
- success(`Imported: ${result.imported} parties`);
3557
- if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3558
- result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3559
- } catch (e) {
3560
- if (e instanceof HisaaboApiError) {
3561
- const err = e.hisaaboError;
3562
- if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3563
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3564
- if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3565
- }
3566
- fatalError(String(e instanceof Error ? e.message : e));
4778
+ if (data.length > MAX_ROWS) {
4779
+ fatalError(`Too many rows (${data.length}; max ${MAX_ROWS} per import). Split the file.`, EXIT.USAGE);
3567
4780
  }
4781
+ return data;
3568
4782
  }
3569
- async function importItemsCommand(filePath, opts) {
3570
- const cfg = requireAuth();
3571
- const client = new HisaaboClient(cfg);
3572
- const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3573
- const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3574
- console.log(` Importing ${data.length} items...`);
3575
- try {
3576
- const result = await client.import.importItems({ items: data });
3577
- if (opts.json) {
3578
- outputJSON(result);
3579
- return;
3580
- }
3581
- success(`Imported: ${result.imported} items`);
3582
- if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3583
- result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3584
- } catch (e) {
3585
- if (e instanceof HisaaboApiError) {
3586
- const err = e.hisaaboError;
3587
- if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3588
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3589
- if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3590
- }
3591
- fatalError(String(e instanceof Error ? e.message : e));
3592
- }
4783
+ function resolveSource(opts) {
4784
+ const source = opts.source ?? DEFAULT_SOURCE;
4785
+ if (!/^[a-z0-9_-]{1,50}$/i.test(source)) fatalError("Invalid --source", EXIT.USAGE);
4786
+ return source;
3593
4787
  }
3594
- async function importInvoicesCommand(filePath, opts) {
4788
+ async function runImport(label, filePath, opts, send) {
3595
4789
  const cfg = requireAuth();
3596
4790
  const client = new HisaaboClient(cfg);
3597
- const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3598
- const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3599
- console.log(` Importing ${data.length} invoices...`);
4791
+ const source = resolveSource(opts);
4792
+ const data = loadRows(filePath, opts);
4793
+ console.log(` Importing ${data.length} ${label}...`);
3600
4794
  try {
3601
- const result = await client.import.importInvoices({ invoices: data });
4795
+ const result = await send(client, data, source);
3602
4796
  if (opts.json) {
3603
4797
  outputJSON(result);
3604
4798
  return;
3605
4799
  }
3606
- success(`Imported: ${result.imported} invoices`);
4800
+ success(`Imported: ${result.created} ${label}`);
3607
4801
  if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3608
- result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
4802
+ (result.errors ?? []).forEach((e) => console.error(` ${e}`));
3609
4803
  } catch (e) {
3610
4804
  if (e instanceof HisaaboApiError) {
3611
4805
  const err = e.hisaaboError;
@@ -3616,46 +4810,33 @@ async function importInvoicesCommand(filePath, opts) {
3616
4810
  fatalError(String(e instanceof Error ? e.message : e));
3617
4811
  }
3618
4812
  }
3619
- async function importPaymentsCommand(filePath, opts) {
3620
- const cfg = requireAuth();
3621
- const client = new HisaaboClient(cfg);
3622
- const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
3623
- const data = fmt === "csv" ? readCsvFile(filePath) : readJsonFile(filePath);
3624
- console.log(` Importing ${data.length} payments...`);
3625
- try {
3626
- const result = await client.import.importPayments({ payments: data });
3627
- if (opts.json) {
3628
- outputJSON(result);
3629
- return;
3630
- }
3631
- success(`Imported: ${result.imported} payments`);
3632
- if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
3633
- result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
3634
- } catch (e) {
3635
- if (e instanceof HisaaboApiError) {
3636
- const err = e.hisaaboError;
3637
- if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
3638
- if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
3639
- if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
3640
- }
3641
- fatalError(String(e instanceof Error ? e.message : e));
3642
- }
4813
+ function importPartiesCommand(filePath, opts) {
4814
+ return runImport("parties", filePath, opts, (c, parties, source) => c.import.importParties({ source, parties }));
4815
+ }
4816
+ function importItemsCommand(filePath, opts) {
4817
+ return runImport("items", filePath, opts, (c, items, source) => c.import.importItems({ source, items }));
4818
+ }
4819
+ function importInvoicesCommand(filePath, opts) {
4820
+ return runImport("invoices", filePath, opts, (c, invoices, source) => c.import.importInvoices({ source, invoices }));
4821
+ }
4822
+ function importPaymentsCommand(filePath, opts) {
4823
+ return runImport("payments", filePath, opts, (c, payments, source) => c.import.importPayments({ source, payments }));
3643
4824
  }
3644
4825
 
3645
4826
  // src/bin/registrars/import.ts
3646
4827
  function registerImportCommands(program2) {
3647
4828
  const importCmd = program2.command("import").description("Bulk import data");
3648
- 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) => {
3649
- await importPartiesCommand(file, { json: opts.json, format: opts.format });
4829
+ 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)").option("--source <source>", "Import source adapter (default: hisaabo; or mybillbook)").action(async (file, opts) => {
4830
+ await importPartiesCommand(file, { json: opts.json, format: opts.format, source: opts.source });
3650
4831
  });
3651
- 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) => {
3652
- await importItemsCommand(file, { json: opts.json, format: opts.format });
4832
+ 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)").option("--source <source>", "Import source adapter (default: hisaabo; or mybillbook)").action(async (file, opts) => {
4833
+ await importItemsCommand(file, { json: opts.json, format: opts.format, source: opts.source });
3653
4834
  });
3654
- 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) => {
3655
- await importInvoicesCommand(file, { json: opts.json, format: opts.format });
4835
+ 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)").option("--source <source>", "Import source adapter (default: hisaabo; or mybillbook)").action(async (file, opts) => {
4836
+ await importInvoicesCommand(file, { json: opts.json, format: opts.format, source: opts.source });
3656
4837
  });
3657
- 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) => {
3658
- await importPaymentsCommand(file, { json: opts.json, format: opts.format });
4838
+ 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)").option("--source <source>", "Import source adapter (default: hisaabo; or mybillbook)").action(async (file, opts) => {
4839
+ await importPaymentsCommand(file, { json: opts.json, format: opts.format, source: opts.source });
3659
4840
  });
3660
4841
  }
3661
4842
 
@@ -3807,7 +4988,7 @@ async function automatedInvoiceGetCommand(id, opts) {
3807
4988
  `);
3808
4989
  tmpl.lineItems.forEach((item, i) => {
3809
4990
  const idx = String(i + 1).padStart(2);
3810
- const desc = item.description.slice(0, 18).padEnd(18);
4991
+ const desc = item.itemName.slice(0, 18).padEnd(18);
3811
4992
  const qty = item.quantity.padStart(5);
3812
4993
  const rate = formatAmount(item.unitPrice).padStart(10);
3813
4994
  const tax = item.taxPercent ? `${item.taxPercent}%`.padStart(5) : " -";
@@ -3854,7 +5035,7 @@ async function automatedInvoiceCreateCommand(opts) {
3854
5035
  fatalError("--custom-interval-days is required when frequency is 'custom'", EXIT.USAGE);
3855
5036
  }
3856
5037
  const lineItems = items.map((desc, i) => ({
3857
- description: desc,
5038
+ itemName: desc,
3858
5039
  quantity: qtys[i] ?? "1",
3859
5040
  unitPrice: rates[i] ?? "0",
3860
5041
  taxPercent: taxes[i],
@@ -3890,24 +5071,29 @@ async function automatedInvoiceCreateCommand(opts) {
3890
5071
  }
3891
5072
 
3892
5073
  // src/commands/automated-invoice/update.ts
5074
+ var FREQUENCIES = ["weekly", "biweekly", "monthly", "quarterly", "half_yearly", "yearly", "custom"];
5075
+ function isFrequency(v) {
5076
+ return FREQUENCIES.includes(v);
5077
+ }
3893
5078
  async function automatedInvoiceUpdateCommand(id, opts) {
3894
5079
  const cfg = requireAuth();
3895
5080
  const client = new HisaaboClient(cfg);
3896
5081
  const data = {};
3897
- if (opts.name !== void 0) data["name"] = opts.name;
3898
- if (opts.frequency !== void 0) data["frequency"] = opts.frequency;
3899
- if (opts.startDate !== void 0) data["startDate"] = opts.startDate;
3900
- if (opts.endDate !== void 0) data["endDate"] = opts.endDate;
3901
- if (opts.maxRuns !== void 0) data["maxRuns"] = parseInt(opts.maxRuns, 10);
3902
- if (opts.notes !== void 0) data["notes"] = opts.notes;
5082
+ if (opts.name !== void 0) data.name = opts.name;
5083
+ if (opts.frequency !== void 0) {
5084
+ if (!isFrequency(opts.frequency)) {
5085
+ fatalError(`--frequency must be one of: ${FREQUENCIES.join(", ")}`, EXIT.USAGE);
5086
+ }
5087
+ data.frequency = opts.frequency;
5088
+ }
5089
+ if (opts.endDate !== void 0) data.endDate = toApiDateTime(opts.endDate, "end");
5090
+ if (opts.maxRuns !== void 0) data.maxRuns = parseInt(opts.maxRuns, 10);
5091
+ if (opts.notes !== void 0) data.notes = opts.notes;
3903
5092
  if (Object.keys(data).length === 0) {
3904
5093
  fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
3905
5094
  }
3906
5095
  try {
3907
- const result = await client.recurringInvoice.update(
3908
- id,
3909
- data
3910
- );
5096
+ const result = await client.recurringInvoice.update(id, data);
3911
5097
  if (opts.json) {
3912
5098
  outputJSON(result);
3913
5099
  return;
@@ -3995,22 +5181,11 @@ async function automatedInvoiceRunNowCommand(id, opts) {
3995
5181
  }
3996
5182
 
3997
5183
  // src/commands/automated-invoice/delete.ts
3998
- import * as readline12 from "readline";
3999
5184
  async function automatedInvoiceDeleteCommand(id, opts) {
4000
5185
  const cfg = requireAuth();
4001
5186
  const client = new HisaaboClient(cfg);
4002
5187
  try {
4003
- if (!opts.yes && process.stdin.isTTY) {
4004
- const rl = readline12.createInterface({ input: process.stdin, output: process.stdout });
4005
- const answer = await new Promise((resolve2) => {
4006
- rl.question(` Delete recurring invoice template ${id}? (y/N): `, resolve2);
4007
- });
4008
- rl.close();
4009
- if (answer.trim().toLowerCase() !== "y") {
4010
- console.log(" Cancelled.");
4011
- process.exit(0);
4012
- }
4013
- }
5188
+ await confirmOrExit(` Delete recurring invoice template ${id}?`, opts);
4014
5189
  const result = await client.recurringInvoice.delete(id);
4015
5190
  if (opts.json) {
4016
5191
  outputJSON(result);
@@ -4133,13 +5308,6 @@ var FREQUENCY_LABELS3 = {
4133
5308
  yearly: "Yearly",
4134
5309
  custom: "Custom"
4135
5310
  };
4136
- function confidenceBadge(confidence) {
4137
- const pct = Math.round(confidence * 100);
4138
- const label = `${pct}%`;
4139
- if (confidence >= 0.8) return chalk6.green(label);
4140
- if (confidence >= 0.5) return chalk6.yellow(label);
4141
- return chalk6.dim(label);
4142
- }
4143
5311
  async function automatedInvoiceSuggestionsCommand(opts) {
4144
5312
  const cfg = requireAuth();
4145
5313
  const client = new HisaaboClient(cfg);
@@ -4159,9 +5327,10 @@ async function automatedInvoiceSuggestionsCommand(opts) {
4159
5327
  `);
4160
5328
  const cols = [
4161
5329
  { key: "partyName", header: "Party", width: 24 },
4162
- { key: "frequency", header: "Suggested Frequency", width: 20, format: (v) => FREQUENCY_LABELS3[String(v ?? "")] ?? String(v ?? "") },
4163
- { key: "confidence", header: "Confidence", width: 12, align: "right", format: (v) => confidenceBadge(Number(v ?? 0)) },
4164
- { key: "reason", header: "Reason", width: 36 }
5330
+ { key: "suggestedFrequency", header: "Suggested Frequency", width: 20, format: (v) => FREQUENCY_LABELS3[String(v ?? "")] ?? String(v ?? "") },
5331
+ { key: "invoiceCount", header: "Invoices", width: 10, align: "right" },
5332
+ { key: "medianAmount", header: "Median \u20B9", width: 14, align: "right" },
5333
+ { key: "medianIntervalDays", header: "Interval (days)", width: 16, align: "right" }
4165
5334
  ];
4166
5335
  outputTable(result, cols);
4167
5336
  console.log();
@@ -4223,12 +5392,11 @@ function registerAutomatedInvoiceCommands(program2) {
4223
5392
  automatedInvoice.command("delete <id>").description("Delete a recurring invoice template").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
4224
5393
  await automatedInvoiceDeleteCommand(id, { yes: opts.yes, json: opts.json });
4225
5394
  });
4226
- 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) => {
5395
+ 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("--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) => {
4227
5396
  await automatedInvoiceUpdateCommand(id, {
4228
5397
  json: opts.json,
4229
5398
  name: opts.name,
4230
5399
  frequency: opts.frequency,
4231
- startDate: opts.startDate,
4232
5400
  endDate: opts.endDate,
4233
5401
  maxRuns: opts.maxRuns,
4234
5402
  notes: opts.notes
@@ -4251,7 +5419,7 @@ function registerAutomatedInvoiceCommands(program2) {
4251
5419
  }
4252
5420
 
4253
5421
  // src/bin/registrars/business.ts
4254
- import * as readline13 from "readline";
5422
+ import * as readline7 from "readline";
4255
5423
  function registerBusinessCommands(program2) {
4256
5424
  const business = program2.command("business").description("Business management");
4257
5425
  business.command("list").description("List all businesses").option("--json", "JSON output").action(async (opts) => {
@@ -4273,23 +5441,23 @@ function registerBusinessCommands(program2) {
4273
5441
  }
4274
5442
  });
4275
5443
  business.command("get").description("Show current business details").option("--json", "JSON output").action(async (opts) => {
4276
- const { businessGetCommand } = await import("./get-GMQRROK2.js");
5444
+ const { businessGetCommand } = await import("./get-HGMB7T6Y.js");
4277
5445
  await businessGetCommand(opts);
4278
5446
  });
4279
- 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) => {
4280
- const { businessUpdateCommand } = await import("./update-EGHPFXLK.js");
5447
+ 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("--json", "JSON output").action(async (opts) => {
5448
+ const { businessUpdateCommand } = await import("./update-I2DZRVLR.js");
4281
5449
  await businessUpdateCommand(opts);
4282
5450
  });
4283
- 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) => {
4284
- const { businessSequenceCommand } = await import("./sequence-KZWADVD7.js");
5451
+ business.command("sequence").description("Set the next document number (cannot go backwards)").requiredOption("--type <type>", "Document type: invoice, payment, quotation, credit_note, delivery_challan, proforma").requiredOption("--next-number <n>", "Next sequence number").option("--json", "JSON output").action(async (opts) => {
5452
+ const { businessSequenceCommand } = await import("./sequence-HOQ4PQRK.js");
4285
5453
  await businessSequenceCommand(opts);
4286
5454
  });
4287
5455
  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) => {
4288
- const { businessAuditTrailCommand } = await import("./audit-trail-IJ6SKACR.js");
5456
+ const { businessAuditTrailCommand } = await import("./audit-trail-RTPTWZAL.js");
4289
5457
  await businessAuditTrailCommand(opts);
4290
5458
  });
4291
5459
  business.command("export").description("Export all business data").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (opts) => {
4292
- const { businessExportCommand } = await import("./export-YOOODNVX.js");
5460
+ const { businessExportCommand } = await import("./export-GFYQIQLT.js");
4293
5461
  await businessExportCommand(opts);
4294
5462
  });
4295
5463
  business.command("switch").description("Switch active business").option("--json", "JSON output").action(async (opts) => {
@@ -4305,7 +5473,7 @@ function registerBusinessCommands(program2) {
4305
5473
  const active = b.id === cfg.businessId ? " [active]" : "";
4306
5474
  console.log(` ${i + 1} ${b.name.padEnd(28)}${active}`);
4307
5475
  });
4308
- const rl = readline13.createInterface({ input: process.stdin, output: process.stdout });
5476
+ const rl = readline7.createInterface({ input: process.stdin, output: process.stdout });
4309
5477
  const answer = await new Promise((res) => rl.question("\n Select: ", res));
4310
5478
  rl.close();
4311
5479
  const idx = parseInt(answer.trim(), 10) - 1;
@@ -4323,6 +5491,16 @@ function registerBusinessCommands(program2) {
4323
5491
  }
4324
5492
 
4325
5493
  // src/bin/registrars/document.ts
5494
+ var CONVERT_TARGET_TYPES = [
5495
+ "invoice",
5496
+ "quotation",
5497
+ "credit_note",
5498
+ "debit_note",
5499
+ "delivery_challan",
5500
+ "proforma",
5501
+ "sales_return",
5502
+ "purchase_return"
5503
+ ];
4326
5504
  var DOC_TYPES = [
4327
5505
  {
4328
5506
  cmd: "quotation",
@@ -4371,59 +5549,49 @@ function registerDocumentCommands(program2) {
4371
5549
  for (const dt of DOC_TYPES) {
4372
5550
  const parent = program2.command(dt.cmd).description(`${dt.label} management`);
4373
5551
  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) => {
4374
- const { docListCommand } = await import("./factory-6MUCSXTL.js");
5552
+ const { docListCommand } = await import("./factory-JSEQCPY3.js");
4375
5553
  await docListCommand(dt, opts);
4376
5554
  });
4377
5555
  parent.command("get <id>").description(`Get ${dt.label.toLowerCase()} details`).option("--json", "JSON output").action(async (id, opts) => {
4378
- const { docGetCommand } = await import("./factory-6MUCSXTL.js");
5556
+ const { docGetCommand } = await import("./factory-JSEQCPY3.js");
4379
5557
  await docGetCommand(dt, id, opts);
4380
5558
  });
4381
- 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) => {
4382
- const { docCreateCommand } = await import("./factory-6MUCSXTL.js");
5559
+ 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("--type <type>", "sale or purchase (default: sale)").option("-y, --yes", "Skip confirmation").action(async (opts) => {
5560
+ const { docCreateCommand } = await import("./factory-JSEQCPY3.js");
4383
5561
  await docCreateCommand(dt, opts);
4384
5562
  });
4385
5563
  parent.command("update-status <id> <status>").description(`Update ${dt.label.toLowerCase()} status (${dt.statuses.join(", ")})`).option("--json", "JSON output").action(async (id, status, opts) => {
4386
- const { docStatusCommand } = await import("./factory-6MUCSXTL.js");
5564
+ const { docStatusCommand } = await import("./factory-JSEQCPY3.js");
4387
5565
  await docStatusCommand(dt, id, status, opts);
4388
5566
  });
4389
5567
  parent.command("delete <id>").description(`Delete a ${dt.label.toLowerCase()}`).option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (id, opts) => {
4390
- const { docDeleteCommand } = await import("./factory-6MUCSXTL.js");
5568
+ const { docDeleteCommand } = await import("./factory-JSEQCPY3.js");
4391
5569
  await docDeleteCommand(dt, id, opts);
4392
5570
  });
4393
5571
  }
4394
5572
  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) => {
4395
- const { HisaaboClient: HisaaboClient2, HisaaboApiError: HisaaboApiError2 } = await import("./client-36JX5MR3.js");
4396
- const { requireAuth: requireAuth2 } = await import("./config-4LLNT4SH.js");
4397
- const { fatalError: fatalError2, outputJSON: outputJSON2, success: success2, EXIT: EXIT2 } = await import("./output-NUOL7KJW.js");
5573
+ const { HisaaboClient: HisaaboClient2, HisaaboApiError: HisaaboApiError2 } = await import("./client-NFYNYEDI.js");
5574
+ const { requireAuth: requireAuth2 } = await import("./config-7HVBRHL3.js");
5575
+ const { fatalError: fatalError2, outputJSON: outputJSON2, success: success2, EXIT: EXIT2 } = await import("./output-XFDIL3A6.js");
4398
5576
  const cfg = requireAuth2();
4399
5577
  const client = new HisaaboClient2(cfg);
4400
- if (!opts.yes && process.stdin.isTTY) {
4401
- const readline14 = await import("readline");
4402
- const rl = readline14.createInterface({ input: process.stdin, output: process.stdout });
4403
- const answer = await new Promise((resolve2) => {
4404
- rl.question(
4405
- ` Convert ${opts.fromType} ${opts.fromId} \u2192 ${opts.toType}? (y/N): `,
4406
- resolve2
4407
- );
4408
- });
4409
- rl.close();
4410
- if (answer.trim().toLowerCase() !== "y") {
4411
- console.log(" Cancelled.");
4412
- process.exit(EXIT2.SUCCESS);
4413
- }
5578
+ const { confirmOrExit: confirmOrExit2 } = await import("./safety-TPD2P7I5.js");
5579
+ await confirmOrExit2(` Convert ${opts.fromType} ${opts.fromId} \u2192 ${opts.toType}?`, opts);
5580
+ const targetType = String(opts.toType).replace(/-/g, "_");
5581
+ if (!CONVERT_TARGET_TYPES.includes(targetType)) {
5582
+ fatalError2(`--to-type must be one of: ${CONVERT_TARGET_TYPES.join(", ")}.`, EXIT2.USAGE);
4414
5583
  }
4415
5584
  try {
4416
5585
  const result = await client.document.convert({
4417
- fromType: opts.fromType,
4418
- fromId: opts.fromId,
4419
- toType: opts.toType
5586
+ sourceDocumentId: opts.fromId,
5587
+ targetDocumentType: targetType
4420
5588
  });
4421
5589
  if (opts.json) {
4422
5590
  outputJSON2(result);
4423
5591
  return;
4424
5592
  }
4425
- const newId = result.id ?? result.documentId ?? "(unknown)";
4426
- const newNum = result.documentNumber ?? result.number ?? newId;
5593
+ const newId = result.id;
5594
+ const newNum = result.invoiceNumber;
4427
5595
  success2(`Converted: ${opts.fromType} \u2192 ${opts.toType} ${newNum}`);
4428
5596
  console.log(` New ID: ${newId}
4429
5597
  `);
@@ -4445,31 +5613,31 @@ function registerDocumentCommands(program2) {
4445
5613
  function registerTenantCommands(program2) {
4446
5614
  const tenant = program2.command("tenant").description("Tenant / workspace management");
4447
5615
  tenant.command("list").description("List tenants / organizations you belong to").option("--json", "JSON output").action(async (opts) => {
4448
- const { tenantListCommand } = await import("./list-OXAVDXH7.js");
5616
+ const { tenantListCommand } = await import("./list-7OSZX6C7.js");
4449
5617
  await tenantListCommand({ json: opts.json });
4450
5618
  });
4451
5619
  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) => {
4452
- const { tenantMembersCommand } = await import("./members-Y6XJVHHR.js");
5620
+ const { tenantMembersCommand } = await import("./members-SPHU5F4M.js");
4453
5621
  await tenantMembersCommand({ json: opts.json, format: opts.format });
4454
5622
  });
4455
5623
  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) => {
4456
- const { tenantInviteCommand } = await import("./invite-GGHBZY4U.js");
5624
+ const { tenantInviteCommand } = await import("./invite-VCBXS7VY.js");
4457
5625
  await tenantInviteCommand(email, { role: opts.role, json: opts.json });
4458
5626
  });
4459
5627
  tenant.command("remove <userId>").description("Remove a member from the tenant").option("-y, --yes", "Skip confirmation").option("--json", "JSON output").action(async (userId, opts) => {
4460
- const { tenantRemoveCommand } = await import("./remove-ZBX34TIQ.js");
5628
+ const { tenantRemoveCommand } = await import("./remove-TC4UWMOL.js");
4461
5629
  await tenantRemoveCommand(userId, { yes: opts.yes, json: opts.json });
4462
5630
  });
4463
5631
  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) => {
4464
- const { tenantUpdateRoleCommand } = await import("./update-role-24PDTNFK.js");
5632
+ const { tenantUpdateRoleCommand } = await import("./update-role-D2ETEL2Q.js");
4465
5633
  await tenantUpdateRoleCommand(userId, role, { json: opts.json });
4466
5634
  });
4467
5635
  tenant.command("invitations").description("List pending invitations").option("--json", "JSON output").action(async (opts) => {
4468
- const { listInvitationsCommand } = await import("./invitations-OVORTTMF.js");
5636
+ const { listInvitationsCommand } = await import("./invitations-LASABD2X.js");
4469
5637
  await listInvitationsCommand(opts);
4470
5638
  });
4471
- tenant.command("revoke-invitation <invitationId>").description("Revoke a pending invitation").option("--json", "JSON output").action(async (invitationId, opts) => {
4472
- const { revokeInvitationCommand } = await import("./revoke-invitation-PQH7XNYA.js");
5639
+ tenant.command("revoke-invitation <invitationId>").description("Revoke a pending invitation").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (invitationId, opts) => {
5640
+ const { revokeInvitationCommand } = await import("./revoke-invitation-Z33EUJTS.js");
4473
5641
  await revokeInvitationCommand(invitationId, opts);
4474
5642
  });
4475
5643
  }
@@ -4478,15 +5646,15 @@ function registerTenantCommands(program2) {
4478
5646
  function registerApiKeyCommands(program2) {
4479
5647
  const apiKey = program2.command("api-key").alias("key").description("API key management");
4480
5648
  apiKey.command("list").description("List all API keys").option("--json", "JSON output").option("--format <fmt>", "Output format: table, tsv, csv").action(async (opts) => {
4481
- const { apiKeyListCommand } = await import("./list-FC5JHKHD.js");
5649
+ const { apiKeyListCommand } = await import("./list-OOROCQR2.js");
4482
5650
  await apiKeyListCommand(opts);
4483
5651
  });
4484
- apiKey.command("create").description("Create a new API key").requiredOption("--name <name>", "Name / label for this key").option("--json", "JSON output").action(async (opts) => {
4485
- const { apiKeyCreateCommand } = await import("./create-C5INBPQO.js");
5652
+ apiKey.command("create").description("Create a new API key").requiredOption("--name <name>", "Name / label for this key").option("--expires-in-days <n>", "Days until the key expires", "90").option("--json", "JSON output").action(async (opts) => {
5653
+ const { apiKeyCreateCommand } = await import("./create-2BZQLXQA.js");
4486
5654
  await apiKeyCreateCommand(opts);
4487
5655
  });
4488
5656
  apiKey.command("revoke <id>").description("Revoke an API key by ID").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
4489
- const { apiKeyRevokeCommand } = await import("./revoke-XDNOA2GJ.js");
5657
+ const { apiKeyRevokeCommand } = await import("./revoke-SXVNALYQ.js");
4490
5658
  await apiKeyRevokeCommand(id, opts);
4491
5659
  });
4492
5660
  }
@@ -4495,16 +5663,16 @@ function registerApiKeyCommands(program2) {
4495
5663
  function registerSessionCommands(program2) {
4496
5664
  const session = program2.command("session").description("Manage active sessions");
4497
5665
  session.command("list").description("List active sessions").option("--expired", "Show expired sessions instead").option("--json", "JSON output").action(async (opts) => {
4498
- const { listSessionsCommand } = await import("./list-RAR56EMQ.js");
5666
+ const { listSessionsCommand } = await import("./list-63EKE6DT.js");
4499
5667
  await listSessionsCommand(opts);
4500
5668
  });
4501
- session.command("revoke <sessionId>").description("Revoke a specific session").option("--json", "JSON output").action(async (sessionId, opts) => {
4502
- const { revokeSessionCommand } = await import("./revoke-ZTAMW2Q2.js");
5669
+ session.command("revoke <sessionId>").description("Revoke a specific session").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (sessionId, opts) => {
5670
+ const { revokeSessionCommand } = await import("./revoke-QHLNPGI5.js");
4503
5671
  await revokeSessionCommand(sessionId, opts);
4504
5672
  });
4505
- session.command("revoke-all").description("Sign out from all devices").action(async () => {
4506
- const { revokeAllSessionsCommand } = await import("./revoke-all-365NRBOA.js");
4507
- await revokeAllSessionsCommand();
5673
+ session.command("revoke-all").description("Sign out from all devices").option("--yes", "Skip confirmation prompt").action(async (opts) => {
5674
+ const { revokeAllSessionsCommand } = await import("./revoke-all-CYW6A5UE.js");
5675
+ await revokeAllSessionsCommand(opts);
4508
5676
  });
4509
5677
  }
4510
5678
 
@@ -4522,16 +5690,14 @@ async function journalListCommand(opts) {
4522
5690
  const client = new HisaaboClient(cfg);
4523
5691
  try {
4524
5692
  const result = await client.journal.list({
4525
- page: opts.page ?? 1,
4526
- limit: opts.limit ?? 25,
4527
- fromDate: opts.from,
4528
- toDate: opts.to
5693
+ fromDate: apiFrom(opts.from),
5694
+ toDate: apiTo(opts.to)
4529
5695
  });
4530
5696
  if (opts.json) {
4531
5697
  outputJSON(result);
4532
5698
  return;
4533
5699
  }
4534
- const entries = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
5700
+ const entries = result;
4535
5701
  console.log(`
4536
5702
  Journal Entries
4537
5703
  `);
@@ -4542,10 +5708,10 @@ async function journalListCommand(opts) {
4542
5708
  return;
4543
5709
  }
4544
5710
  for (const entry of entries) {
4545
- const date = formatDate(String(entry["date"] ?? entry["journalDate"] ?? ""));
4546
- const number = String(entry["number"] ?? entry["voucherNumber"] ?? "-");
4547
- const narration = String(entry["narration"] ?? entry["description"] ?? "").slice(0, 40);
4548
- const status = String(entry["status"] ?? "").padEnd(8);
5711
+ const date = formatDate(entry.entryDate);
5712
+ const number = entry.entryNumber;
5713
+ const narration = (entry.narration ?? "").slice(0, 40);
5714
+ const status = (entry.isVoided ? "voided" : "posted").padEnd(8);
4549
5715
  console.log(` ${date.padEnd(13)} ${number.padEnd(14)} ${status} ${narration}`);
4550
5716
  }
4551
5717
  console.log();
@@ -4562,25 +5728,20 @@ async function journalGetCommand(id, opts) {
4562
5728
  outputJSON(result);
4563
5729
  return;
4564
5730
  }
4565
- const r = result;
5731
+ if (!result) fatalError(`Journal entry not found: ${id}`, EXIT.NOT_FOUND);
4566
5732
  console.log(`
4567
- Journal Entry \u2014 ${String(r["number"] ?? r["voucherNumber"] ?? id)}
5733
+ Journal Entry \u2014 ${result.entryNumber}
4568
5734
  `);
4569
5735
  console.log(` ${"\u2550".repeat(60)}
4570
5736
  `);
4571
- console.log(` Date: ${formatDate(String(r["date"] ?? r["journalDate"] ?? ""))}`);
4572
- console.log(` Narration: ${String(r["narration"] ?? r["description"] ?? "-")}`);
4573
- console.log(` Status: ${String(r["status"] ?? "-")}`);
5737
+ console.log(` Date: ${formatDate(result.entryDate)}`);
5738
+ console.log(` Narration: ${result.narration ?? "-"}`);
5739
+ console.log(` Status: ${result.isVoided ? "voided" : "posted"}`);
4574
5740
  console.log();
4575
- const lines = r["lines"] ?? r["entries"] ?? r["lineItems"];
4576
- if (lines && Array.isArray(lines)) {
4577
- console.log(" Lines:\n");
4578
- for (const line of lines) {
4579
- const account = String(line["accountName"] ?? line["account"] ?? "-").padEnd(28);
4580
- const debit = String(line["debit"] ?? "0");
4581
- const credit = String(line["credit"] ?? "0");
4582
- console.log(` ${account} Dr: ${debit.padStart(12)} Cr: ${credit.padStart(12)}`);
4583
- }
5741
+ console.log(" Lines:\n");
5742
+ for (const line of result.lines) {
5743
+ const account = line.accountName.padEnd(28);
5744
+ console.log(` ${account} Dr: ${line.debit.padStart(12)} Cr: ${line.credit.padStart(12)}`);
4584
5745
  }
4585
5746
  console.log();
4586
5747
  } catch (e) {
@@ -4590,6 +5751,7 @@ async function journalGetCommand(id, opts) {
4590
5751
  async function journalVoidCommand(id, opts) {
4591
5752
  const cfg = requireAuth();
4592
5753
  const client = new HisaaboClient(cfg);
5754
+ await confirmOrExit(`Void journal entry ${id}?`, opts);
4593
5755
  try {
4594
5756
  const result = await client.journal.void(id);
4595
5757
  if (opts.json) {
@@ -4611,7 +5773,7 @@ async function journalTemplatesCommand(opts) {
4611
5773
  outputJSON(result);
4612
5774
  return;
4613
5775
  }
4614
- const templates = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
5776
+ const templates = result;
4615
5777
  console.log(`
4616
5778
  Journal Templates
4617
5779
  `);
@@ -4622,8 +5784,8 @@ async function journalTemplatesCommand(opts) {
4622
5784
  return;
4623
5785
  }
4624
5786
  for (const t of templates) {
4625
- const id = String(t["id"] ?? "-").slice(0, 8);
4626
- const name = String(t["name"] ?? "-").padEnd(30);
5787
+ const id = t.id.slice(0, 8);
5788
+ const name = t.name.padEnd(30);
4627
5789
  console.log(` ${id} ${name}`);
4628
5790
  }
4629
5791
  console.log();
@@ -4635,14 +5797,14 @@ async function journalTemplatesCommand(opts) {
4635
5797
  // src/bin/registrars/journal.ts
4636
5798
  function registerJournalCommands(program2) {
4637
5799
  const journal = program2.command("journal").description("Journal entries and templates");
4638
- journal.command("list").description("List journal entries").option("--json", "JSON output").option("--page <n>", "Page number", parseInt).option("--limit <n>", "Results per page", parseInt).option("--from <date>", "From date").option("--to <date>", "To date").action(async (opts) => {
4639
- await journalListCommand(opts);
5800
+ journal.command("list").description("List journal entries").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").action(async (opts) => {
5801
+ await journalListCommand({ json: opts.json, from: opts.from, to: opts.to });
4640
5802
  });
4641
5803
  journal.command("get <id>").description("Get journal entry details").option("--json", "JSON output").action(async (id, opts) => {
4642
5804
  await journalGetCommand(id, { json: opts.json });
4643
5805
  });
4644
- journal.command("void <id>").description("Void a journal entry").option("--json", "JSON output").action(async (id, opts) => {
4645
- await journalVoidCommand(id, { json: opts.json });
5806
+ journal.command("void <id>").description("Void a journal entry").option("--yes", "Skip confirmation prompt").option("--json", "JSON output").action(async (id, opts) => {
5807
+ await journalVoidCommand(id, { json: opts.json, yes: opts.yes });
4646
5808
  });
4647
5809
  journal.command("templates").description("List journal entry templates").option("--json", "JSON output").action(async (opts) => {
4648
5810
  await journalTemplatesCommand({ json: opts.json });
@@ -4650,6 +5812,9 @@ function registerJournalCommands(program2) {
4650
5812
  }
4651
5813
 
4652
5814
  // src/commands/itc/index.ts
5815
+ function isBlockReason(v) {
5816
+ return itcBlockReasons.includes(v);
5817
+ }
4653
5818
  function handleError2(e) {
4654
5819
  if (e instanceof HisaaboApiError) {
4655
5820
  const err = e.hisaaboError;
@@ -4662,23 +5827,21 @@ async function itcDashboardCommand(opts) {
4662
5827
  const cfg = requireAuth();
4663
5828
  const client = new HisaaboClient(cfg);
4664
5829
  try {
4665
- const result = await client.itc.dashboard({ fromDate: opts.from, toDate: opts.to });
5830
+ const result = await client.itc.dashboard({ returnPeriod: opts.period });
4666
5831
  if (opts.json) {
4667
5832
  outputJSON(result);
4668
5833
  return;
4669
5834
  }
4670
- const r = result;
4671
- console.log("\n ITC Dashboard\n");
5835
+ console.log(`
5836
+ ITC Dashboard ${result.returnPeriod}
5837
+ `);
4672
5838
  console.log(` ${"\u2550".repeat(50)}
4673
5839
  `);
4674
- const eligible = String(r["totalEligible"] ?? r["eligible"] ?? "0");
4675
- const blocked = String(r["totalBlocked"] ?? r["blocked"] ?? "0");
4676
- const utilized = String(r["totalUtilized"] ?? r["utilized"] ?? "0");
4677
- const available = String(r["availableBalance"] ?? r["available"] ?? "0");
4678
- console.log(` Eligible ITC: ${formatAmount(eligible).padStart(14)}`);
4679
- console.log(` Blocked ITC: ${formatAmount(blocked).padStart(14)}`);
4680
- console.log(` Utilized ITC: ${formatAmount(utilized).padStart(14)}`);
4681
- console.log(` Available Balance:${formatAmount(available).padStart(14)}`);
5840
+ const total = (status) => result.summary[status]?.total ?? "0";
5841
+ console.log(` Available ITC: ${formatAmount(total("available")).padStart(14)}`);
5842
+ console.log(` Blocked ITC: ${formatAmount(total("blocked")).padStart(14)}`);
5843
+ console.log(` Utilized ITC: ${formatAmount(total("utilized")).padStart(14)}`);
5844
+ console.log(` Reversed ITC: ${formatAmount(total("reversed")).padStart(14)}`);
4682
5845
  console.log();
4683
5846
  } catch (e) {
4684
5847
  handleError2(e);
@@ -4688,23 +5851,23 @@ async function itcLedgerCommand(opts) {
4688
5851
  const cfg = requireAuth();
4689
5852
  const client = new HisaaboClient(cfg);
4690
5853
  try {
4691
- const result = await client.itc.ledger({ fromDate: opts.from, toDate: opts.to });
5854
+ const result = await client.itc.ledger({ returnPeriod: opts.period });
4692
5855
  if (opts.json) {
4693
5856
  outputJSON(result);
4694
5857
  return;
4695
5858
  }
4696
- const entries = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : Array.isArray(result?.entries) ? result.entries : [];
5859
+ const entries = result.entries;
4697
5860
  console.log("\n ITC Ledger\n");
4698
5861
  console.log(` ${"\u2550".repeat(70)}
4699
5862
  `);
4700
5863
  for (const entry of entries) {
4701
- const date = String(entry["date"] ?? "-").slice(0, 10);
4702
- const supplier = String(entry["supplierName"] ?? entry["supplier"] ?? "-").padEnd(22);
4703
- const gstin = String(entry["gstin"] ?? "-").padEnd(16);
4704
- const igst = formatAmount(String(entry["igst"] ?? "0")).padStart(12);
4705
- const cgst = formatAmount(String(entry["cgst"] ?? "0")).padStart(12);
4706
- const sgst = formatAmount(String(entry["sgst"] ?? "0")).padStart(12);
4707
- console.log(` ${date.padEnd(12)} ${supplier} ${gstin} IGST:${igst} CGST:${cgst} SGST:${sgst}`);
5864
+ const date = formatDate(entry.invoiceDate);
5865
+ const supplier = (entry.partyName ?? "-").padEnd(22);
5866
+ const status = entry.status.padEnd(10);
5867
+ const igst = formatAmount(entry.igst).padStart(12);
5868
+ const cgst = formatAmount(entry.cgst).padStart(12);
5869
+ const sgst = formatAmount(entry.sgst).padStart(12);
5870
+ console.log(` ${date.padEnd(12)} ${supplier} ${status} IGST:${igst} CGST:${cgst} SGST:${sgst}`);
4708
5871
  }
4709
5872
  console.log();
4710
5873
  } catch (e) {
@@ -4720,7 +5883,7 @@ async function itcAgingCommand(opts) {
4720
5883
  outputJSON(result);
4721
5884
  return;
4722
5885
  }
4723
- const alerts = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : Array.isArray(result?.alerts) ? result.alerts : [];
5886
+ const alerts = result;
4724
5887
  console.log("\n ITC Aging Alerts\n");
4725
5888
  console.log(` ${"\u2550".repeat(60)}
4726
5889
  `);
@@ -4729,9 +5892,9 @@ async function itcAgingCommand(opts) {
4729
5892
  return;
4730
5893
  }
4731
5894
  for (const alert of alerts) {
4732
- const supplier = String(alert["supplierName"] ?? alert["supplier"] ?? "-").padEnd(25);
4733
- const amount = formatAmount(String(alert["amount"] ?? "0")).padStart(14);
4734
- const days = String(alert["daysOld"] ?? alert["age"] ?? "-").padStart(6);
5895
+ const supplier = alert.partyName.padEnd(25);
5896
+ const amount = formatAmount(alert.itcAmount).padStart(14);
5897
+ const days = String(alert.daysOutstanding).padStart(6);
4735
5898
  console.log(` ${supplier} ${amount} ${days} days`);
4736
5899
  }
4737
5900
  console.log();
@@ -4742,8 +5905,12 @@ async function itcAgingCommand(opts) {
4742
5905
  async function itcBlockCommand(invoiceId, opts) {
4743
5906
  const cfg = requireAuth();
4744
5907
  const client = new HisaaboClient(cfg);
5908
+ const blockReason = opts.reason ?? "other";
5909
+ if (!isBlockReason(blockReason)) {
5910
+ fatalError(`--reason must be one of: ${itcBlockReasons.join(", ")}`, EXIT.USAGE);
5911
+ }
4745
5912
  try {
4746
- const result = await client.itc.markBlocked({ invoiceId });
5913
+ const result = await client.itc.markBlocked({ invoiceId, blockReason, notes: opts.notes });
4747
5914
  if (opts.json) {
4748
5915
  outputJSON(result);
4749
5916
  return;
@@ -4773,17 +5940,17 @@ async function itcUnblockCommand(invoiceId, opts) {
4773
5940
  // src/bin/registrars/itc.ts
4774
5941
  function registerItcCommands(program2) {
4775
5942
  const itc = program2.command("itc").description("Input Tax Credit tracking");
4776
- itc.command("dashboard").description("ITC summary dashboard").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").action(async (opts) => {
4777
- await itcDashboardCommand(opts);
5943
+ itc.command("dashboard").description("ITC summary dashboard").option("--json", "JSON output").option("--period <YYYY-MM>", "Return period (default: current month)").action(async (opts) => {
5944
+ await itcDashboardCommand({ json: opts.json, period: opts.period });
4778
5945
  });
4779
- itc.command("ledger").description("ITC ledger \u2014 all eligible purchase credits").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").action(async (opts) => {
4780
- await itcLedgerCommand(opts);
5946
+ itc.command("ledger").description("ITC ledger \u2014 all eligible purchase credits").option("--json", "JSON output").option("--period <YYYY-MM>", "Return period (default: all periods)").action(async (opts) => {
5947
+ await itcLedgerCommand({ json: opts.json, period: opts.period });
4781
5948
  });
4782
5949
  itc.command("aging").description("ITC aging alerts \u2014 credits at risk of reversal").option("--json", "JSON output").action(async (opts) => {
4783
5950
  await itcAgingCommand({ json: opts.json });
4784
5951
  });
4785
- itc.command("block <invoiceId>").description("Mark ITC for an invoice as blocked").option("--json", "JSON output").action(async (invoiceId, opts) => {
4786
- await itcBlockCommand(invoiceId, { json: opts.json });
5952
+ itc.command("block <invoiceId>").description("Mark ITC for an invoice as blocked").option("--json", "JSON output").option("--reason <reason>", "Block reason (motor_vehicle, food_beverage, personal, membership, travel_benefits, works_contract, construction, telecom, other)").option("--notes <text>", "Free-text notes").action(async (invoiceId, opts) => {
5953
+ await itcBlockCommand(invoiceId, { json: opts.json, reason: opts.reason, notes: opts.notes });
4787
5954
  });
4788
5955
  itc.command("unblock <invoiceId>").description("Mark ITC for an invoice as eligible").option("--json", "JSON output").action(async (invoiceId, opts) => {
4789
5956
  await itcUnblockCommand(invoiceId, { json: opts.json });
@@ -4799,16 +5966,24 @@ function handleError3(e) {
4799
5966
  }
4800
5967
  fatalError(String(e instanceof Error ? e.message : e));
4801
5968
  }
5969
+ async function bankAccountIdForImport(client, importId) {
5970
+ for (let page = 1; ; page++) {
5971
+ const { data, total, limit } = await client.bankRecon.importList({ page, limit: 100 });
5972
+ const hit = data.find((i) => i.id === importId);
5973
+ if (hit) return hit.bankAccountId;
5974
+ if (page * limit >= total) return null;
5975
+ }
5976
+ }
4802
5977
  async function bankReconImportsCommand(opts) {
4803
5978
  const cfg = requireAuth();
4804
5979
  const client = new HisaaboClient(cfg);
4805
5980
  try {
4806
- const result = await client.bankRecon.importList();
5981
+ const result = await client.bankRecon.importList({});
4807
5982
  if (opts.json) {
4808
5983
  outputJSON(result);
4809
5984
  return;
4810
5985
  }
4811
- const imports = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
5986
+ const imports = result.data;
4812
5987
  console.log("\n Bank Reconciliation Imports\n");
4813
5988
  console.log(` ${"\u2550".repeat(65)}
4814
5989
  `);
@@ -4817,12 +5992,12 @@ async function bankReconImportsCommand(opts) {
4817
5992
  return;
4818
5993
  }
4819
5994
  for (const imp of imports) {
4820
- const id = String(imp["id"] ?? "-").slice(0, 8);
4821
- const date = formatDate(String(imp["createdAt"] ?? imp["importDate"] ?? ""));
4822
- const account = String(imp["accountName"] ?? imp["bankAccount"] ?? "-").padEnd(20);
4823
- const lines = String(imp["totalLines"] ?? imp["lineCount"] ?? "-").padStart(6);
4824
- const matched = String(imp["matchedLines"] ?? imp["matched"] ?? "-").padStart(8);
4825
- const status = String(imp["status"] ?? "-").padEnd(10);
5995
+ const id = imp.id.slice(0, 8);
5996
+ const date = formatDate(imp.createdAt);
5997
+ const account = imp.fileName.padEnd(20);
5998
+ const lines = String(imp.totalLines).padStart(6);
5999
+ const matched = String(imp.matchedLines).padStart(8);
6000
+ const status = imp.status.padEnd(10);
4826
6001
  console.log(` ${id} ${date.padEnd(13)} ${account} Lines:${lines} Matched:${matched} ${status}`);
4827
6002
  }
4828
6003
  console.log();
@@ -4834,29 +6009,28 @@ async function bankReconSummaryCommand(importId, opts) {
4834
6009
  const cfg = requireAuth();
4835
6010
  const client = new HisaaboClient(cfg);
4836
6011
  try {
4837
- const result = await client.bankRecon.summary(importId);
6012
+ const bankAccountId = await bankAccountIdForImport(client, importId);
6013
+ if (!bankAccountId) fatalError(`Import not found: ${importId}`, EXIT.NOT_FOUND);
6014
+ const result = await client.bankRecon.summary({ bankAccountId, importId });
4838
6015
  if (opts.json) {
4839
6016
  outputJSON(result);
4840
6017
  return;
4841
6018
  }
4842
- const r = result;
4843
6019
  console.log(`
4844
6020
  Bank Recon Summary \u2014 ${importId}
4845
6021
  `);
4846
6022
  console.log(` ${"\u2550".repeat(55)}
4847
6023
  `);
4848
- const total = String(r["totalLines"] ?? r["total"] ?? "0");
4849
- const matched = String(r["matchedLines"] ?? r["matched"] ?? "0");
4850
- const unmatched = String(r["unmatchedLines"] ?? r["unmatched"] ?? "0");
4851
- const ignored = String(r["ignoredLines"] ?? r["ignored"] ?? "0");
4852
- const openingBalance = String(r["openingBalance"] ?? "0");
4853
- const closingBalance = String(r["closingBalance"] ?? "0");
4854
- console.log(` Total Lines: ${total.padStart(8)}`);
4855
- console.log(` Matched: ${matched.padStart(8)}`);
4856
- console.log(` Unmatched: ${unmatched.padStart(8)}`);
4857
- console.log(` Ignored: ${ignored.padStart(8)}`);
4858
- console.log(` Opening Balance: ${formatAmount(openingBalance).padStart(14)}`);
4859
- console.log(` Closing Balance: ${formatAmount(closingBalance).padStart(14)}`);
6024
+ const imp = result.import;
6025
+ console.log(` Account: ${result.accountName}`);
6026
+ console.log(` Total Lines: ${String(imp?.totalLines ?? 0).padStart(8)}`);
6027
+ console.log(` Matched: ${String(imp?.matchedLines ?? 0).padStart(8)}`);
6028
+ console.log(` Unmatched: ${String(imp?.unmatchedLines ?? 0).padStart(8)}`);
6029
+ console.log(` Book Balance: ${formatAmount(result.bookBalance).padStart(14)}`);
6030
+ console.log(` Statement Balance: ${formatAmount(result.statementBalance ?? "0").padStart(14)}`);
6031
+ console.log(` Difference: ${formatAmount(result.difference ?? "0").padStart(14)}`);
6032
+ console.log(` Unmatched Debits: ${formatAmount(result.unmatchedDebits).padStart(14)}`);
6033
+ console.log(` Unmatched Credits: ${formatAmount(result.unmatchedCredits).padStart(14)}`);
4860
6034
  console.log();
4861
6035
  } catch (e) {
4862
6036
  handleError3(e);
@@ -4871,7 +6045,7 @@ async function bankReconRulesCommand(opts) {
4871
6045
  outputJSON(result);
4872
6046
  return;
4873
6047
  }
4874
- const rules = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
6048
+ const rules = result;
4875
6049
  console.log("\n Bank Recon Rules\n");
4876
6050
  console.log(` ${"\u2550".repeat(60)}
4877
6051
  `);
@@ -4880,10 +6054,10 @@ async function bankReconRulesCommand(opts) {
4880
6054
  return;
4881
6055
  }
4882
6056
  for (const rule of rules) {
4883
- const id = String(rule["id"] ?? "-").slice(0, 8);
4884
- const name = String(rule["name"] ?? "-").padEnd(25);
4885
- const condition = String(rule["condition"] ?? rule["matchPattern"] ?? "-").padEnd(20);
4886
- const action = String(rule["action"] ?? "-").padEnd(12);
6057
+ const id = rule.id.slice(0, 8);
6058
+ const name = `${rule.matchField} ${rule.matchType}`.padEnd(25);
6059
+ const condition = rule.matchValue.padEnd(20);
6060
+ const action = rule.action.padEnd(12);
4887
6061
  console.log(` ${id} ${name} ${condition} ${action}`);
4888
6062
  }
4889
6063
  console.log();
@@ -4907,6 +6081,10 @@ function registerBankReconCommands(program2) {
4907
6081
  }
4908
6082
 
4909
6083
  // src/commands/einvoice/index.ts
6084
+ var CANCEL_REASONS = ["1", "2", "3", "4"];
6085
+ function isCancelReason(v) {
6086
+ return CANCEL_REASONS.includes(v);
6087
+ }
4910
6088
  function handleError4(e) {
4911
6089
  if (e instanceof HisaaboApiError) {
4912
6090
  const err = e.hisaaboError;
@@ -4919,19 +6097,18 @@ async function eInvoiceDashboardCommand(opts) {
4919
6097
  const cfg = requireAuth();
4920
6098
  const client = new HisaaboClient(cfg);
4921
6099
  try {
4922
- const result = await client.eInvoice.dashboard({ fromDate: opts.from, toDate: opts.to });
6100
+ const result = await client.eInvoice.dashboard({ fromDate: apiFrom(opts.from), toDate: apiTo(opts.to) });
4923
6101
  if (opts.json) {
4924
6102
  outputJSON(result);
4925
6103
  return;
4926
6104
  }
4927
- const r = result;
4928
6105
  console.log("\n E-Invoice Dashboard\n");
4929
6106
  console.log(` ${"\u2550".repeat(50)}
4930
6107
  `);
4931
- const generated = String(r["totalGenerated"] ?? r["generated"] ?? "0");
4932
- const cancelled = String(r["totalCancelled"] ?? r["cancelled"] ?? "0");
4933
- const failed = String(r["totalFailed"] ?? r["failed"] ?? "0");
4934
- const pending = String(r["pending"] ?? "0");
6108
+ const generated = String(result.counts.generated);
6109
+ const cancelled = String(result.counts.cancelled);
6110
+ const failed = String(result.counts.failed);
6111
+ const pending = String(result.counts.pending);
4935
6112
  console.log(` Generated: ${generated.padStart(8)}`);
4936
6113
  console.log(` Cancelled: ${cancelled.padStart(8)}`);
4937
6114
  console.log(` Failed: ${failed.padStart(8)}`);
@@ -4950,9 +6127,8 @@ async function eInvoiceGenerateCommand(invoiceId, opts) {
4950
6127
  outputJSON(result);
4951
6128
  return;
4952
6129
  }
4953
- const r = result;
4954
- const irn = String(r["irn"] ?? r["invoiceReferenceNumber"] ?? "-");
4955
- const ackNo = String(r["ackNo"] ?? r["acknowledgementNumber"] ?? "-");
6130
+ const irn = result.irn ?? "-";
6131
+ const ackNo = result.irnAckNumber ?? "-";
4956
6132
  console.log(` E-Invoice generated.
4957
6133
  `);
4958
6134
  console.log(` IRN: ${irn}`);
@@ -4965,8 +6141,11 @@ async function eInvoiceGenerateCommand(invoiceId, opts) {
4965
6141
  async function eInvoiceCancelCommand(invoiceId, opts) {
4966
6142
  const cfg = requireAuth();
4967
6143
  const client = new HisaaboClient(cfg);
6144
+ await confirmOrExit(`Cancel the e-invoice for ${invoiceId}? This cannot be undone.`, opts);
4968
6145
  try {
4969
- const result = await client.eInvoice.cancel({ invoiceId, cancelReason: opts.reason ?? "1" });
6146
+ const cancelReason = opts.reason ?? "1";
6147
+ if (!isCancelReason(cancelReason)) fatalError("--reason must be one of: 1, 2, 3, 4", EXIT.USAGE);
6148
+ const result = await client.eInvoice.cancel({ invoiceId, cancelReason });
4970
6149
  if (opts.json) {
4971
6150
  outputJSON(result);
4972
6151
  return;
@@ -4986,8 +6165,7 @@ async function eInvoiceRetryCommand(invoiceId, opts) {
4986
6165
  outputJSON(result);
4987
6166
  return;
4988
6167
  }
4989
- const r = result;
4990
- const status = String(r["status"] ?? "queued");
6168
+ const status = result.eInvoiceStatus ?? "queued";
4991
6169
  console.log(` Retry queued for invoice ${invoiceId}. Status: ${status}
4992
6170
  `);
4993
6171
  } catch (e) {
@@ -5004,8 +6182,8 @@ function registerEInvoiceCommands(program2) {
5004
6182
  einvoice.command("generate <invoiceId>").description("Generate an e-invoice (get IRN from IRP)").option("--json", "JSON output").action(async (invoiceId, opts) => {
5005
6183
  await eInvoiceGenerateCommand(invoiceId, { json: opts.json });
5006
6184
  });
5007
- einvoice.command("cancel <invoiceId>").description("Cancel an e-invoice").option("--json", "JSON output").option("--reason <code>", "Cancel reason code (1-4)").action(async (invoiceId, opts) => {
5008
- await eInvoiceCancelCommand(invoiceId, { json: opts.json, reason: opts.reason });
6185
+ einvoice.command("cancel <invoiceId>").description("Cancel an e-invoice").option("--json", "JSON output").option("--reason <code>", "Cancel reason code (1-4)").option("--yes", "Skip confirmation prompt").action(async (invoiceId, opts) => {
6186
+ await eInvoiceCancelCommand(invoiceId, { json: opts.json, reason: opts.reason, yes: opts.yes });
5009
6187
  });
5010
6188
  einvoice.command("retry <invoiceId>").description("Retry a failed e-invoice generation").option("--json", "JSON output").action(async (invoiceId, opts) => {
5011
6189
  await eInvoiceRetryCommand(invoiceId, { json: opts.json });
@@ -5025,19 +6203,18 @@ async function ewbDashboardCommand(opts) {
5025
6203
  const cfg = requireAuth();
5026
6204
  const client = new HisaaboClient(cfg);
5027
6205
  try {
5028
- const result = await client.ewayBill.dashboard({ fromDate: opts.from, toDate: opts.to });
6206
+ const result = await client.ewayBill.dashboard({});
5029
6207
  if (opts.json) {
5030
6208
  outputJSON(result);
5031
6209
  return;
5032
6210
  }
5033
- const r = result;
5034
6211
  console.log("\n E-Way Bill Dashboard\n");
5035
6212
  console.log(` ${"\u2550".repeat(50)}
5036
6213
  `);
5037
- const generated = String(r["totalGenerated"] ?? r["generated"] ?? "0");
5038
- const cancelled = String(r["totalCancelled"] ?? r["cancelled"] ?? "0");
5039
- const expired = String(r["totalExpired"] ?? r["expired"] ?? "0");
5040
- const active = String(r["active"] ?? "0");
6214
+ const generated = String(result.summary["generated"] ?? 0);
6215
+ const cancelled = String(result.summary["cancelled"] ?? 0);
6216
+ const expired = String(result.summary["expired"] ?? 0);
6217
+ const active = String(result.summary["active"] ?? 0);
5041
6218
  console.log(` Generated: ${generated.padStart(8)}`);
5042
6219
  console.log(` Active: ${active.padStart(8)}`);
5043
6220
  console.log(` Cancelled: ${cancelled.padStart(8)}`);
@@ -5051,14 +6228,13 @@ async function ewbGenerateCommand(invoiceId, opts) {
5051
6228
  const cfg = requireAuth();
5052
6229
  const client = new HisaaboClient(cfg);
5053
6230
  try {
5054
- const result = await client.ewayBill.generate({ invoiceId });
6231
+ const result = await client.ewayBill.generate({ invoiceId, vehicleNumber: opts.vehicle, distance: opts.distance });
5055
6232
  if (opts.json) {
5056
6233
  outputJSON(result);
5057
6234
  return;
5058
6235
  }
5059
- const r = result;
5060
- const ewbNo = String(r["eWayBillNo"] ?? r["ewbNumber"] ?? r["ewbNo"] ?? "-");
5061
- const validUpto = String(r["validUpto"] ?? r["validTill"] ?? "-");
6236
+ const ewbNo = result.ewbNumber ?? "-";
6237
+ const validUpto = formatDate(result.validUpto);
5062
6238
  console.log(` E-Way Bill generated.
5063
6239
  `);
5064
6240
  console.log(` EWB No: ${ewbNo}`);
@@ -5072,14 +6248,14 @@ async function ewbExpiringCommand(opts) {
5072
6248
  const cfg = requireAuth();
5073
6249
  const client = new HisaaboClient(cfg);
5074
6250
  try {
5075
- const result = await client.ewayBill.expiringList({ withinDays: opts.days ?? 3 });
6251
+ const result = await client.ewayBill.expiringList();
5076
6252
  if (opts.json) {
5077
6253
  outputJSON(result);
5078
6254
  return;
5079
6255
  }
5080
- const bills = Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : [];
6256
+ const bills = result;
5081
6257
  console.log(`
5082
- Expiring E-Way Bills (within ${opts.days ?? 3} days)
6258
+ Expiring E-Way Bills (within 24 hours)
5083
6259
  `);
5084
6260
  console.log(` ${"\u2550".repeat(65)}
5085
6261
  `);
@@ -5088,10 +6264,10 @@ async function ewbExpiringCommand(opts) {
5088
6264
  return;
5089
6265
  }
5090
6266
  for (const bill of bills) {
5091
- const ewbNo = String(bill["eWayBillNo"] ?? bill["ewbNumber"] ?? "-").padEnd(14);
5092
- const invoiceNo = String(bill["invoiceNumber"] ?? bill["invoice"] ?? "-").padEnd(14);
5093
- const party = String(bill["partyName"] ?? bill["party"] ?? "-").padEnd(22);
5094
- const validUpto = formatDate(String(bill["validUpto"] ?? bill["validTill"] ?? ""));
6267
+ const ewbNo = (bill.ewbNumber ?? "-").padEnd(14);
6268
+ const invoiceNo = (bill.invoiceNumber ?? "-").padEnd(14);
6269
+ const party = (bill.partyName ?? "-").padEnd(22);
6270
+ const validUpto = formatDate(bill.validUpto);
5095
6271
  console.log(` ${ewbNo} ${invoiceNo} ${party} Expires: ${validUpto}`);
5096
6272
  }
5097
6273
  console.log();
@@ -5103,20 +6279,20 @@ async function ewbExpiringCommand(opts) {
5103
6279
  // src/bin/registrars/ewb.ts
5104
6280
  function registerEwbCommands(program2) {
5105
6281
  const ewb = program2.command("ewb").description("E-Way Bill management");
5106
- ewb.command("dashboard").description("E-way bill summary dashboard").option("--json", "JSON output").option("--from <date>", "From date").option("--to <date>", "To date").action(async (opts) => {
5107
- await ewbDashboardCommand(opts);
6282
+ ewb.command("dashboard").description("E-way bill summary dashboard").option("--json", "JSON output").action(async (opts) => {
6283
+ await ewbDashboardCommand({ json: opts.json });
5108
6284
  });
5109
- ewb.command("generate <invoiceId>").description("Generate an e-way bill for an invoice").option("--json", "JSON output").action(async (invoiceId, opts) => {
5110
- await ewbGenerateCommand(invoiceId, { json: opts.json });
6285
+ ewb.command("generate <invoiceId>").description("Generate an e-way bill for an invoice").option("--json", "JSON output").requiredOption("--vehicle <number>", "Vehicle registration number (e.g. MH12AB1234)").requiredOption("--distance <km>", "Approximate distance in km (1-4000)", (v) => parseInt(v, 10)).action(async (invoiceId, opts) => {
6286
+ await ewbGenerateCommand(invoiceId, { json: opts.json, vehicle: opts.vehicle, distance: opts.distance });
5111
6287
  });
5112
- ewb.command("expiring").description("List e-way bills expiring soon").option("--json", "JSON output").option("--days <n>", "Within N days (default: 3)", parseInt).action(async (opts) => {
5113
- await ewbExpiringCommand({ json: opts.json, days: opts.days });
6288
+ ewb.command("expiring").description("List e-way bills expiring within the next 24 hours").option("--json", "JSON output").action(async (opts) => {
6289
+ await ewbExpiringCommand({ json: opts.json });
5114
6290
  });
5115
6291
  }
5116
6292
 
5117
6293
  // src/bin/registrars/backup.ts
5118
6294
  function registerBackupCommands(program2) {
5119
- program2.command("export").description("Download a full tenant backup as a .tar.gz archive").requiredOption("--tenant <slug-or-id>", "Tenant slug or UUID to export").requiredOption("-o, --output <file>", "Output file path (e.g. backup.tar.gz)").addHelpText(
6295
+ program2.command("export").description("Download a full tenant backup as a .tar.gz archive").requiredOption("--tenant <slug-or-id>", "Tenant slug or UUID to export").requiredOption("-o, --output <file>", "Output file path (e.g. backup.tar.gz)").option("--force", "Overwrite the output file if it exists").addHelpText(
5120
6296
  "after",
5121
6297
  `
5122
6298
  Examples:
@@ -5129,8 +6305,8 @@ Exit codes:
5129
6305
  2 Rate limit reached (2 exports per day)
5130
6306
  5 Server or network error`
5131
6307
  ).action(async (opts) => {
5132
- const { exportCommand } = await import("./export-6PMJ2YVL.js");
5133
- await exportCommand({ tenant: opts.tenant, output: opts.output });
6308
+ const { exportCommand } = await import("./export-WS24LYNH.js");
6309
+ await exportCommand({ tenant: opts.tenant, output: opts.output, force: opts.force });
5134
6310
  });
5135
6311
  program2.command("restore").description("Upload a .tar.gz backup archive into an empty tenant").requiredOption("--tenant <slug-or-id>", "Target tenant slug or UUID (must be empty)").requiredOption("-i, --input <file>", "Input backup file path (e.g. backup.tar.gz)").option("-y, --yes", "Skip confirmation prompt").addHelpText(
5136
6312
  "after",
@@ -5151,27 +6327,38 @@ Exit codes:
5151
6327
  4 Input file missing, unreadable, or empty
5152
6328
  5 Server or network error`
5153
6329
  ).action(async (opts) => {
5154
- const { restoreCommand } = await import("./import-UUHMLCKX.js");
6330
+ const { restoreCommand } = await import("./import-6CEMNCTM.js");
5155
6331
  await restoreCommand({ tenant: opts.tenant, input: opts.input, yes: opts.yes });
5156
6332
  });
5157
6333
  }
5158
6334
 
5159
6335
  // src/bin/hisaabo.ts
6336
+ installTerminalSanitizer();
5160
6337
  var program = new Command();
5161
- var cliVersion = true ? "0.9.0" : "dev";
5162
- program.name("hisaabo").description("Hisaabo CLI \u2014 Invoicing and business management").version(cliVersion);
6338
+ var cliVersion = true ? "0.10.0" : "dev";
6339
+ program.name("hisaabo").description("Hisaabo CLI \u2014 Invoicing and business management").version(cliVersion).option("--tz <zone>", "IANA time zone for --from/--to day boundaries (default: HISAABO_TZ, else machine zone)");
6340
+ program.hook("preAction", (_thisCommand, actionCommand) => {
6341
+ try {
6342
+ setTimeZone(actionCommand.optsWithGlobals().tz);
6343
+ } catch (err) {
6344
+ if (err instanceof InvalidTimeZoneError) fatalError(err.message, EXIT.USAGE);
6345
+ throw err;
6346
+ }
6347
+ });
5163
6348
  registerAuthCommands(program);
5164
6349
  registerDashboardCommands(program);
5165
6350
  registerInvoiceCommands(program);
5166
6351
  registerPartyCommands(program);
5167
6352
  registerItemCommands(program);
5168
6353
  registerPaymentCommands(program);
6354
+ registerTdsSectionCommands(program);
5169
6355
  registerExpenseCommands(program);
5170
6356
  registerGstCommands(program);
5171
6357
  registerReportCommands(program);
5172
6358
  registerBankCommands(program);
5173
6359
  registerShipmentCommands(program);
5174
6360
  registerTargetCommands(program);
6361
+ registerNotificationCommands(program);
5175
6362
  registerStoreCommands(program);
5176
6363
  registerImportCommands(program);
5177
6364
  registerAutomatedInvoiceCommands(program);