@hisaabo/cli 0.7.5 → 0.8.4

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 (210) hide show
  1. package/LICENSE +31 -0
  2. package/README.md +9 -0
  3. package/dist/bin/{audit-trail-DLSSSM4T.js → audit-trail-IJ6SKACR.js} +2 -2
  4. package/dist/bin/{categories-63QR6WCV.js → categories-O6TODPAH.js} +2 -2
  5. package/dist/bin/{check-slug-NXO55WKH.js → check-slug-P7RFU6OP.js} +2 -2
  6. package/dist/bin/chunk-NO4FIFMS.js +0 -0
  7. package/dist/bin/{chunk-7MJDOL6B.js → chunk-QUITS2FE.js} +28 -0
  8. package/dist/bin/{chunk-M42SETRZ.js → chunk-WDN7RIE3.js} +23 -2
  9. package/dist/bin/chunk-ZPYC767N.js +0 -0
  10. package/dist/bin/{client-T32CIZA3.js → client-36JX5MR3.js} +1 -1
  11. package/dist/bin/{collection-efficiency-T6PWNTZO.js → collection-efficiency-DA5RWG3V.js} +2 -2
  12. package/dist/bin/{config-V4QFCONN.js → config-4LLNT4SH.js} +3 -1
  13. package/dist/bin/{create-NUKHDWLK.js → create-C5INBPQO.js} +2 -2
  14. package/dist/bin/{default-account-JWFPHMRF.js → default-account-2GMQ7ZA4.js} +2 -2
  15. package/dist/bin/{expenses-2UWUZVLI.js → expenses-S2YVA5UT.js} +2 -2
  16. package/dist/bin/{export-XSX7WQH7.js → export-YOOODNVX.js} +2 -2
  17. package/dist/bin/export-ZA43MLWO.js +191 -0
  18. package/dist/bin/{factory-BWOKRIP4.js → factory-6MUCSXTL.js} +2 -2
  19. package/dist/bin/{get-CHNTG3IM.js → get-GMQRROK2.js} +2 -2
  20. package/dist/bin/{get-ZSZ6SL3N.js → get-ZV3SC2VY.js} +2 -2
  21. package/dist/bin/hisaabo.js +100 -57
  22. package/dist/bin/import-UUHMLCKX.js +267 -0
  23. package/dist/bin/{invitations-H2SL3XAD.js → invitations-OVORTTMF.js} +2 -2
  24. package/dist/bin/{invite-EW73UIBE.js → invite-GGHBZY4U.js} +2 -2
  25. package/dist/bin/{invoice-breakdown-XP4QATCF.js → invoice-breakdown-32XXAZDP.js} +2 -2
  26. package/dist/bin/{items-DPD6EFTP.js → items-6NOIMH6B.js} +2 -2
  27. package/dist/bin/{items-toggle-R4OPSE4W.js → items-toggle-L6W6QKQD.js} +2 -2
  28. package/dist/bin/{list-PKHBE475.js → list-FC5JHKHD.js} +2 -2
  29. package/dist/bin/{list-KLEHBMQ2.js → list-OXAVDXH7.js} +2 -2
  30. package/dist/bin/{list-UR7OOJVF.js → list-RAR56EMQ.js} +2 -2
  31. package/dist/bin/{members-XA3TF4IQ.js → members-Y6XJVHHR.js} +2 -2
  32. package/dist/bin/{monthly-comparison-OLVS5HEY.js → monthly-comparison-IAUZ6SBJ.js} +2 -2
  33. package/dist/bin/{order-cancel-MXMJFFRR.js → order-cancel-QRTCNART.js} +2 -2
  34. package/dist/bin/{order-confirm-IXU45Q4L.js → order-confirm-LGQOMC4O.js} +2 -2
  35. package/dist/bin/{order-get-RDXMHLJ7.js → order-get-4XAQCRYV.js} +2 -2
  36. package/dist/bin/{order-update-KGIPBEJX.js → order-update-KZY4H2UR.js} +2 -2
  37. package/dist/bin/output-NUOL7KJW.js +0 -0
  38. package/dist/bin/{payment-modes-CZL35SVS.js → payment-modes-DY2ZEMK7.js} +2 -2
  39. package/dist/bin/{profit-loss-M332OSC5.js → profit-loss-5GJBG3PL.js} +2 -2
  40. package/dist/bin/{receivables-aging-OXRHGMBF.js → receivables-aging-6A7XJKDT.js} +2 -2
  41. package/dist/bin/{remove-I5HD2Y4K.js → remove-ZBX34TIQ.js} +2 -2
  42. package/dist/bin/{revoke-OC6AOMIZ.js → revoke-XDNOA2GJ.js} +2 -2
  43. package/dist/bin/{revoke-MFLWGCMP.js → revoke-ZTAMW2Q2.js} +2 -2
  44. package/dist/bin/{revoke-all-FSAPBB3P.js → revoke-all-365NRBOA.js} +2 -2
  45. package/dist/bin/{revoke-invitation-JXDPXTOW.js → revoke-invitation-PQH7XNYA.js} +2 -2
  46. package/dist/bin/{sales-trend-KK63WNDL.js → sales-trend-D6PQ7MHY.js} +2 -2
  47. package/dist/bin/{sequence-IQ4HUJ3W.js → sequence-KZWADVD7.js} +2 -2
  48. package/dist/bin/{store-6QT6HKG2.js → store-SVRZBUFO.js} +2 -2
  49. package/dist/bin/{summary-3FTF5B4A.js → summary-H6U7O5GJ.js} +2 -2
  50. package/dist/bin/{top-customers-HNYGXBQZ.js → top-customers-ATBN6RDI.js} +2 -2
  51. package/dist/bin/{top-items-JUDG3BVW.js → top-items-XXU6KYTC.js} +2 -2
  52. package/dist/bin/{top-outstanding-WK26ZNE5.js → top-outstanding-JTQNGGW4.js} +2 -2
  53. package/dist/bin/{unpaid-invoices-RYFIIIK7.js → unpaid-invoices-BTNQFWCH.js} +2 -2
  54. package/dist/bin/{untracked-FAFS3KCK.js → untracked-PAMEDJ6Y.js} +2 -2
  55. package/dist/bin/{update-5YSPXIWO.js → update-6ZMX2OYX.js} +2 -2
  56. package/dist/bin/{update-I46XLU77.js → update-EGHPFXLK.js} +2 -2
  57. package/dist/bin/{update-NAW2JWZS.js → update-EK4NJWU4.js} +2 -2
  58. package/dist/bin/{update-role-5GV42MSN.js → update-role-24PDTNFK.js} +2 -2
  59. package/dist/bin/{update-settings-KYSQDIEO.js → update-settings-AASI6WZX.js} +2 -2
  60. package/package.json +35 -9
  61. package/.turbo/turbo-build.log +0 -13
  62. package/.turbo/turbo-typecheck.log +0 -4
  63. package/CLI-UX-ARCHITECTURE.md +0 -1269
  64. package/src/auth.ts +0 -221
  65. package/src/bin/hisaabo.ts +0 -74
  66. package/src/bin/registrars/api-key.ts +0 -44
  67. package/src/bin/registrars/auth.ts +0 -222
  68. package/src/bin/registrars/automated-invoice.ts +0 -167
  69. package/src/bin/registrars/bank-recon.ts +0 -34
  70. package/src/bin/registrars/bank.ts +0 -124
  71. package/src/bin/registrars/business.ts +0 -120
  72. package/src/bin/registrars/dashboard.ts +0 -225
  73. package/src/bin/registrars/document.ts +0 -184
  74. package/src/bin/registrars/einvoice.ts +0 -46
  75. package/src/bin/registrars/ewb.ts +0 -37
  76. package/src/bin/registrars/expense.ts +0 -87
  77. package/src/bin/registrars/gst.ts +0 -57
  78. package/src/bin/registrars/import.ts +0 -49
  79. package/src/bin/registrars/invoice.ts +0 -117
  80. package/src/bin/registrars/itc.ts +0 -56
  81. package/src/bin/registrars/item.ts +0 -112
  82. package/src/bin/registrars/journal.ts +0 -47
  83. package/src/bin/registrars/party.ts +0 -81
  84. package/src/bin/registrars/payment.ts +0 -128
  85. package/src/bin/registrars/report.ts +0 -186
  86. package/src/bin/registrars/session.ts +0 -32
  87. package/src/bin/registrars/shipment.ts +0 -74
  88. package/src/bin/registrars/store.ts +0 -128
  89. package/src/bin/registrars/target.ts +0 -46
  90. package/src/bin/registrars/tenant.ts +0 -73
  91. package/src/client.ts +0 -2071
  92. package/src/commands/api-key/create.ts +0 -72
  93. package/src/commands/api-key/list.ts +0 -71
  94. package/src/commands/api-key/revoke.ts +0 -46
  95. package/src/commands/automated-invoice/create.ts +0 -85
  96. package/src/commands/automated-invoice/delete.ts +0 -42
  97. package/src/commands/automated-invoice/get.ts +0 -113
  98. package/src/commands/automated-invoice/history.ts +0 -65
  99. package/src/commands/automated-invoice/index.ts +0 -11
  100. package/src/commands/automated-invoice/list.ts +0 -91
  101. package/src/commands/automated-invoice/pause.ts +0 -29
  102. package/src/commands/automated-invoice/resume.ts +0 -29
  103. package/src/commands/automated-invoice/run-now.ts +0 -29
  104. package/src/commands/automated-invoice/suggestions.ts +0 -68
  105. package/src/commands/automated-invoice/update.ts +0 -54
  106. package/src/commands/automated-invoice/usage.ts +0 -68
  107. package/src/commands/bank/gateway-config.ts +0 -61
  108. package/src/commands/bank/index.ts +0 -244
  109. package/src/commands/bank/update-gateway.ts +0 -84
  110. package/src/commands/bank-recon/index.ts +0 -127
  111. package/src/commands/business/audit-trail.ts +0 -79
  112. package/src/commands/business/export.ts +0 -52
  113. package/src/commands/business/get.ts +0 -55
  114. package/src/commands/business/sequence.ts +0 -65
  115. package/src/commands/business/update.ts +0 -64
  116. package/src/commands/dashboard/collection-efficiency.ts +0 -164
  117. package/src/commands/dashboard/expenses.ts +0 -76
  118. package/src/commands/dashboard/invoice-breakdown.ts +0 -89
  119. package/src/commands/dashboard/monthly-comparison.ts +0 -193
  120. package/src/commands/dashboard/payment-modes.ts +0 -121
  121. package/src/commands/dashboard/profit-loss.ts +0 -146
  122. package/src/commands/dashboard/receivables-aging.ts +0 -169
  123. package/src/commands/dashboard/sales-trend.ts +0 -68
  124. package/src/commands/dashboard/summary.ts +0 -105
  125. package/src/commands/dashboard/top-customers.ts +0 -70
  126. package/src/commands/dashboard/top-items.ts +0 -74
  127. package/src/commands/dashboard/top-outstanding.ts +0 -61
  128. package/src/commands/dashboard.ts +0 -105
  129. package/src/commands/document/factory.ts +0 -590
  130. package/src/commands/einvoice/index.ts +0 -109
  131. package/src/commands/ewb/index.ts +0 -108
  132. package/src/commands/expense/categories.ts +0 -40
  133. package/src/commands/expense/create.ts +0 -51
  134. package/src/commands/expense/delete.ts +0 -45
  135. package/src/commands/expense/list.ts +0 -65
  136. package/src/commands/expense/update.ts +0 -58
  137. package/src/commands/gst/index.ts +0 -194
  138. package/src/commands/import/index.ts +0 -168
  139. package/src/commands/invoice/create.ts +0 -262
  140. package/src/commands/invoice/delete.ts +0 -44
  141. package/src/commands/invoice/get.ts +0 -113
  142. package/src/commands/invoice/list.ts +0 -126
  143. package/src/commands/invoice/pdf.ts +0 -75
  144. package/src/commands/invoice/status.ts +0 -41
  145. package/src/commands/itc/index.ts +0 -163
  146. package/src/commands/item/categories.ts +0 -40
  147. package/src/commands/item/create.ts +0 -98
  148. package/src/commands/item/delete.ts +0 -44
  149. package/src/commands/item/list.ts +0 -81
  150. package/src/commands/item/low-stock-count.ts +0 -32
  151. package/src/commands/item/merge.ts +0 -53
  152. package/src/commands/item/price-history.ts +0 -59
  153. package/src/commands/item/rename-unit.ts +0 -39
  154. package/src/commands/item/sales-stats.ts +0 -44
  155. package/src/commands/item/stock-history.ts +0 -70
  156. package/src/commands/item/stock.ts +0 -46
  157. package/src/commands/item/switch-base-unit.ts +0 -42
  158. package/src/commands/item/update.ts +0 -59
  159. package/src/commands/item/variants-create.ts +0 -58
  160. package/src/commands/item/variants-delete.ts +0 -47
  161. package/src/commands/item/variants-list.ts +0 -63
  162. package/src/commands/item/variants-update.ts +0 -61
  163. package/src/commands/journal/index.ts +0 -156
  164. package/src/commands/party/create.ts +0 -88
  165. package/src/commands/party/delete.ts +0 -44
  166. package/src/commands/party/get.ts +0 -42
  167. package/src/commands/party/ledger-report.ts +0 -81
  168. package/src/commands/party/ledger.ts +0 -63
  169. package/src/commands/party/list.ts +0 -69
  170. package/src/commands/party/merge.ts +0 -50
  171. package/src/commands/party/stats.ts +0 -40
  172. package/src/commands/party/top-items.ts +0 -57
  173. package/src/commands/party/update.ts +0 -65
  174. package/src/commands/payment/create.ts +0 -131
  175. package/src/commands/payment/default-account.ts +0 -56
  176. package/src/commands/payment/delete.ts +0 -46
  177. package/src/commands/payment/get.ts +0 -59
  178. package/src/commands/payment/list.ts +0 -66
  179. package/src/commands/payment/unpaid-invoices.ts +0 -69
  180. package/src/commands/payment/untracked.ts +0 -70
  181. package/src/commands/payment/update.ts +0 -54
  182. package/src/commands/report/index.ts +0 -736
  183. package/src/commands/session/list.ts +0 -91
  184. package/src/commands/session/revoke-all.ts +0 -20
  185. package/src/commands/session/revoke.ts +0 -32
  186. package/src/commands/shipment/index.ts +0 -170
  187. package/src/commands/store/check-slug.ts +0 -48
  188. package/src/commands/store/index.ts +0 -77
  189. package/src/commands/store/items-toggle.ts +0 -41
  190. package/src/commands/store/items.ts +0 -61
  191. package/src/commands/store/order-cancel.ts +0 -48
  192. package/src/commands/store/order-confirm.ts +0 -45
  193. package/src/commands/store/order-get.ts +0 -66
  194. package/src/commands/store/order-update.ts +0 -52
  195. package/src/commands/store/update-settings.ts +0 -52
  196. package/src/commands/target/index.ts +0 -118
  197. package/src/commands/tenant/invitations.ts +0 -62
  198. package/src/commands/tenant/invite.ts +0 -57
  199. package/src/commands/tenant/list.ts +0 -46
  200. package/src/commands/tenant/members.ts +0 -55
  201. package/src/commands/tenant/remove.ts +0 -47
  202. package/src/commands/tenant/revoke-invitation.ts +0 -32
  203. package/src/commands/tenant/update-role.ts +0 -41
  204. package/src/config.ts +0 -120
  205. package/src/error-handler.ts +0 -53
  206. package/src/format.ts +0 -181
  207. package/src/output.ts +0 -228
  208. package/src/spinner.ts +0 -39
  209. package/tsconfig.json +0 -22
  210. package/tsup.config.ts +0 -18
