@hisaabo/cli 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/.turbo/turbo-typecheck.log +1 -1
  2. package/README.md +332 -0
  3. package/dist/bin/audit-trail-5LOCJ7XZ.js +78 -0
  4. package/dist/bin/categories-64WWZTND.js +47 -0
  5. package/dist/bin/check-slug-FLHHUDYS.js +65 -0
  6. package/dist/bin/chunk-4MEL44QX.js +848 -0
  7. package/dist/bin/chunk-FIMJZAS4.js +84 -0
  8. package/dist/bin/chunk-NO4FIFMS.js +176 -0
  9. package/dist/bin/chunk-T63VQXNM.js +156 -0
  10. package/dist/bin/client-5NZ23GML.js +11 -0
  11. package/dist/bin/collection-efficiency-U56XNVEE.js +165 -0
  12. package/dist/bin/config-335MN4I7.js +18 -0
  13. package/dist/bin/create-RPDEORDD.js +83 -0
  14. package/dist/bin/default-account-AE6EXZZR.js +58 -0
  15. package/dist/bin/expenses-5N2QSG54.js +89 -0
  16. package/dist/bin/export-QICOQK34.js +59 -0
  17. package/dist/bin/factory-KOCW2AQM.js +483 -0
  18. package/dist/bin/get-A43QCI2S.js +66 -0
  19. package/dist/bin/get-GWH6S5SJ.js +71 -0
  20. package/dist/bin/hisaabo.js +2302 -1510
  21. package/dist/bin/invitations-P3EEN5WI.js +66 -0
  22. package/dist/bin/invite-T3CKX53E.js +53 -0
  23. package/dist/bin/invoice-breakdown-FN5BEFJD.js +97 -0
  24. package/dist/bin/items-2OOCQKVF.js +62 -0
  25. package/dist/bin/items-toggle-SKZWCGJH.js +46 -0
  26. package/dist/bin/list-A2RKI3ZG.js +79 -0
  27. package/dist/bin/list-NRMBMKMI.js +90 -0
  28. package/dist/bin/list-T74SN6IR.js +46 -0
  29. package/dist/bin/members-W2GW3ODT.js +55 -0
  30. package/dist/bin/monthly-comparison-T34ZFOHL.js +176 -0
  31. package/dist/bin/order-cancel-TI27JYYD.js +55 -0
  32. package/dist/bin/order-confirm-VMRAMNTD.js +53 -0
  33. package/dist/bin/order-get-C2RBUR4O.js +88 -0
  34. package/dist/bin/order-update-RE3HATNF.js +60 -0
  35. package/dist/bin/output-NUOL7KJW.js +35 -0
  36. package/dist/bin/payment-modes-WOOT22I7.js +126 -0
  37. package/dist/bin/profit-loss-T4RESJ32.js +135 -0
  38. package/dist/bin/receivables-aging-6XMENEWS.js +161 -0
  39. package/dist/bin/remove-6QZI4JCY.js +52 -0
  40. package/dist/bin/revoke-AVEMPAC7.js +40 -0
  41. package/dist/bin/revoke-YUCFZFNR.js +52 -0
  42. package/dist/bin/revoke-all-LFW5WBHO.js +33 -0
  43. package/dist/bin/revoke-invitation-DTGQRJR4.js +40 -0
  44. package/dist/bin/sales-trend-ZYBRUDUU.js +71 -0
  45. package/dist/bin/sequence-FPOJTI2P.js +66 -0
  46. package/dist/bin/store-IOB4Y67C.js +82 -0
  47. package/dist/bin/summary-5KYBA4ZO.js +113 -0
  48. package/dist/bin/top-customers-WSQ2UEJL.js +81 -0
  49. package/dist/bin/top-items-RWQPDGLN.js +84 -0
  50. package/dist/bin/top-outstanding-QAMO2E7Y.js +64 -0
  51. package/dist/bin/unpaid-invoices-WB3TK5B4.js +65 -0
  52. package/dist/bin/untracked-H733MYJL.js +67 -0
  53. package/dist/bin/update-H6LPO2Z4.js +61 -0
  54. package/dist/bin/update-JU2X3XU5.js +54 -0
  55. package/dist/bin/update-TLBUIC5J.js +57 -0
  56. package/dist/bin/update-role-QST7BVFX.js +45 -0
  57. package/dist/bin/update-settings-Q2EGRLKZ.js +56 -0
  58. package/package.json +7 -6
  59. package/src/auth.ts +12 -3
  60. package/src/bin/hisaabo.ts +49 -935
  61. package/src/bin/registrars/api-key.ts +44 -0
  62. package/src/bin/registrars/auth.ts +222 -0
  63. package/src/bin/registrars/automated-invoice.ts +167 -0
  64. package/src/bin/registrars/bank.ts +124 -0
  65. package/src/bin/registrars/business.ts +120 -0
  66. package/src/bin/registrars/dashboard.ts +225 -0
  67. package/src/bin/registrars/document.ts +184 -0
  68. package/src/bin/registrars/expense.ts +87 -0
  69. package/src/bin/registrars/gst.ts +41 -0
  70. package/src/bin/registrars/import.ts +49 -0
  71. package/src/bin/registrars/invoice.ts +117 -0
  72. package/src/bin/registrars/item.ts +112 -0
  73. package/src/bin/registrars/party.ts +81 -0
  74. package/src/bin/registrars/payment.ts +128 -0
  75. package/src/bin/registrars/report.ts +142 -0
  76. package/src/bin/registrars/session.ts +32 -0
  77. package/src/bin/registrars/shipment.ts +74 -0
  78. package/src/bin/registrars/store.ts +128 -0
  79. package/src/bin/registrars/target.ts +46 -0
  80. package/src/bin/registrars/tenant.ts +73 -0
  81. package/src/client.ts +589 -15
  82. package/src/commands/api-key/create.ts +72 -0
  83. package/src/commands/api-key/list.ts +71 -0
  84. package/src/commands/api-key/revoke.ts +46 -0
  85. package/src/commands/automated-invoice/create.ts +85 -0
  86. package/src/commands/automated-invoice/delete.ts +42 -0
  87. package/src/commands/automated-invoice/get.ts +113 -0
  88. package/src/commands/automated-invoice/history.ts +65 -0
  89. package/src/commands/automated-invoice/index.ts +11 -0
  90. package/src/commands/automated-invoice/list.ts +91 -0
  91. package/src/commands/automated-invoice/pause.ts +29 -0
  92. package/src/commands/automated-invoice/resume.ts +29 -0
  93. package/src/commands/automated-invoice/run-now.ts +29 -0
  94. package/src/commands/automated-invoice/suggestions.ts +68 -0
  95. package/src/commands/automated-invoice/update.ts +54 -0
  96. package/src/commands/automated-invoice/usage.ts +68 -0
  97. package/src/commands/bank/gateway-config.ts +61 -0
  98. package/src/commands/bank/update-gateway.ts +84 -0
  99. package/src/commands/business/audit-trail.ts +79 -0
  100. package/src/commands/business/export.ts +52 -0
  101. package/src/commands/business/get.ts +55 -0
  102. package/src/commands/business/sequence.ts +65 -0
  103. package/src/commands/business/update.ts +64 -0
  104. package/src/commands/dashboard/collection-efficiency.ts +164 -0
  105. package/src/commands/dashboard/expenses.ts +76 -0
  106. package/src/commands/dashboard/invoice-breakdown.ts +89 -0
  107. package/src/commands/dashboard/monthly-comparison.ts +193 -0
  108. package/src/commands/dashboard/payment-modes.ts +121 -0
  109. package/src/commands/dashboard/profit-loss.ts +146 -0
  110. package/src/commands/dashboard/receivables-aging.ts +169 -0
  111. package/src/commands/dashboard/sales-trend.ts +68 -0
  112. package/src/commands/dashboard/summary.ts +105 -0
  113. package/src/commands/dashboard/top-customers.ts +70 -0
  114. package/src/commands/dashboard/top-items.ts +74 -0
  115. package/src/commands/dashboard/top-outstanding.ts +61 -0
  116. package/src/commands/document/factory.ts +590 -0
  117. package/src/commands/expense/categories.ts +40 -0
  118. package/src/commands/expense/update.ts +58 -0
  119. package/src/commands/import/index.ts +68 -0
  120. package/src/commands/item/categories.ts +40 -0
  121. package/src/commands/item/low-stock-count.ts +32 -0
  122. package/src/commands/item/merge.ts +53 -0
  123. package/src/commands/item/price-history.ts +59 -0
  124. package/src/commands/item/rename-unit.ts +39 -0
  125. package/src/commands/item/sales-stats.ts +44 -0
  126. package/src/commands/item/stock-history.ts +70 -0
  127. package/src/commands/item/switch-base-unit.ts +42 -0
  128. package/src/commands/item/update.ts +59 -0
  129. package/src/commands/item/variants-create.ts +58 -0
  130. package/src/commands/item/variants-delete.ts +47 -0
  131. package/src/commands/item/variants-list.ts +63 -0
  132. package/src/commands/item/variants-update.ts +61 -0
  133. package/src/commands/party/ledger-report.ts +81 -0
  134. package/src/commands/party/merge.ts +50 -0
  135. package/src/commands/party/stats.ts +40 -0
  136. package/src/commands/party/top-items.ts +57 -0
  137. package/src/commands/party/update.ts +65 -0
  138. package/src/commands/payment/default-account.ts +56 -0
  139. package/src/commands/payment/get.ts +59 -0
  140. package/src/commands/payment/unpaid-invoices.ts +69 -0
  141. package/src/commands/payment/untracked.ts +70 -0
  142. package/src/commands/payment/update.ts +54 -0
  143. package/src/commands/report/index.ts +348 -1
  144. package/src/commands/session/list.ts +91 -0
  145. package/src/commands/session/revoke-all.ts +20 -0
  146. package/src/commands/session/revoke.ts +32 -0
  147. package/src/commands/store/check-slug.ts +48 -0
  148. package/src/commands/store/items-toggle.ts +41 -0
  149. package/src/commands/store/items.ts +61 -0
  150. package/src/commands/store/order-cancel.ts +48 -0
  151. package/src/commands/store/order-confirm.ts +45 -0
  152. package/src/commands/store/order-get.ts +66 -0
  153. package/src/commands/store/order-update.ts +52 -0
  154. package/src/commands/store/update-settings.ts +52 -0
  155. package/src/commands/tenant/invitations.ts +62 -0
  156. package/src/commands/tenant/invite.ts +57 -0
  157. package/src/commands/tenant/list.ts +46 -0
  158. package/src/commands/tenant/members.ts +55 -0
  159. package/src/commands/tenant/remove.ts +47 -0
  160. package/src/commands/tenant/revoke-invitation.ts +32 -0
  161. package/src/commands/tenant/update-role.ts +41 -0
  162. package/src/config.ts +51 -2
  163. package/src/error-handler.ts +53 -0
  164. package/src/output.ts +1 -0
  165. package/src/spinner.ts +39 -0
  166. package/tsup.config.ts +6 -1
  167. package/src/components/ErrorDisplay.tsx +0 -16
  168. package/src/components/Header.tsx +0 -26
  169. package/src/components/MoneyCell.tsx +0 -16
  170. package/src/components/Spinner.tsx +0 -12
  171. package/src/components/StatusBadge.tsx +0 -39
  172. package/src/components/Table.tsx +0 -63
