@hisaabo/cli 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +332 -0
  2. package/dist/bin/audit-trail-2YGXGUXW.js +78 -0
  3. package/dist/bin/categories-P5VFWD5F.js +47 -0
  4. package/dist/bin/check-slug-4TMOTWUJ.js +65 -0
  5. package/dist/bin/chunk-2P35S2C3.js +46 -0
  6. package/dist/bin/chunk-EYNDY7RB.js +175 -0
  7. package/dist/bin/chunk-FFBG6RU4.js +156 -0
  8. package/dist/bin/chunk-FTOBDKMO.js +804 -0
  9. package/dist/bin/client-QNJ2H5CW.js +11 -0
  10. package/dist/bin/collection-efficiency-WMKEGS6U.js +165 -0
  11. package/dist/bin/config-UKVQYPPR.js +18 -0
  12. package/dist/bin/create-Y22FAVOW.js +83 -0
  13. package/dist/bin/default-account-SA56M66A.js +58 -0
  14. package/dist/bin/expenses-VZAOLYUW.js +89 -0
  15. package/dist/bin/export-QZ6WT6PJ.js +59 -0
  16. package/dist/bin/factory-2DCU3B5T.js +483 -0
  17. package/dist/bin/get-6UYP6UVD.js +71 -0
  18. package/dist/bin/get-EXL44I2X.js +66 -0
  19. package/dist/bin/hisaabo.js +2029 -1450
  20. package/dist/bin/invite-O26SAL72.js +53 -0
  21. package/dist/bin/invoice-breakdown-XEATXVMR.js +97 -0
  22. package/dist/bin/items-3U5USBVG.js +62 -0
  23. package/dist/bin/items-toggle-YEKMI2CM.js +46 -0
  24. package/dist/bin/list-FX2C3NCL.js +46 -0
  25. package/dist/bin/list-VBAHY72W.js +79 -0
  26. package/dist/bin/members-5FPRUAB6.js +55 -0
  27. package/dist/bin/monthly-comparison-JEJ3TTY2.js +176 -0
  28. package/dist/bin/order-cancel-XI2LKYXV.js +55 -0
  29. package/dist/bin/order-confirm-HUFCU6MO.js +53 -0
  30. package/dist/bin/order-get-NSDMPUZR.js +88 -0
  31. package/dist/bin/order-update-C7QYSD5R.js +60 -0
  32. package/dist/bin/output-QFLEKG5W.js +35 -0
  33. package/dist/bin/payment-modes-WI3AWSES.js +126 -0
  34. package/dist/bin/profit-loss-5RIEOBKP.js +135 -0
  35. package/dist/bin/receivables-aging-L6DIQCNE.js +161 -0
  36. package/dist/bin/remove-M2B4TZ37.js +52 -0
  37. package/dist/bin/revoke-H3V2GNCD.js +52 -0
  38. package/dist/bin/sales-trend-TICB3KGF.js +71 -0
  39. package/dist/bin/sequence-XUD6FAKY.js +66 -0
  40. package/dist/bin/store-UQ2DDQ5I.js +82 -0
  41. package/dist/bin/summary-BPNFC7I2.js +113 -0
  42. package/dist/bin/top-customers-WGGJWKCN.js +81 -0
  43. package/dist/bin/top-items-C7ZDDJMR.js +84 -0
  44. package/dist/bin/top-outstanding-MOGWJIQS.js +64 -0
  45. package/dist/bin/unpaid-invoices-ZUPNMQJP.js +65 -0
  46. package/dist/bin/untracked-BCJEVDW4.js +67 -0
  47. package/dist/bin/update-HIU4PANX.js +54 -0
  48. package/dist/bin/update-IG565YIN.js +61 -0
  49. package/dist/bin/update-PVLAX7T3.js +57 -0
  50. package/dist/bin/update-role-Q4ZYJRYT.js +45 -0
  51. package/dist/bin/update-settings-XPC6L5WM.js +56 -0
  52. package/package.json +6 -1
  53. package/src/bin/hisaabo.ts +42 -933
  54. package/src/bin/registrars/api-key.ts +44 -0
  55. package/src/bin/registrars/auth.ts +153 -0
  56. package/src/bin/registrars/automated-invoice.ts +167 -0
  57. package/src/bin/registrars/bank.ts +90 -0
  58. package/src/bin/registrars/business.ts +120 -0
  59. package/src/bin/registrars/dashboard.ts +225 -0
  60. package/src/bin/registrars/document.ts +184 -0
  61. package/src/bin/registrars/expense.ts +87 -0
  62. package/src/bin/registrars/gst.ts +41 -0
  63. package/src/bin/registrars/import.ts +49 -0
  64. package/src/bin/registrars/invoice.ts +117 -0
  65. package/src/bin/registrars/item.ts +112 -0
  66. package/src/bin/registrars/party.ts +81 -0
  67. package/src/bin/registrars/payment.ts +128 -0
  68. package/src/bin/registrars/report.ts +142 -0
  69. package/src/bin/registrars/shipment.ts +74 -0
  70. package/src/bin/registrars/store.ts +128 -0
  71. package/src/bin/registrars/target.ts +46 -0
  72. package/src/bin/registrars/tenant.ts +55 -0
  73. package/src/client.ts +495 -4
  74. package/src/commands/api-key/create.ts +72 -0
  75. package/src/commands/api-key/list.ts +71 -0
  76. package/src/commands/api-key/revoke.ts +46 -0
  77. package/src/commands/automated-invoice/create.ts +85 -0
  78. package/src/commands/automated-invoice/delete.ts +42 -0
  79. package/src/commands/automated-invoice/get.ts +113 -0
  80. package/src/commands/automated-invoice/history.ts +65 -0
  81. package/src/commands/automated-invoice/index.ts +11 -0
  82. package/src/commands/automated-invoice/list.ts +91 -0
  83. package/src/commands/automated-invoice/pause.ts +29 -0
  84. package/src/commands/automated-invoice/resume.ts +29 -0
  85. package/src/commands/automated-invoice/run-now.ts +29 -0
  86. package/src/commands/automated-invoice/suggestions.ts +68 -0
  87. package/src/commands/automated-invoice/update.ts +54 -0
  88. package/src/commands/automated-invoice/usage.ts +68 -0
  89. package/src/commands/business/audit-trail.ts +79 -0
  90. package/src/commands/business/export.ts +52 -0
  91. package/src/commands/business/get.ts +55 -0
  92. package/src/commands/business/sequence.ts +65 -0
  93. package/src/commands/business/update.ts +64 -0
  94. package/src/commands/dashboard/collection-efficiency.ts +164 -0
  95. package/src/commands/dashboard/expenses.ts +76 -0
  96. package/src/commands/dashboard/invoice-breakdown.ts +89 -0
  97. package/src/commands/dashboard/monthly-comparison.ts +193 -0
  98. package/src/commands/dashboard/payment-modes.ts +121 -0
  99. package/src/commands/dashboard/profit-loss.ts +146 -0
  100. package/src/commands/dashboard/receivables-aging.ts +169 -0
  101. package/src/commands/dashboard/sales-trend.ts +68 -0
  102. package/src/commands/dashboard/summary.ts +105 -0
  103. package/src/commands/dashboard/top-customers.ts +70 -0
  104. package/src/commands/dashboard/top-items.ts +74 -0
  105. package/src/commands/dashboard/top-outstanding.ts +61 -0
  106. package/src/commands/document/factory.ts +590 -0
  107. package/src/commands/expense/categories.ts +40 -0
  108. package/src/commands/expense/update.ts +58 -0
  109. package/src/commands/import/index.ts +68 -0
  110. package/src/commands/item/categories.ts +40 -0
  111. package/src/commands/item/low-stock-count.ts +32 -0
  112. package/src/commands/item/merge.ts +53 -0
  113. package/src/commands/item/price-history.ts +59 -0
  114. package/src/commands/item/rename-unit.ts +39 -0
  115. package/src/commands/item/sales-stats.ts +44 -0
  116. package/src/commands/item/stock-history.ts +70 -0
  117. package/src/commands/item/switch-base-unit.ts +42 -0
  118. package/src/commands/item/update.ts +59 -0
  119. package/src/commands/item/variants-create.ts +58 -0
  120. package/src/commands/item/variants-delete.ts +47 -0
  121. package/src/commands/item/variants-list.ts +63 -0
  122. package/src/commands/item/variants-update.ts +61 -0
  123. package/src/commands/party/ledger-report.ts +81 -0
  124. package/src/commands/party/merge.ts +50 -0
  125. package/src/commands/party/stats.ts +40 -0
  126. package/src/commands/party/top-items.ts +57 -0
  127. package/src/commands/party/update.ts +65 -0
  128. package/src/commands/payment/default-account.ts +56 -0
  129. package/src/commands/payment/get.ts +59 -0
  130. package/src/commands/payment/unpaid-invoices.ts +69 -0
  131. package/src/commands/payment/untracked.ts +70 -0
  132. package/src/commands/payment/update.ts +54 -0
  133. package/src/commands/report/index.ts +348 -1
  134. package/src/commands/store/check-slug.ts +48 -0
  135. package/src/commands/store/items-toggle.ts +41 -0
  136. package/src/commands/store/items.ts +61 -0
  137. package/src/commands/store/order-cancel.ts +48 -0
  138. package/src/commands/store/order-confirm.ts +45 -0
  139. package/src/commands/store/order-get.ts +66 -0
  140. package/src/commands/store/order-update.ts +52 -0
  141. package/src/commands/store/update-settings.ts +52 -0
  142. package/src/commands/tenant/invite.ts +57 -0
  143. package/src/commands/tenant/list.ts +46 -0
  144. package/src/commands/tenant/members.ts +55 -0
  145. package/src/commands/tenant/remove.ts +47 -0
  146. package/src/commands/tenant/update-role.ts +41 -0