package/src/config.ts DELETED
@@ -1,120 +0,0 @@
1
- import Conf from "conf";
2
- import { hostname, userInfo } from "os";
3
- import { createHash } from "crypto";
4
- import { fatalError, warn } from "./output.js";
5
- import type { HisaaboClient } from "./client.js";
6
-
7
- interface ConfigSchema {
8
- apiUrl: string;
9
- token: string;
10
- tenantId: string;
11
- businessId: string;
12
- businessName: string;
13
- tokenCreatedAt: number;
14
- }
15
-
16
- /**
17
- * Derive a machine+user-specific encryption key. Prevents casual read of
18
- * the config file and stops accidental credential leaks in screenshots,
19
- * backups, or `cat` output. Not unbreakable — but the token at rest is
20
- * no longer plaintext.
21
- */
22
- function deriveEncryptionKey(): string {
23
- let uid: string;
24
- try {
25
- uid = String(userInfo().uid);
26
- } catch {
27
- uid = String(process.getuid?.() ?? process.pid);
28
- }
29
- const raw = `${uid}:${hostname()}:hisaabo-cli`;
30
- return createHash("sha256").update(raw).digest("hex");
31
- }
32
-
33
- const conf = new Conf<Partial<ConfigSchema>>({
34
- projectName: "hisaabo",
35
- projectSuffix: "",
36
- configName: "config",
37
- encryptionKey: deriveEncryptionKey(),
38
- configFileMode: 0o600, // owner read/write only — prevents credential theft on shared systems
39
- });
40
-
41
- export function getConfig(): Partial<ConfigSchema> {
42
- return conf.store;
43
- }
44
-
45
- export function setConfig(values: Partial<ConfigSchema>): void {
46
- for (const [k, v] of Object.entries(values)) {
47
- if (v !== undefined) {
48
- conf.set(k as keyof ConfigSchema, v as string);
49
- }
50
- }
51
- }
52
-
53
- export function clearConfig(): void {
54
- conf.clear();
55
- }
56
-
57
- export function isAuthenticated(): boolean {
58
- const cfg = getConfig();
59
- return !!(cfg.token && cfg.apiUrl && cfg.businessId);
60
- }
61
-
62
- export function requireAuth(): ConfigSchema {
63
- // Environment variables take priority — never persisted to disk (CI/scripts)
64
- const envToken = process.env["HISAABO_TOKEN"];
65
- const envUrl = process.env["HISAABO_API_URL"];
66
- if (envToken && envUrl) {
67
- return {
68
- apiUrl: envUrl,
69
- token: envToken,
70
- tenantId: process.env["HISAABO_TENANT_ID"] ?? "",
71
- businessId: process.env["HISAABO_BUSINESS_ID"] ?? "",
72
- businessName: process.env["HISAABO_BUSINESS_NAME"] ?? "",
73
- tokenCreatedAt: Date.now(),
74
- };
75
- }
76
-
77
- const cfg = getConfig();
78
- if (!cfg.token || !cfg.apiUrl || !cfg.businessId || !cfg.tenantId) {
79
- fatalError("Not authenticated. Run: hisaabo login", 3);
80
- }
81
-
82
- // Warn about expiring session tokens (not API keys)
83
- const isApiKey = cfg.token.startsWith("hisaabo_key_");
84
- if (!isApiKey && cfg.tokenCreatedAt) {
85
- const ageMs = Date.now() - cfg.tokenCreatedAt;
86
- const TWENTY_FIVE_DAYS = 25 * 24 * 60 * 60 * 1000;
87
- if (ageMs > TWENTY_FIVE_DAYS) {
88
- warn("Session expires soon. Run: hisaabo login");
89
- }
90
- }
91
-
92
- return cfg as ConfigSchema;
93
- }
94
-
95
- export function getConfigPath(): string {
96
- return conf.path;
97
- }
98
-
99
- /**
100
- * Check if the system is under maintenance and warn the user.
101
- * Called after requireAuth() in command handlers.
102
- * Non-fatal — prints warning and continues (the API will block tenant ops anyway).
103
- */
104
- export async function checkMaintenance(client: HisaaboClient): Promise<void> {
105
- try {
106
- const status = await client.system.maintenanceStatus();
107
- if (status.enabled) {
108
- warn(`System is under maintenance: ${status.message || "Please try again later."}`);
109
- if (status.endsAt) {
110
- const end = new Date(status.endsAt).toLocaleString();
111
- warn(`Estimated end: ${end}`);
112
- }
113
- } else if (status.startsAt && new Date(status.startsAt) > new Date()) {
114
- const start = new Date(status.startsAt).toLocaleString();
115
- warn(`Scheduled maintenance: ${start}${status.message ? ` — ${status.message}` : ""}`);
116
- }
117
- } catch {
118
- // Silently ignore — don't block CLI startup if status check fails
119
- }
120
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * Shared error handler for CLI commands.
3
- *
4
- * Extracts the repeated try-catch pattern from 100+ command files into a
5
- * single function. All tRPC error codes are handled with actionable messages
6
- * and appropriate exit codes.
7
- */
8
-
9
- import { HisaaboApiError } from "./client.js";
10
- import { fatalError, EXIT } from "./output.js";
11
- import { getConfig } from "./config.js";
12
-
13
- /**
14
- * Handle any error thrown during a CLI command. Recognizes HisaaboApiError
15
- * subtypes and exits with the correct code and message.
16
- *
17
- * Usage:
18
- * try {
19
- * await doStuff();
20
- * } catch (e) {
21
- * handleApiError(e);
22
- * }
23
- */
24
- export function handleApiError(e: unknown): never {
25
- if (e instanceof HisaaboApiError) {
26
- const err = e.hisaaboError;
27
-
28
- if (err.code === "unauthorized") {
29
- fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
30
- } else if (err.code === "forbidden") {
31
- fatalError(err.message, EXIT.FORBIDDEN);
32
- } else if (err.code === "not_found") {
33
- fatalError(err.resource, EXIT.NOT_FOUND);
34
- } else if (err.code === "validation_failed") {
35
- fatalError(e.message, EXIT.VALIDATION);
36
- } else if (err.code === "rate_limited") {
37
- fatalError(err.message, EXIT.RATE_LIMITED);
38
- } else if (err.code === "network_error") {
39
- const cfg = getConfig();
40
- const url = cfg.apiUrl ?? "unknown";
41
- fatalError(
42
- `Cannot reach ${url}\n` +
43
- ` Is the server running? Check: curl ${url}/health\n` +
44
- ` Wrong URL? Run: hisaabo login`,
45
- EXIT.NETWORK,
46
- );
47
- } else {
48
- fatalError(e.message, EXIT.GENERAL);
49
- }
50
- }
51
-
52
- fatalError(String(e instanceof Error ? e.message : e), EXIT.GENERAL);
53
- }
package/src/format.ts DELETED
@@ -1,181 +0,0 @@
1
- import chalk from "chalk";
2
- import { hasColor } from "./output.js";
3
-
4
- // ── INR formatting ─────────────────────────────────────────────────────────
5
-
6
- /**
7
- * Format a decimal string as Indian-locale currency with ₹ symbol.
8
- * Uses en-IN grouping (lakh/crore system).
9
- */
10
- export function formatINR(amount: string | number): string {
11
- const num = typeof amount === "string" ? parseFloat(amount) : amount;
12
- if (isNaN(num)) return "0.00";
13
- const abs = Math.abs(num);
14
- const formatted = new Intl.NumberFormat("en-IN", {
15
- minimumFractionDigits: 2,
16
- maximumFractionDigits: 2,
17
- }).format(abs);
18
- return (num < 0 ? "-" : "") + "₹" + formatted;
19
- }
20
-
21
- /**
22
- * Format for table cells — no ₹ symbol (column header has it).
23
- */
24
- export function formatAmount(amount: string | number): string {
25
- const num = typeof amount === "string" ? parseFloat(amount) : amount;
26
- if (isNaN(num)) return "0.00";
27
- const abs = Math.abs(num);
28
- const formatted = new Intl.NumberFormat("en-IN", {
29
- minimumFractionDigits: 2,
30
- maximumFractionDigits: 2,
31
- }).format(abs);
32
- return (num < 0 ? "-" : "") + formatted;
33
- }
34
-
35
- // ── Date formatting ────────────────────────────────────────────────────────
36
-
37
- const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
38
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
39
-
40
- /**
41
- * Format ISO date string as "dd MMM yyyy" (en-IN style).
42
- */
43
- export function formatDate(date: string | null | undefined): string {
44
- if (!date) return "-";
45
- try {
46
- const d = new Date(date);
47
- if (isNaN(d.getTime())) return date;
48
- const day = String(d.getDate()).padStart(2, "0");
49
- const month = MONTHS[d.getMonth()];
50
- const year = d.getFullYear();
51
- return `${day} ${month} ${year}`;
52
- } catch {
53
- return date;
54
- }
55
- }
56
-
57
- /**
58
- * Relative date — "Today", "Yesterday", "2d ago", etc.
59
- */
60
- export function formatRelativeDate(date: string | null | undefined): string {
61
- if (!date) return "-";
62
- try {
63
- const d = new Date(date);
64
- const now = new Date();
65
- const diff = Math.floor((now.getTime() - d.getTime()) / (1000 * 60 * 60 * 24));
66
- if (diff === 0) return "Today";
67
- if (diff === 1) return "Yesterday";
68
- if (diff < 30) return `${diff}d ago`;
69
- if (diff < 365) return `${Math.floor(diff / 30)}mo ago`;
70
- return `${Math.floor(diff / 365)}y ago`;
71
- } catch {
72
- return date ?? "-";
73
- }
74
- }
75
-
76
- // ── Status badges ──────────────────────────────────────────────────────────
77
-
78
- const STATUS_CONFIG: Record<string, { label: string; color: (s: string) => string }> = {
79
- paid: { label: "PAID", color: (s) => chalk.green(s) },
80
- sent: { label: "SENT", color: (s) => chalk.blue(s) },
81
- draft: { label: "DRAFT", color: (s) => chalk.dim(s) },
82
- partial: { label: "PARTIAL", color: (s) => chalk.yellow(s) },
83
- overdue: { label: "OVERDUE", color: (s) => chalk.red(s) },
84
- cancelled: { label: "CANCEL", color: (s) => chalk.dim(chalk.strikethrough(s)) },
85
- adjusted: { label: "ADJUST", color: (s) => chalk.magenta(s) },
86
- unfulfilled: { label: "UNFUL", color: (s) => chalk.blue(s) },
87
- pending: { label: "PEND", color: (s) => chalk.yellow(s) },
88
- confirmed: { label: "CONF", color: (s) => chalk.blue(s) },
89
- delivered: { label: "DELIV", color: (s) => chalk.green(s) },
90
- shipped: { label: "SHIPPED", color: (s) => chalk.blue(s) },
91
- in_transit: { label: "TRANSIT", color: (s) => chalk.cyan(s) },
92
- returned: { label: "RETURN", color: (s) => chalk.red(s) },
93
- preparing: { label: "PREP", color: (s) => chalk.yellow(s) },
94
- ready: { label: "READY", color: (s) => chalk.cyan(s) },
95
- };
96
-
97
- export function formatStatus(status: string): string {
98
- const cfg = STATUS_CONFIG[status.toLowerCase()];
99
- const label = cfg ? `[${cfg.label}]` : `[${status.toUpperCase()}]`;
100
- if (!hasColor() || !cfg) return label;
101
- return cfg.color(label);
102
- }
103
-
104
- // ── Financial year ─────────────────────────────────────────────────────────
105
-
106
- /**
107
- * Current FY string, e.g. "2025-26". Assumes FY starts April 1.
108
- */
109
- export function currentFY(): string {
110
- const now = new Date();
111
- const year = now.getFullYear();
112
- const month = now.getMonth() + 1; // 1-indexed
113
- if (month >= 4) {
114
- return `${year}-${String(year + 1).slice(2)}`;
115
- }
116
- return `${year - 1}-${String(year).slice(2)}`;
117
- }
118
-
119
- /**
120
- * FY start date as ISO string (April 1 of current FY).
121
- */
122
- export function fyStart(): string {
123
- const now = new Date();
124
- const year = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
125
- return `${year}-04-01`;
126
- }
127
-
128
- /**
129
- * Today as ISO date string.
130
- */
131
- export function todayISO(): string {
132
- return new Date().toISOString().split("T")[0] ?? "";
133
- }
134
-
135
- /**
136
- * First day of current month.
137
- */
138
- export function monthStart(): string {
139
- const now = new Date();
140
- return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`;
141
- }
142
-
143
- /**
144
- * Last day of current month.
145
- */
146
- export function monthEnd(): string {
147
- const now = new Date();
148
- const last = new Date(now.getFullYear(), now.getMonth() + 1, 0);
149
- return `${last.getFullYear()}-${String(last.getMonth() + 1).padStart(2, "0")}-${String(last.getDate()).padStart(2, "0")}`;
150
- }
151
-
152
- /**
153
- * Quarter start/end for a quarter string like "Q1", "Q2", "Q3", "Q4".
154
- * Q1 = Apr-Jun, Q2 = Jul-Sep, Q3 = Oct-Dec, Q4 = Jan-Mar
155
- */
156
- export function quarterRange(q: string): { from: string; to: string; month: number; year: number } {
157
- const now = new Date();
158
- const fyYear = now.getMonth() + 1 >= 4 ? now.getFullYear() : now.getFullYear() - 1;
159
-
160
- const ranges: Record<string, { from: string; to: string; month: number; year: number }> = {
161
- Q1: { from: `${fyYear}-04-01`, to: `${fyYear}-06-30`, month: 4, year: fyYear },
162
- Q2: { from: `${fyYear}-07-01`, to: `${fyYear}-09-30`, month: 7, year: fyYear },
163
- Q3: { from: `${fyYear}-10-01`, to: `${fyYear}-12-31`, month: 10, year: fyYear },
164
- Q4: { from: `${fyYear + 1}-01-01`, to: `${fyYear + 1}-03-31`, month: 1, year: fyYear + 1 },
165
- };
166
-
167
- const upper = q.toUpperCase();
168
- return ranges[upper] ?? ranges["Q1"]!;
169
- }
170
-
171
- export function deliveryMethodLabel(method: string): string {
172
- const map: Record<string, string> = {
173
- self_pickup: "Self Pickup",
174
- hand_delivery: "Hand Delivery",
175
- courier: "Courier",
176
- bus: "Bus",
177
- transport: "Transport",
178
- post: "Post",
179
- };
180
- return map[method] ?? method;
181
- }
package/src/output.ts DELETED
@@ -1,228 +0,0 @@
1
- import chalk from "chalk";
2
-
3
- // ── Environment detection ──────────────────────────────────────────────────
4
-
5
- export function isInteractive(): boolean {
6
- return process.stdout.isTTY === true;
7
- }
8
-
9
- export function hasColor(): boolean {
10
- if (process.env["NO_COLOR"] !== undefined) return false;
11
- if (process.env["FORCE_COLOR"] === "0") return false;
12
- return process.stdout.hasColors?.() ?? isInteractive();
13
- }
14
-
15
- // ── Strip ANSI ─────────────────────────────────────────────────────────────
16
-
17
- export function stripAnsi(str: string): string {
18
- // eslint-disable-next-line no-control-regex
19
- return str.replace(/\x1b\[[0-9;]*m/g, "");
20
- }
21
-
22
- // ── Terminal width tiers ──────────────────────────────────────────────────
23
-
24
- export type WidthTier = "narrow" | "standard" | "wide";
25
-
26
- export function getWidthTier(): WidthTier {
27
- const w = process.stdout.columns ?? 80;
28
- if (w < 80) return "narrow";
29
- if (w <= 120) return "standard";
30
- return "wide";
31
- }
32
-
33
- export function termWidth(): number {
34
- return process.stdout.columns ?? 80;
35
- }
36
-
37
- // ── Exit codes ────────────────────────────────────────────────────────────
38
-
39
- export const EXIT = {
40
- SUCCESS: 0,
41
- GENERAL: 1,
42
- USAGE: 2,
43
- AUTH: 3,
44
- FORBIDDEN: 4,
45
- NOT_FOUND: 5,
46
- VALIDATION: 6,
47
- NETWORK: 7,
48
- CONFLICT: 8,
49
- RATE_LIMITED: 9,
50
- } as const;
51
-
52
- // ── Output helpers ────────────────────────────────────────────────────────
53
-
54
- export function fatalError(message: string, code = 1): never {
55
- if (hasColor()) {
56
- process.stderr.write(chalk.red("Error: ") + message + "\n");
57
- } else {
58
- process.stderr.write("Error: " + message + "\n");
59
- }
60
- process.exit(code);
61
- }
62
-
63
- export function success(message: string): void {
64
- if (hasColor()) {
65
- process.stdout.write(chalk.green("✓ ") + message + "\n");
66
- } else {
67
- process.stdout.write("OK: " + message + "\n");
68
- }
69
- }
70
-
71
- export function warn(message: string): void {
72
- if (hasColor()) {
73
- process.stderr.write(chalk.yellow("Warning: ") + message + "\n");
74
- } else {
75
- process.stderr.write("Warning: " + message + "\n");
76
- }
77
- }
78
-
79
- // ── JSON output ───────────────────────────────────────────────────────────
80
-
81
- export function outputJSON(data: unknown): void {
82
- process.stdout.write(JSON.stringify(data, null, 2) + "\n");
83
- }
84
-
85
- // ── Table output ──────────────────────────────────────────────────────────
86
-
87
- export interface ColumnDef<T extends object> {
88
- key: keyof T | string;
89
- header: string;
90
- width?: number;
91
- align?: "left" | "right";
92
- format?: (value: unknown, row: T) => string;
93
- }
94
-
95
- function getNestedValue(obj: object, key: string): unknown {
96
- const parts = key.split(".");
97
- let cur: unknown = obj;
98
- for (const part of parts) {
99
- if (cur == null || typeof cur !== "object") return undefined;
100
- cur = (cur as Record<string, unknown>)[part];
101
- }
102
- return cur;
103
- }
104
-
105
- function padEnd(str: string, len: number): string {
106
- const visual = stripAnsi(str).length;
107
- const pad = Math.max(0, len - visual);
108
- return str + " ".repeat(pad);
109
- }
110
-
111
- function padStart(str: string, len: number): string {
112
- const visual = stripAnsi(str).length;
113
- const pad = Math.max(0, len - visual);
114
- return " ".repeat(pad) + str;
115
- }
116
-
117
- export function outputTable<T extends object>(rows: T[], columns: ColumnDef<T>[]): void {
118
- if (rows.length === 0) {
119
- process.stdout.write(" (no results)\n");
120
- return;
121
- }
122
-
123
- // Compute column widths
124
- const widths = columns.map((col) => {
125
- let max = stripAnsi(col.header).length;
126
- for (const row of rows) {
127
- const val = col.format
128
- ? col.format(getNestedValue(row, col.key as string), row)
129
- : String(getNestedValue(row, col.key as string) ?? "");
130
- const vis = stripAnsi(val).length;
131
- if (vis > max) max = vis;
132
- }
133
- if (col.width) max = Math.min(max, col.width);
134
- return max;
135
- });
136
-
137
- const sep = "─".repeat(widths.reduce((s, w) => s + w + 2, 1));
138
-
139
- // Header
140
- let header = " ";
141
- for (let i = 0; i < columns.length; i++) {
142
- const col = columns[i];
143
- const h = col.align === "right"
144
- ? padStart(col.header, widths[i])
145
- : padEnd(col.header, widths[i]);
146
- header += (hasColor() ? chalk.dim(h) : h) + " ";
147
- }
148
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
149
- process.stdout.write(header.trimEnd() + "\n");
150
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
151
-
152
- // Rows
153
- for (const row of rows) {
154
- let line = " ";
155
- for (let i = 0; i < columns.length; i++) {
156
- const col = columns[i];
157
- let val = col.format
158
- ? col.format(getNestedValue(row, col.key as string), row)
159
- : String(getNestedValue(row, col.key as string) ?? "");
160
- // Truncate if needed
161
- const vis = stripAnsi(val).length;
162
- if (col.width && vis > col.width) {
163
- val = val.slice(0, col.width - 1) + "…";
164
- }
165
- const cell = col.align === "right"
166
- ? padStart(val, widths[i])
167
- : padEnd(val, widths[i]);
168
- line += cell + " ";
169
- }
170
- process.stdout.write(line.trimEnd() + "\n");
171
- }
172
-
173
- process.stdout.write(" " + (hasColor() ? chalk.dim(sep) : sep) + "\n");
174
- }
175
-
176
- // ── TSV output ────────────────────────────────────────────────────────────
177
-
178
- export function outputTSV<T extends object>(rows: T[], columns: ColumnDef<T>[]): void {
179
- process.stdout.write(columns.map((c) => c.header).join("\t") + "\n");
180
- for (const row of rows) {
181
- const line = columns.map((col) => {
182
- const val = col.format
183
- ? col.format(getNestedValue(row, col.key as string), row)
184
- : String(getNestedValue(row, col.key as string) ?? "");
185
- return stripAnsi(val).replace(/\t/g, " ");
186
- });
187
- process.stdout.write(line.join("\t") + "\n");
188
- }
189
- }
190
-
191
- // ── CSV output ────────────────────────────────────────────────────────────
192
-
193
- function csvEscape(val: string): string {
194
- if (val.includes(",") || val.includes('"') || val.includes("\n")) {
195
- return `"${val.replace(/"/g, '""')}"`;
196
- }
197
- return val;
198
- }
199
-
200
- export function outputCSV<T extends object>(rows: T[], columns: ColumnDef<T>[]): void {
201
- process.stdout.write(columns.map((c) => csvEscape(c.header)).join(",") + "\n");
202
- for (const row of rows) {
203
- const line = columns.map((col) => {
204
- const val = col.format
205
- ? col.format(getNestedValue(row, col.key as string), row)
206
- : String(getNestedValue(row, col.key as string) ?? "");
207
- return csvEscape(stripAnsi(val));
208
- });
209
- process.stdout.write(line.join(",") + "\n");
210
- }
211
- }
212
-
213
- // ── ID-only output ────────────────────────────────────────────────────────
214
-
215
- export function outputIds(ids: string[]): void {
216
- for (const id of ids) {
217
- process.stdout.write(id + "\n");
218
- }
219
- }
220
-
221
- // ── Pagination footer ─────────────────────────────────────────────────────
222
-
223
- export function paginationFooter(page: number, limit: number, total: number): void {
224
- const from = (page - 1) * limit + 1;
225
- const to = Math.min(page * limit, total);
226
- const msg = ` Showing ${from}-${to} of ${total}`;
227
- process.stdout.write("\n" + (hasColor() ? chalk.dim(msg) : msg) + "\n");
228
- }
package/src/spinner.ts DELETED
@@ -1,39 +0,0 @@
1
- /**
2
- * Spinner utility for long-running CLI operations.
3
- *
4
- * Uses a simple ANSI spinner that works cross-platform. No external deps
5
- * needed — just stdout.write with cursor control.
6
- */
7
-
8
- const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
9
- const INTERVAL = 80;
10
-
11
- /**
12
- * Run an async function with a terminal spinner. The spinner is only shown
13
- * when stdout is a TTY (skipped in pipes/CI).
14
- *
15
- * Usage:
16
- * const result = await withSpinner("Loading invoices...", () => client.invoice.list(input));
17
- */
18
- export async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {
19
- // No spinner in non-interactive environments
20
- if (!process.stdout.isTTY) return fn();
21
-
22
- let frame = 0;
23
- const timer = setInterval(() => {
24
- const spinner = FRAMES[frame % FRAMES.length];
25
- process.stdout.write(`\r ${spinner} ${label}`);
26
- frame++;
27
- }, INTERVAL);
28
-
29
- try {
30
- const result = await fn();
31
- clearInterval(timer);
32
- process.stdout.write(`\r${" ".repeat(label.length + 6)}\r`); // clear spinner line
33
- return result;
34
- } catch (err) {
35
- clearInterval(timer);
36
- process.stdout.write(`\r${" ".repeat(label.length + 6)}\r`);
37
- throw err;
38
- }
39
- }
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "NodeNext",
5
- "moduleResolution": "NodeNext",
6
- "jsx": "react-jsx",
7
- "strict": true,
8
- "skipLibCheck": true,
9
- "outDir": "dist",
10
- "rootDir": "src",
11
- "declaration": true,
12
- "declarationMap": true,
13
- "sourceMap": true,
14
- "resolveJsonModule": true,
15
- "esModuleInterop": true,
16
- "forceConsistentCasingInFileNames": true,
17
- "paths": {
18
- "@/*": ["./src/*"]
19
- }
20
- },
21
- "include": ["src"]
22
- }
package/tsup.config.ts DELETED
@@ -1,18 +0,0 @@
1
- import { defineConfig } from "tsup";
2
- import { readFileSync } from "fs";
3
-
4
- const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf-8"));
5
-
6
- export default defineConfig({
7
- entry: ["src/bin/hisaabo.ts"],
8
- format: ["esm"],
9
- target: "node20",
10
- banner: {
11
- js: "#!/usr/bin/env node",
12
- },
13
- define: {
14
- __CLI_VERSION__: JSON.stringify(pkg.version),
15
- },
16
- outDir: "dist/bin",
17
- clean: true,
18
- });