@@ -0,0 +1,29 @@
1
+ import { HisaaboClient, HisaaboApiError } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
4
+
5
+ export async function automatedInvoiceRunNowCommand(id: string, opts: { json?: boolean }): Promise<void> {
6
+ const cfg = requireAuth();
7
+ const client = new HisaaboClient(cfg);
8
+
9
+ try {
10
+ const result = await client.recurringInvoice.runNow(id);
11
+
12
+ if (opts.json) {
13
+ outputJSON(result);
14
+ return;
15
+ }
16
+
17
+ success(`Manually triggered recurring invoice template: ${id}`);
18
+
19
+ } catch (e) {
20
+ if (e instanceof HisaaboApiError) {
21
+ const err = e.hisaaboError;
22
+ if (err.code === "not_found") fatalError(`Template not found: ${id}`, EXIT.NOT_FOUND);
23
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
24
+ if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
25
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
26
+ }
27
+ fatalError(String(e instanceof Error ? e.message : e));
28
+ }
29
+ }
@@ -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,61 @@
1
+ import { HisaaboClient, HisaaboApiError, type GatewayChargeRate } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, outputTable, EXIT, type ColumnDef } from "../../output.js";
4
+
5
+ function formatChargeRate(rate: GatewayChargeRate | undefined): string {
6
+ if (!rate) return "-";
7
+ return rate.type === "percentage" ? `${rate.value}%` : `Flat ${rate.value}`;
8
+ }
9
+
10
+ export async function bankGatewayConfigCommand(
11
+ accountId: string,
12
+ opts: { json?: boolean },
13
+ ): Promise<void> {
14
+ const cfg = requireAuth();
15
+ const client = new HisaaboClient(cfg);
16
+
17
+ try {
18
+ const config = await client.bankAccount.getGatewayConfig(accountId);
19
+
20
+ if (!config) {
21
+ fatalError(`No gateway configuration found for account: ${accountId}`, EXIT.NOT_FOUND);
22
+ }
23
+
24
+ if (opts.json) {
25
+ outputJSON(config);
26
+ return;
27
+ }
28
+
29
+ console.log(`\n Gateway Configuration`);
30
+ console.log(" " + "\u2500".repeat(45));
31
+ console.log(` Account: ${accountId}`);
32
+ console.log(` Settlement Account: ${config.settlementAccountId}`);
33
+ console.log(` Expense Category: ${config.expenseCategory}`);
34
+ console.log(` Auto Settle: ${config.autoSettle ? "Yes" : "No"}`);
35
+ console.log(` Active: ${config.isActive ? "Yes" : "No"}`);
36
+ console.log();
37
+
38
+ const modes = ["credit_card", "debit_card", "upi", "net_banking", "wallet", "default"] as const;
39
+ const rows = modes.map((mode) => ({
40
+ mode,
41
+ rate: formatChargeRate(config.chargeConfig[mode]),
42
+ }));
43
+
44
+ const cols: ColumnDef<{ mode: string; rate: string }>[] = [
45
+ { key: "mode", header: "Payment Mode", width: 18 },
46
+ { key: "rate", header: "Charge Rate", width: 16 },
47
+ ];
48
+
49
+ console.log(" Charge Rates:\n");
50
+ outputTable(rows, cols);
51
+ console.log();
52
+ } catch (e) {
53
+ if (e instanceof HisaaboApiError) {
54
+ const err = e.hisaaboError;
55
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
56
+ if (err.code === "not_found") fatalError(`Bank account not found: ${accountId}`, EXIT.NOT_FOUND);
57
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
58
+ }
59
+ fatalError(String(e instanceof Error ? e.message : e));
60
+ }
61
+ }
@@ -0,0 +1,84 @@
1
+ import { HisaaboClient, HisaaboApiError, type GatewayChargeConfig } from "../../client.js";
2
+ import { requireAuth } from "../../config.js";
3
+ import { fatalError, outputJSON, EXIT, success } from "../../output.js";
4
+
5
+ export interface UpdateGatewayOpts {
6
+ json?: boolean;
7
+ chargeCreditCard?: string;
8
+ chargeDebitCard?: string;
9
+ chargeUpi?: string;
10
+ chargeNetBanking?: string;
11
+ chargeWallet?: string;
12
+ chargeDefault?: string;
13
+ settlementAccount?: string;
14
+ }
15
+
16
+ function parseChargeRate(value: string): { type: "percentage" | "flat"; value: string } {
17
+ // If value starts with "flat:" treat as flat amount, otherwise percentage
18
+ if (value.toLowerCase().startsWith("flat:")) {
19
+ return { type: "flat", value: value.slice(5) };
20
+ }
21
+ return { type: "percentage", value };
22
+ }
23
+
24
+ export async function bankUpdateGatewayCommand(
25
+ accountId: string,
26
+ opts: UpdateGatewayOpts,
27
+ ): Promise<void> {
28
+ const cfg = requireAuth();
29
+ const client = new HisaaboClient(cfg);
30
+
31
+ try {
32
+ // Fetch existing config to merge with updates
33
+ const existing = await client.bankAccount.getGatewayConfig(accountId);
34
+
35
+ const chargeConfig: GatewayChargeConfig = existing?.chargeConfig ?? {};
36
+
37
+ if (opts.chargeCreditCard !== undefined) {
38
+ chargeConfig.credit_card = parseChargeRate(opts.chargeCreditCard);
39
+ }
40
+ if (opts.chargeDebitCard !== undefined) {
41
+ chargeConfig.debit_card = parseChargeRate(opts.chargeDebitCard);
42
+ }
43
+ if (opts.chargeUpi !== undefined) {
44
+ chargeConfig.upi = parseChargeRate(opts.chargeUpi);
45
+ }
46
+ if (opts.chargeNetBanking !== undefined) {
47
+ chargeConfig.net_banking = parseChargeRate(opts.chargeNetBanking);
48
+ }
49
+ if (opts.chargeWallet !== undefined) {
50
+ chargeConfig.wallet = parseChargeRate(opts.chargeWallet);
51
+ }
52
+ if (opts.chargeDefault !== undefined) {
53
+ chargeConfig.default = parseChargeRate(opts.chargeDefault);
54
+ }
55
+
56
+ const settlementAccountId = opts.settlementAccount ?? existing?.settlementAccountId;
57
+ if (!settlementAccountId) {
58
+ fatalError("--settlement-account is required when creating a new gateway config", EXIT.USAGE);
59
+ }
60
+
61
+ const result = await client.bankAccount.upsertGatewayConfig({
62
+ bankAccountId: accountId,
63
+ settlementAccountId,
64
+ chargeConfig,
65
+ });
66
+
67
+ if (opts.json) {
68
+ outputJSON(result);
69
+ return;
70
+ }
71
+
72
+ success(`Gateway configuration updated for account: ${accountId}`);
73
+ console.log(` Settlement Account: ${result.settlementAccountId}\n`);
74
+ } catch (e) {
75
+ if (e instanceof HisaaboApiError) {
76
+ const err = e.hisaaboError;
77
+ if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
78
+ if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
79
+ if (err.code === "not_found") fatalError(`Bank account not found: ${accountId}`, EXIT.NOT_FOUND);
80
+ if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
81
+ }
82
+ fatalError(String(e instanceof Error ? e.message : e));
83
+ }
84
+ }
@@ -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
+ }