@@ -0,0 +1,68 @@
1
+ import { HisaaboClient, HisaaboApiError, type RecurringInvoiceSuggestion } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, outputTable, EXIT, type ColumnDef } from "../../output.js";
4
+ import chalk from "chalk";
5
+
6
+ const FREQUENCY_LABELS: Record<string, string> = {
7
+ weekly: "Weekly",
8
+ biweekly: "Every 2 Weeks",
9
+ monthly: "Monthly",
10
+ quarterly: "Quarterly",
11
+ half_yearly: "Every 6 Months",
12
+ yearly: "Yearly",
13
+ custom: "Custom",
14
+ };
15
+
16
+ function confidenceBadge(confidence: number): string {
17
+ const pct = Math.round(confidence * 100);
18
+ const label = `${pct}%`;
19
+ if (confidence >= 0.8) return chalk.green(label);
20
+ if (confidence >= 0.5) return chalk.yellow(label);
21
+ return chalk.dim(label);
22
+ }
23
+
24
+ interface SuggestionsOpts {
25
+ json?: boolean;
26
+ }
27
+
28
+ export async function automatedInvoiceSuggestionsCommand(opts: SuggestionsOpts): Promise<void> {
29
+ const cfg = requireAuth();
30
+ const client = new HisaaboClient(cfg);
31
+
32
+ try {
33
+ const result = await client.recurringInvoice.suggestions();
34
+
35
+ if (opts.json) {
36
+ outputJSON(result);
37
+ return;
38
+ }
39
+
40
+ if (result.length === 0) {
41
+ console.log("\n No recurring invoice suggestions yet.\n");
42
+ console.log(" Suggestions appear after patterns are detected in your invoice history.\n");
43
+ return;
44
+ }
45
+
46
+ console.log(`\n Recurring Invoice Suggestions ${result.length} found\n`);
47
+
48
+ const cols: ColumnDef<RecurringInvoiceSuggestion>[] = [
49
+ { key: "partyName", header: "Party", width: 24 },
50
+ { key: "frequency", header: "Suggested Frequency", width: 20, format: (v) => FREQUENCY_LABELS[String(v ?? "")] ?? String(v ?? "") },
51
+ { key: "confidence", header: "Confidence", width: 12, align: "right", format: (v) => confidenceBadge(Number(v ?? 0)) },
52
+ { key: "reason", header: "Reason", width: 36 },
53
+ ];
54
+
55
+ outputTable(result, cols);
56
+
57
+ console.log();
58
+ console.log(` Tip: run ${chalk.cyan("hisaabo automated-invoice create --party-id <id>")} to set up a template.\n`);
59
+
60
+ } catch (e) {
61
+ if (e instanceof HisaaboApiError) {
62
+ const err = e.hisaaboError;
63
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
64
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
65
+ }
66
+ fatalError(String(e instanceof Error ? e.message : e));
67
+ }
68
+ }
@@ -0,0 +1,54 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
4
+
5
+ interface UpdateOpts {
6
+ json?: boolean;
7
+ name?: string;
8
+ frequency?: string;
9
+ startDate?: string;
10
+ endDate?: string;
11
+ maxRuns?: string;
12
+ notes?: string;
13
+ }
14
+
15
+ export async function automatedInvoiceUpdateCommand(id: string, opts: UpdateOpts): Promise<void> {
16
+ const cfg = requireAuth();
17
+ const client = new HisaaboClient(cfg);
18
+
19
+ const data: Record<string, unknown> = {};
20
+ if (opts.name !== undefined) data["name"] = opts.name;
21
+ if (opts.frequency !== undefined) data["frequency"] = opts.frequency;
22
+ if (opts.startDate !== undefined) data["startDate"] = opts.startDate;
23
+ if (opts.endDate !== undefined) data["endDate"] = opts.endDate;
24
+ if (opts.maxRuns !== undefined) data["maxRuns"] = parseInt(opts.maxRuns, 10);
25
+ if (opts.notes !== undefined) data["notes"] = opts.notes;
26
+
27
+ if (Object.keys(data).length === 0) {
28
+ fatalError("No fields to update. Provide at least one option.", EXIT.USAGE);
29
+ }
30
+
31
+ try {
32
+ const result = await client.recurringInvoice.update(
33
+ id,
34
+ data as Parameters<typeof client.recurringInvoice.update>[1],
35
+ );
36
+
37
+ if (opts.json) {
38
+ outputJSON(result);
39
+ return;
40
+ }
41
+
42
+ success(`Updated recurring invoice template: ${result.name} (${result.id})`);
43
+
44
+ } catch (e) {
45
+ if (e instanceof HisaaboApiError) {
46
+ const err = e.hisaaboError;
47
+ if (err.code === "not_found") fatalError(`Recurring invoice template not found: ${id}`, EXIT.NOT_FOUND);
48
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
49
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
50
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
51
+ }
52
+ fatalError(String(e instanceof Error ? e.message : e));
53
+ }
54
+ }
@@ -0,0 +1,68 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, hasColor } from "../../output.js";
4
+ import chalk from "chalk";
5
+
6
+ const FREE_PLAN_LIMIT = 5;
7
+ const BAR_WIDTH = 20;
8
+
9
+ function usageBar(used: number, limit: number): string {
10
+ const pct = limit > 0 ? Math.min(used / limit, 1) : 0;
11
+ const filled = Math.round(pct * BAR_WIDTH);
12
+ const empty = BAR_WIDTH - filled;
13
+ const filledChar = "█".repeat(filled);
14
+ const emptyChar = "░".repeat(empty);
15
+
16
+ if (!hasColor()) return `[${filledChar}${emptyChar}]`;
17
+
18
+ const bar = pct >= 1
19
+ ? chalk.red(filledChar)
20
+ : pct >= 0.8
21
+ ? chalk.yellow(filledChar)
22
+ : chalk.green(filledChar);
23
+
24
+ return `[${bar}${chalk.dim(emptyChar)}]`;
25
+ }
26
+
27
+ interface UsageOpts {
28
+ json?: boolean;
29
+ }
30
+
31
+ export async function automatedInvoiceUsageCommand(opts: UsageOpts): Promise<void> {
32
+ const cfg = requireAuth();
33
+ const client = new HisaaboClient(cfg);
34
+
35
+ try {
36
+ const result = await client.recurringInvoice.planUsage();
37
+
38
+ if (opts.json) {
39
+ outputJSON(result);
40
+ return;
41
+ }
42
+
43
+ const limit = FREE_PLAN_LIMIT;
44
+ const pct = limit > 0 ? Math.round((result.runsThisMonth / limit) * 100) : 0;
45
+
46
+ console.log("\n Plan Usage — Recurring Invoices\n");
47
+ console.log(` Templates: ${result.totalTemplates}`);
48
+ console.log(` Runs/month: ${result.runsThisMonth} / ${limit} ${usageBar(result.runsThisMonth, limit)} ${pct}%`);
49
+
50
+ if (result.runsThisMonth >= limit) {
51
+ const msg = " Monthly run limit reached. Upgrade your plan for unlimited runs.";
52
+ console.log(hasColor() ? chalk.red(msg) : msg);
53
+ } else {
54
+ const remaining = limit - result.runsThisMonth;
55
+ console.log(` Remaining: ${remaining} run${remaining !== 1 ? "s" : ""} this month`);
56
+ }
57
+
58
+ console.log();
59
+
60
+ } catch (e) {
61
+ if (e instanceof HisaaboApiError) {
62
+ const err = e.hisaaboError;
63
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
64
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
65
+ }
66
+ fatalError(String(e instanceof Error ? e.message : e));
67
+ }
68
+ }
@@ -0,0 +1,79 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, outputTable, outputTSV, outputCSV, EXIT, hasColor, paginationFooter } from "../../output.js";
4
+ import { formatDate } from "../../format.js";
5
+ import chalk from "chalk";
6
+
7
+ interface AuditTrailOpts {
8
+ page?: string;
9
+ limit?: string;
10
+ json?: boolean;
11
+ format?: string;
12
+ }
13
+
14
+ export async function businessAuditTrailCommand(opts: AuditTrailOpts): Promise<void> {
15
+ const cfg = requireAuth();
16
+ const client = new HisaaboClient(cfg);
17
+
18
+ const page = opts.page ? parseInt(opts.page, 10) : 1;
19
+ const limit = opts.limit ? parseInt(opts.limit, 10) : 25;
20
+
21
+ if (isNaN(page) || page < 1) fatalError("--page must be a positive integer.", EXIT.USAGE);
22
+ if (isNaN(limit) || limit < 1 || limit > 100) fatalError("--limit must be between 1 and 100.", EXIT.USAGE);
23
+
24
+ try {
25
+ const data = await client.business.auditTrail({ page, limit });
26
+
27
+ if (opts.json) {
28
+ outputJSON(data);
29
+ return;
30
+ }
31
+
32
+ const items: unknown[] = Array.isArray(data)
33
+ ? data
34
+ : Array.isArray(data?.items)
35
+ ? data.items
36
+ : Array.isArray(data?.data)
37
+ ? data.data
38
+ : [];
39
+
40
+ const total: number = typeof data?.total === "number" ? data.total : items.length;
41
+
42
+ const rows = items.map((item: unknown) => {
43
+ const r = item as Record<string, unknown>;
44
+ return {
45
+ timestamp: formatDate(String(r["createdAt"] ?? r["timestamp"] ?? "")),
46
+ user: String(r["userName"] ?? r["user"] ?? r["userEmail"] ?? "-"),
47
+ action: String(r["action"] ?? r["event"] ?? "-"),
48
+ details: String(r["details"] ?? r["description"] ?? r["meta"] ?? "-"),
49
+ };
50
+ });
51
+
52
+ const columns = [
53
+ { key: "timestamp", header: "Date", align: "left" as const },
54
+ { key: "user", header: "User", align: "left" as const, width: 28 },
55
+ { key: "action", header: "Action", align: "left" as const, width: 24 },
56
+ { key: "details", header: "Details", align: "left" as const, width: 40 },
57
+ ];
58
+
59
+ if (opts.format === "tsv") {
60
+ outputTSV(rows, columns);
61
+ } else if (opts.format === "csv") {
62
+ outputCSV(rows, columns);
63
+ } else {
64
+ if (hasColor()) process.stdout.write("\n" + chalk.bold(" Audit Trail\n") + "\n");
65
+ else process.stdout.write("\n Audit Trail\n\n");
66
+ outputTable(rows, columns);
67
+ if (total > limit) paginationFooter(page, limit, total);
68
+ process.stdout.write("\n");
69
+ }
70
+ } catch (e) {
71
+ if (e instanceof HisaaboApiError) {
72
+ const err = e.hisaaboError;
73
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
74
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
75
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
76
+ }
77
+ fatalError(String(e instanceof Error ? e.message : e));
78
+ }
79
+ }
@@ -0,0 +1,52 @@
1
+ import * as readline from "readline";
2
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
3
+ import { requireAuth } from "../../config.js";
4
+ import { fatalError, success, outputJSON, EXIT } from "../../output.js";
5
+
6
+ interface BusinessExportOpts {
7
+ yes?: boolean;
8
+ json?: boolean;
9
+ }
10
+
11
+ export async function businessExportCommand(opts: BusinessExportOpts): Promise<void> {
12
+ const cfg = requireAuth();
13
+ const client = new HisaaboClient(cfg);
14
+
15
+ if (!opts.yes && process.stdin.isTTY) {
16
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
17
+ const answer = await new Promise<string>((resolve) => {
18
+ rl.question(" Export all business data? This may take a moment. (y/N): ", resolve);
19
+ });
20
+ rl.close();
21
+ if (answer.trim().toLowerCase() !== "y") {
22
+ console.log(" Cancelled.");
23
+ process.exit(0);
24
+ }
25
+ }
26
+
27
+ try {
28
+ const result = await client.business.exportData();
29
+
30
+ if (opts.json) {
31
+ outputJSON(result);
32
+ return;
33
+ }
34
+
35
+ if (result?.url) {
36
+ success("Export complete.");
37
+ process.stdout.write(` Download URL: ${result.url}\n`);
38
+ } else if (result?.status === "processing" || result?.queued) {
39
+ success("Export queued. You will be notified when the export is ready.");
40
+ } else {
41
+ success("Export initiated successfully.");
42
+ }
43
+ } catch (e) {
44
+ if (e instanceof HisaaboApiError) {
45
+ const err = e.hisaaboError;
46
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
47
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
48
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
49
+ }
50
+ fatalError(String(e instanceof Error ? e.message : e));
51
+ }
52
+ }
@@ -0,0 +1,55 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, hasColor } from "../../output.js";
4
+ import chalk from "chalk";
5
+
6
+ export async function businessGetCommand(opts: { json?: boolean }): Promise<void> {
7
+ const cfg = requireAuth();
8
+ const client = new HisaaboClient(cfg);
9
+
10
+ try {
11
+ const biz = await client.business.get();
12
+
13
+ if (opts.json) {
14
+ outputJSON(biz);
15
+ return;
16
+ }
17
+
18
+ const sep = "─".repeat(52);
19
+ const line = (label: string, value: string | null | undefined) => {
20
+ if (!value) return;
21
+ const lbl = hasColor() ? chalk.dim(label.padEnd(24)) : label.padEnd(24);
22
+ process.stdout.write(` ${lbl}${value}\n`);
23
+ };
24
+
25
+ process.stdout.write("\n");
26
+ if (hasColor()) {
27
+ process.stdout.write(" " + chalk.bold(biz.name ?? "") + "\n");
28
+ process.stdout.write(" " + chalk.dim(sep) + "\n");
29
+ } else {
30
+ process.stdout.write(` ${biz.name ?? ""}\n`);
31
+ process.stdout.write(" " + sep + "\n");
32
+ }
33
+
34
+ line("GSTIN", biz.gstin);
35
+ line("GST Type", biz.gstRegistrationType);
36
+ line("Phone", biz.phone);
37
+ line("Email", biz.email);
38
+ line("Address", biz.address);
39
+ line("City", biz.city);
40
+ line("State", biz.state);
41
+ line("Pincode", biz.pincode);
42
+ line("Financial Year Start", biz.financialYearStart ? `Month ${biz.financialYearStart}` : undefined);
43
+ line("Currency", biz.currency);
44
+ line("ID", biz.id);
45
+
46
+ process.stdout.write("\n");
47
+ } catch (e) {
48
+ if (e instanceof HisaaboApiError) {
49
+ const err = e.hisaaboError;
50
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
51
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
52
+ }
53
+ fatalError(String(e instanceof Error ? e.message : e));
54
+ }
55
+ }
@@ -0,0 +1,65 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, success, outputJSON, EXIT } from "../../output.js";
4
+
5
+ interface BusinessSequenceOpts {
6
+ type?: string;
7
+ prefix?: string;
8
+ nextNumber?: string;
9
+ json?: boolean;
10
+ }
11
+
12
+ export async function businessSequenceCommand(opts: BusinessSequenceOpts): Promise<void> {
13
+ const cfg = requireAuth();
14
+ const client = new HisaaboClient(cfg);
15
+
16
+ if (!opts.type) {
17
+ fatalError("--type is required (sale or purchase).", EXIT.USAGE);
18
+ }
19
+ if (opts.type !== "sale" && opts.type !== "purchase") {
20
+ fatalError("--type must be 'sale' or 'purchase'.", EXIT.USAGE);
21
+ }
22
+
23
+ const payload: Record<string, unknown> = { type: opts.type };
24
+ if (opts.prefix !== undefined) payload["prefix"] = opts.prefix;
25
+ if (opts.nextNumber !== undefined) {
26
+ const n = parseInt(opts.nextNumber, 10);
27
+ if (isNaN(n) || n < 1) {
28
+ fatalError("--next-number must be a positive integer.", EXIT.USAGE);
29
+ }
30
+ payload["nextNumber"] = n;
31
+ }
32
+
33
+ if (Object.keys(payload).length === 1) {
34
+ fatalError("Pass at least one of --prefix or --next-number.", EXIT.USAGE);
35
+ }
36
+
37
+ try {
38
+ const result = await client.business.updateSequenceNumber(payload);
39
+
40
+ if (opts.json) {
41
+ outputJSON(result);
42
+ return;
43
+ }
44
+
45
+ const typeLabel = opts.type === "sale" ? "Sales" : "Purchase";
46
+ const parts: string[] = [];
47
+ if (opts.prefix !== undefined) parts.push(`prefix → "${opts.prefix}"`);
48
+ if (opts.nextNumber !== undefined) parts.push(`next number → ${opts.nextNumber}`);
49
+ success(`${typeLabel} invoice sequence updated: ${parts.join(", ")}.`);
50
+ } catch (e) {
51
+ if (e instanceof HisaaboApiError) {
52
+ const err = e.hisaaboError;
53
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
54
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
55
+ if (err.code === "validation_failed") {
56
+ const msgs = Object.entries(err.fields)
57
+ .map(([f, ms]) => ` ${f}: ${ms.join(", ")}`)
58
+ .join("\n");
59
+ fatalError(`Validation failed:\n${msgs}`, EXIT.VALIDATION);
60
+ }
61
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
62
+ }
63
+ fatalError(String(e instanceof Error ? e.message : e));
64
+ }
65
+ }
@@ -0,0 +1,64 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, success, outputJSON, EXIT } from "../../output.js";
4
+
5
+ interface BusinessUpdateOpts {
6
+ name?: string;
7
+ gstin?: string;
8
+ address?: string;
9
+ state?: string;
10
+ phone?: string;
11
+ email?: string;
12
+ financialYearStart?: string;
13
+ json?: boolean;
14
+ }
15
+
16
+ export async function businessUpdateCommand(opts: BusinessUpdateOpts): Promise<void> {
17
+ const cfg = requireAuth();
18
+ const client = new HisaaboClient(cfg);
19
+
20
+ // Build update payload — only include provided fields
21
+ const payload: Record<string, unknown> = {};
22
+ if (opts.name !== undefined) payload["name"] = opts.name;
23
+ if (opts.gstin !== undefined) payload["gstin"] = opts.gstin;
24
+ if (opts.address !== undefined) payload["address"] = opts.address;
25
+ if (opts.state !== undefined) payload["state"] = opts.state;
26
+ if (opts.phone !== undefined) payload["phone"] = opts.phone;
27
+ if (opts.email !== undefined) payload["email"] = opts.email;
28
+ if (opts.financialYearStart !== undefined) {
29
+ const month = parseInt(opts.financialYearStart, 10);
30
+ if (isNaN(month) || month < 1 || month > 12) {
31
+ fatalError("--financial-year-start must be a month number (1–12).", EXIT.USAGE);
32
+ }
33
+ payload["financialYearStart"] = month;
34
+ }
35
+
36
+ if (Object.keys(payload).length === 0) {
37
+ fatalError("No fields to update. Pass at least one option (--name, --gstin, etc.).", EXIT.USAGE);
38
+ }
39
+
40
+ try {
41
+ const result = await client.business.update(payload);
42
+
43
+ if (opts.json) {
44
+ outputJSON(result);
45
+ return;
46
+ }
47
+
48
+ success("Business settings updated.");
49
+ } catch (e) {
50
+ if (e instanceof HisaaboApiError) {
51
+ const err = e.hisaaboError;
52
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
53
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
54
+ if (err.code === "validation_failed") {
55
+ const msgs = Object.entries(err.fields)
56
+ .map(([f, ms]) => ` ${f}: ${ms.join(", ")}`)
57
+ .join("\n");
58
+ fatalError(`Validation failed:\n${msgs}`, EXIT.VALIDATION);
59
+ }
60
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
61
+ }
62
+ fatalError(String(e instanceof Error ? e.message : e));
63
+ }
64
+ }
@@ -0,0 +1,164 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, outputTable, outputTSV, outputCSV, EXIT, hasColor, termWidth } from "../../output.js";
4
+ import { formatAmount, fyStart, todayISO, monthStart, monthEnd } from "../../format.js";
5
+ import chalk from "chalk";
6
+
7
+ interface CollectionEfficiencyOpts {
8
+ from?: string;
9
+ to?: string;
10
+ thisMonth?: boolean;
11
+ thisFy?: boolean;
12
+ json?: boolean;
13
+ format?: string;
14
+ }
15
+
16
+ function rateBar(rate: number, width: number): string {
17
+ const clamped = Math.min(100, Math.max(0, rate));
18
+ const filled = Math.round((clamped / 100) * width);
19
+ const bar = "█".repeat(filled) + "░".repeat(width - filled);
20
+ if (!hasColor()) return bar;
21
+ if (clamped >= 80) return chalk.green(bar);
22
+ if (clamped >= 50) return chalk.yellow(bar);
23
+ return chalk.red(bar);
24
+ }
25
+
26
+ export async function dashboardCollectionEfficiencyCommand(opts: CollectionEfficiencyOpts): Promise<void> {
27
+ const cfg = requireAuth();
28
+ const client = new HisaaboClient(cfg);
29
+
30
+ let fromDate = opts.from;
31
+ let toDate = opts.to;
32
+ if (opts.thisMonth) { fromDate = monthStart(); toDate = monthEnd(); }
33
+ else if (opts.thisFy) { fromDate = fyStart(); toDate = todayISO(); }
34
+
35
+ try {
36
+ const data = await client.dashboard.collectionEfficiency({ fromDate, toDate });
37
+
38
+ if (opts.json) {
39
+ outputJSON(data);
40
+ return;
41
+ }
42
+
43
+ const d = (data ?? {}) as Record<string, unknown>;
44
+
45
+ // Top-level metrics
46
+ const totalInvoiced = parseFloat(String(d["totalInvoiced"] ?? d["invoiced"] ?? d["billed"] ?? "0"));
47
+ const totalCollected = parseFloat(String(d["totalCollected"] ?? d["collected"] ?? d["received"] ?? "0"));
48
+ const outstanding = parseFloat(String(d["outstanding"] ?? d["totalOutstanding"] ?? String(totalInvoiced - totalCollected)));
49
+ const collectionRate = parseFloat(String(d["collectionRate"] ?? d["rate"] ?? (totalInvoiced > 0 ? ((totalCollected / totalInvoiced) * 100).toFixed(2) : "0")));
50
+ const dso = parseFloat(String(d["dso"] ?? d["daysSalesOutstanding"] ?? "0"));
51
+
52
+ // Aging breakdown sub-object
53
+ const aging = (d["aging"] ?? d["agingBreakdown"] ?? d["breakdown"] ?? null) as Record<string, unknown> | null;
54
+
55
+ if (opts.format === "tsv" || opts.format === "csv") {
56
+ const rows: Array<Record<string, string>> = [
57
+ { metric: "Total Invoiced", value: formatAmount(totalInvoiced) },
58
+ { metric: "Total Collected", value: formatAmount(totalCollected) },
59
+ { metric: "Outstanding", value: formatAmount(outstanding) },
60
+ { metric: "Collection Rate", value: `${collectionRate.toFixed(1)}%` },
61
+ { metric: "DSO (days)", value: dso > 0 ? String(Math.round(dso)) : "-" },
62
+ ];
63
+ if (aging) {
64
+ for (const [k, v] of Object.entries(aging)) {
65
+ rows.push({ metric: `Aging: ${k}`, value: formatAmount(String(v)) });
66
+ }
67
+ }
68
+ const columns = [
69
+ { key: "metric", header: "Metric", align: "left" as const },
70
+ { key: "value", header: "Value", align: "right" as const },
71
+ ];
72
+ if (opts.format === "tsv") outputTSV(rows, columns);
73
+ else outputCSV(rows, columns);
74
+ return;
75
+ }
76
+
77
+ // Pretty display
78
+ const width = Math.min(termWidth() - 4, 56);
79
+ const innerW = width - 2;
80
+ const barW = Math.max(8, innerW - 22);
81
+
82
+ const line = (label: string, value: string, opts2: { bold?: boolean; color?: (s: string) => string } = {}): void => {
83
+ const lbl = label.padEnd(20).slice(0, 20);
84
+ const val = value.padStart(innerW - 22).slice(0, innerW - 22);
85
+ let out = ` │ ${lbl} ${val} │`;
86
+ if (hasColor()) {
87
+ if (opts2.bold) out = ` │ ${chalk.bold(lbl)} ${val} │`;
88
+ if (opts2.color) out = ` │ ${opts2.bold ? chalk.bold(lbl) : lbl} ${opts2.color(val)} │`;
89
+ }
90
+ process.stdout.write(out + "\n");
91
+ };
92
+
93
+ const sep = (): void => { process.stdout.write(" ├" + "─".repeat(innerW) + "┤\n"); };
94
+
95
+ process.stdout.write("\n");
96
+ if (hasColor()) process.stdout.write(" " + chalk.bold("Collection Efficiency") + "\n\n");
97
+ else process.stdout.write(" Collection Efficiency\n\n");
98
+
99
+ process.stdout.write(" ┌" + "─".repeat(innerW) + "┐\n");
100
+
101
+ line("Total Invoiced", `₹${formatAmount(totalInvoiced)}`, { bold: true });
102
+ line("Total Collected", `₹${formatAmount(totalCollected)}`, {
103
+ color: totalCollected >= totalInvoiced * 0.8 ? chalk.green : chalk.yellow,
104
+ });
105
+ line("Outstanding", `₹${formatAmount(outstanding)}`, {
106
+ color: outstanding > 0 ? chalk.red : chalk.green,
107
+ });
108
+ sep();
109
+
110
+ // Collection rate with bar
111
+ const rateStr = `${collectionRate.toFixed(1)}%`;
112
+ const bar = rateBar(collectionRate, barW);
113
+ const rateLabel = "Collection Rate".padEnd(20).slice(0, 20);
114
+ process.stdout.write(` │ ${hasColor() ? chalk.bold(rateLabel) : rateLabel} ${bar} ${rateStr.padStart(6)} │\n`);
115
+
116
+ if (dso > 0) {
117
+ const dsoStr = `${Math.round(dso)} days`;
118
+ const dsoLabel = "DSO".padEnd(20).slice(0, 20);
119
+ const dsoColor = dso <= 30 ? chalk.green : dso <= 60 ? chalk.yellow : chalk.red;
120
+ const dsoVal = hasColor() ? dsoColor(dsoStr) : dsoStr;
121
+ process.stdout.write(` │ ${dsoLabel} ${dsoVal.padStart(innerW - 22)} │\n`);
122
+ }
123
+
124
+ // Aging buckets if available
125
+ if (aging && Object.keys(aging).length > 0) {
126
+ sep();
127
+ process.stdout.write(` │ ${hasColor() ? chalk.bold("Aging Breakdown") : "Aging Breakdown"}${" ".repeat(innerW - 16)} │\n`);
128
+ const agingEntries = Object.entries(aging);
129
+ for (const [bucket, val] of agingEntries) {
130
+ const amt = parseFloat(String(val));
131
+ const amtStr = `₹${formatAmount(amt)}`;
132
+ const bucketLabel = bucket.padEnd(20).slice(0, 20);
133
+ const isOld = /90\+|90_plus/i.test(bucket);
134
+ const color = isOld ? chalk.red : /31|61/.test(bucket) ? chalk.yellow : undefined;
135
+ const valStr = color && hasColor() ? color(amtStr) : amtStr;
136
+ process.stdout.write(` │ ${bucketLabel.slice(0, 18)} ${valStr.padStart(innerW - 22)} │\n`);
137
+ }
138
+ }
139
+
140
+ process.stdout.write(" └" + "─".repeat(innerW) + "┘\n\n");
141
+
142
+ // Also show aging as a table for easy reading
143
+ if (aging && Object.keys(aging).length > 0) {
144
+ const agingRows = Object.entries(aging).map(([bucket, val]) => ({
145
+ bucket,
146
+ amount: formatAmount(String(val)),
147
+ }));
148
+ const agingColumns = [
149
+ { key: "bucket", header: "Aging Bucket", align: "left" as const },
150
+ { key: "amount", header: "Amount ₹", align: "right" as const },
151
+ ];
152
+ outputTable(agingRows, agingColumns);
153
+ process.stdout.write("\n");
154
+ }
155
+
156
+ } catch (e) {
157
+ if (e instanceof HisaaboApiError) {
158
+ const err = e.hisaaboError;
159
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
160
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
161
+ }
162
+ fatalError(String(e instanceof Error ? e.message : e));
163
+ }
164
+ }