@hisaabo/cli 0.1.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.
- package/.turbo/turbo-build.log +13 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/CLI-UX-ARCHITECTURE.md +1269 -0
- package/dist/bin/hisaabo.js +3516 -0
- package/package.json +34 -0
- package/src/auth.ts +212 -0
- package/src/bin/hisaabo.ts +950 -0
- package/src/client.ts +1229 -0
- package/src/commands/bank/index.ts +244 -0
- package/src/commands/dashboard.ts +105 -0
- package/src/commands/expense/create.ts +51 -0
- package/src/commands/expense/delete.ts +45 -0
- package/src/commands/expense/list.ts +65 -0
- package/src/commands/gst/index.ts +116 -0
- package/src/commands/import/index.ts +100 -0
- package/src/commands/invoice/create.ts +262 -0
- package/src/commands/invoice/delete.ts +44 -0
- package/src/commands/invoice/get.ts +105 -0
- package/src/commands/invoice/list.ts +126 -0
- package/src/commands/invoice/pdf.ts +75 -0
- package/src/commands/invoice/status.ts +41 -0
- package/src/commands/item/create.ts +98 -0
- package/src/commands/item/delete.ts +44 -0
- package/src/commands/item/list.ts +81 -0
- package/src/commands/item/stock.ts +46 -0
- package/src/commands/party/create.ts +88 -0
- package/src/commands/party/delete.ts +44 -0
- package/src/commands/party/get.ts +42 -0
- package/src/commands/party/ledger.ts +63 -0
- package/src/commands/party/list.ts +69 -0
- package/src/commands/payment/create.ts +133 -0
- package/src/commands/payment/delete.ts +46 -0
- package/src/commands/payment/list.ts +66 -0
- package/src/commands/report/index.ts +218 -0
- package/src/commands/shipment/index.ts +170 -0
- package/src/commands/store/index.ts +77 -0
- package/src/commands/target/index.ts +118 -0
- package/src/components/ErrorDisplay.tsx +16 -0
- package/src/components/Header.tsx +26 -0
- package/src/components/MoneyCell.tsx +16 -0
- package/src/components/Spinner.tsx +12 -0
- package/src/components/StatusBadge.tsx +39 -0
- package/src/components/Table.tsx +63 -0
- package/src/config.ts +47 -0
- package/src/format.ts +180 -0
- package/src/output.ts +227 -0
- package/tsconfig.json +22 -0
- package/tsup.config.ts +13 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { HisaaboClient, HisaaboApiError } from "../../client.js";
|
|
4
|
+
import { requireAuth } from "../../config.js";
|
|
5
|
+
import { fatalError, outputJSON, EXIT, success, warn } from "../../output.js";
|
|
6
|
+
|
|
7
|
+
function readJsonFile(filePath: string): unknown[] {
|
|
8
|
+
const abs = path.resolve(filePath);
|
|
9
|
+
if (!fs.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
|
|
10
|
+
const raw = fs.readFileSync(abs, "utf-8");
|
|
11
|
+
try {
|
|
12
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
13
|
+
if (!Array.isArray(parsed)) fatalError("Expected a JSON array", EXIT.USAGE);
|
|
14
|
+
return parsed as unknown[];
|
|
15
|
+
} catch {
|
|
16
|
+
fatalError(`Invalid JSON in file: ${abs}`, EXIT.USAGE);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function readCsvFile(filePath: string): Array<Record<string, string>> {
|
|
21
|
+
const abs = path.resolve(filePath);
|
|
22
|
+
if (!fs.existsSync(abs)) fatalError(`File not found: ${abs}`, EXIT.NOT_FOUND);
|
|
23
|
+
const lines = fs.readFileSync(abs, "utf-8").split("\n").filter((l) => l.trim());
|
|
24
|
+
if (lines.length < 2) fatalError("CSV must have at least a header row and one data row", EXIT.USAGE);
|
|
25
|
+
const headers = (lines[0] ?? "").split(",").map((h) => h.trim().replace(/^"|"$/g, ""));
|
|
26
|
+
return lines.slice(1).map((line) => {
|
|
27
|
+
const vals = line.split(",").map((v) => v.trim().replace(/^"|"$/g, ""));
|
|
28
|
+
const obj: Record<string, string> = {};
|
|
29
|
+
headers.forEach((h, i) => { obj[h] = vals[i] ?? ""; });
|
|
30
|
+
return obj;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function importPartiesCommand(filePath: string, opts: { json?: boolean; format?: string }): Promise<void> {
|
|
35
|
+
const cfg = requireAuth();
|
|
36
|
+
const client = new HisaaboClient(cfg);
|
|
37
|
+
|
|
38
|
+
const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
|
|
39
|
+
const data = fmt === "csv"
|
|
40
|
+
? readCsvFile(filePath)
|
|
41
|
+
: readJsonFile(filePath) as Array<Record<string, unknown>>;
|
|
42
|
+
|
|
43
|
+
console.log(` Importing ${data.length} parties...`);
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
const result = await client.import.importParties({ parties: data as Array<Record<string, unknown>> });
|
|
47
|
+
|
|
48
|
+
if (opts.json) {
|
|
49
|
+
outputJSON(result);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
success(`Imported: ${result.imported} parties`);
|
|
54
|
+
if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
|
|
55
|
+
result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
|
|
56
|
+
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if (e instanceof HisaaboApiError) {
|
|
59
|
+
const err = e.hisaaboError;
|
|
60
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
61
|
+
if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
|
|
62
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
63
|
+
}
|
|
64
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function importItemsCommand(filePath: string, opts: { json?: boolean; format?: string }): Promise<void> {
|
|
69
|
+
const cfg = requireAuth();
|
|
70
|
+
const client = new HisaaboClient(cfg);
|
|
71
|
+
|
|
72
|
+
const fmt = opts.format ?? (filePath.endsWith(".csv") ? "csv" : "json");
|
|
73
|
+
const data = fmt === "csv"
|
|
74
|
+
? readCsvFile(filePath)
|
|
75
|
+
: readJsonFile(filePath) as Array<Record<string, unknown>>;
|
|
76
|
+
|
|
77
|
+
console.log(` Importing ${data.length} items...`);
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const result = await client.import.importItems({ items: data as Array<Record<string, unknown>> });
|
|
81
|
+
|
|
82
|
+
if (opts.json) {
|
|
83
|
+
outputJSON(result);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
success(`Imported: ${result.imported} items`);
|
|
88
|
+
if (result.skipped > 0) warn(`Skipped: ${result.skipped}`);
|
|
89
|
+
result.errors.forEach((e) => console.error(` Row ${e.row}: ${e.message}`));
|
|
90
|
+
|
|
91
|
+
} catch (e) {
|
|
92
|
+
if (e instanceof HisaaboApiError) {
|
|
93
|
+
const err = e.hisaaboError;
|
|
94
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
95
|
+
if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
|
|
96
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
97
|
+
}
|
|
98
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import * as readline from "readline";
|
|
2
|
+
import { HisaaboClient, HisaaboApiError, type InvoiceLineItemInput } from "../../client.js";
|
|
3
|
+
import { requireAuth } from "../../config.js";
|
|
4
|
+
import { fatalError, outputJSON, EXIT, success } from "../../output.js";
|
|
5
|
+
import { formatAmount, formatINR, todayISO } from "../../format.js";
|
|
6
|
+
|
|
7
|
+
interface CreateOpts {
|
|
8
|
+
json?: boolean;
|
|
9
|
+
party?: string;
|
|
10
|
+
partyId?: string;
|
|
11
|
+
type?: string;
|
|
12
|
+
items?: string[];
|
|
13
|
+
qty?: string[];
|
|
14
|
+
rate?: string[];
|
|
15
|
+
delivery?: string;
|
|
16
|
+
notes?: string;
|
|
17
|
+
terms?: string;
|
|
18
|
+
yes?: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function prompt(rl: readline.Interface, question: string): Promise<string> {
|
|
22
|
+
return new Promise((resolve) => rl.question(question, resolve));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function invoiceCreateCommand(opts: CreateOpts): Promise<void> {
|
|
26
|
+
const cfg = requireAuth();
|
|
27
|
+
const client = new HisaaboClient(cfg);
|
|
28
|
+
|
|
29
|
+
const isNonInteractive = !process.stdin.isTTY || opts.yes;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// ── Determine type ──────────────────────────────────────────────
|
|
33
|
+
let invoiceType: "sale" | "purchase" = "sale";
|
|
34
|
+
if (opts.type === "purchase") invoiceType = "purchase";
|
|
35
|
+
|
|
36
|
+
// ── Resolve party ───────────────────────────────────────────────
|
|
37
|
+
let partyId = opts.partyId;
|
|
38
|
+
let partyName = opts.party ?? "";
|
|
39
|
+
|
|
40
|
+
if (!partyId) {
|
|
41
|
+
if (!isNonInteractive) {
|
|
42
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
43
|
+
console.log(`\n New ${invoiceType === "sale" ? "Sale Invoice" : "Purchase Bill"}`);
|
|
44
|
+
console.log(" " + "─".repeat(40) + "\n");
|
|
45
|
+
|
|
46
|
+
const search = await prompt(rl, " Select Party:\n > Search: ");
|
|
47
|
+
const parties = await client.party.list({ search: search.trim(), limit: 5 });
|
|
48
|
+
|
|
49
|
+
if (parties.data.length === 0) {
|
|
50
|
+
rl.close();
|
|
51
|
+
fatalError("No parties found. Create one with: hisaabo party create", EXIT.NOT_FOUND);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
parties.data.forEach((p, i) => {
|
|
55
|
+
console.log(` ${i + 1} ${p.name.padEnd(20)} ${(p.phone ?? "").padEnd(14)} ${p.type}`);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const partyChoice = await prompt(rl, "\n Party [1]: ");
|
|
59
|
+
const idx = parseInt(partyChoice.trim() || "1", 10) - 1;
|
|
60
|
+
const selected = parties.data[Math.max(0, Math.min(idx, parties.data.length - 1))];
|
|
61
|
+
if (!selected) { rl.close(); fatalError("Invalid selection.", EXIT.USAGE); }
|
|
62
|
+
partyId = selected.id;
|
|
63
|
+
partyName = selected.name;
|
|
64
|
+
console.log(` Party: ${partyName}\n`);
|
|
65
|
+
rl.close();
|
|
66
|
+
} else {
|
|
67
|
+
// Non-interactive: search by name
|
|
68
|
+
if (!partyName) fatalError("--party or --party-id is required", EXIT.USAGE);
|
|
69
|
+
const parties = await client.party.list({ search: partyName, limit: 5 });
|
|
70
|
+
if (parties.data.length === 0) fatalError(`Party not found: ${partyName}`, EXIT.NOT_FOUND);
|
|
71
|
+
partyId = parties.data[0]!.id;
|
|
72
|
+
partyName = parties.data[0]!.name;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ── Build line items ────────────────────────────────────────────
|
|
77
|
+
const lineItems: InvoiceLineItemInput[] = [];
|
|
78
|
+
|
|
79
|
+
if (opts.items && opts.items.length > 0) {
|
|
80
|
+
// Flag-based item creation
|
|
81
|
+
for (let i = 0; i < opts.items.length; i++) {
|
|
82
|
+
const itemName = opts.items[i]!;
|
|
83
|
+
const qty = opts.qty?.[i] ?? "1";
|
|
84
|
+
let unitPrice = opts.rate?.[i] ?? "";
|
|
85
|
+
|
|
86
|
+
if (!unitPrice) {
|
|
87
|
+
// Try to find the item and use its sale price
|
|
88
|
+
const items = await client.item.list({ search: itemName, limit: 3 });
|
|
89
|
+
if (items.data.length > 0 && items.data[0]?.salePrice) {
|
|
90
|
+
unitPrice = items.data[0].salePrice;
|
|
91
|
+
lineItems.push({
|
|
92
|
+
itemId: items.data[0].id,
|
|
93
|
+
description: items.data[0].name,
|
|
94
|
+
quantity: qty,
|
|
95
|
+
unitPrice,
|
|
96
|
+
taxPercent: items.data[0].taxPercent,
|
|
97
|
+
});
|
|
98
|
+
} else {
|
|
99
|
+
fatalError(`Item not found or has no price: ${itemName}. Use --rate to specify price.`, EXIT.NOT_FOUND);
|
|
100
|
+
}
|
|
101
|
+
} else {
|
|
102
|
+
// Try to find item by name for linking
|
|
103
|
+
const items = await client.item.list({ search: itemName, limit: 3 });
|
|
104
|
+
const matched = items.data.find((it) => it.name.toLowerCase().includes(itemName.toLowerCase()));
|
|
105
|
+
if (matched) {
|
|
106
|
+
lineItems.push({
|
|
107
|
+
itemId: matched.id,
|
|
108
|
+
description: matched.name,
|
|
109
|
+
quantity: qty,
|
|
110
|
+
unitPrice,
|
|
111
|
+
taxPercent: matched.taxPercent,
|
|
112
|
+
});
|
|
113
|
+
} else {
|
|
114
|
+
lineItems.push({ description: itemName, quantity: qty, unitPrice });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} else if (!isNonInteractive) {
|
|
119
|
+
// Interactive item wizard
|
|
120
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
121
|
+
console.log(" Add Line Items (empty description to finish):\n");
|
|
122
|
+
let itemNum = 1;
|
|
123
|
+
|
|
124
|
+
while (true) {
|
|
125
|
+
console.log(` Item ${itemNum}:`);
|
|
126
|
+
const search = await prompt(rl, " Search item (or description): ");
|
|
127
|
+
if (!search.trim()) break;
|
|
128
|
+
|
|
129
|
+
let description = search.trim();
|
|
130
|
+
let itemId: string | undefined;
|
|
131
|
+
let defaultPrice = "";
|
|
132
|
+
let defaultTax = "0";
|
|
133
|
+
|
|
134
|
+
// Search for items
|
|
135
|
+
const items = await client.item.list({ search: search.trim(), limit: 5 });
|
|
136
|
+
if (items.data.length > 0) {
|
|
137
|
+
items.data.forEach((it, i) => {
|
|
138
|
+
const stock = it.itemType === "service" ? "-" : String(it.stockQuantity);
|
|
139
|
+
const price = it.salePrice ? formatINR(it.salePrice) : "no price";
|
|
140
|
+
console.log(` ${i + 1} ${it.name.padEnd(20)} ${price.padEnd(12)} Stock: ${stock}`);
|
|
141
|
+
});
|
|
142
|
+
const choice = await prompt(rl, " Item [1] (or 0 to use as description): ");
|
|
143
|
+
const idx = parseInt(choice.trim() || "1", 10);
|
|
144
|
+
if (idx > 0) {
|
|
145
|
+
const selected = items.data[idx - 1];
|
|
146
|
+
if (selected) {
|
|
147
|
+
itemId = selected.id;
|
|
148
|
+
description = selected.name;
|
|
149
|
+
defaultPrice = selected.salePrice ?? "";
|
|
150
|
+
defaultTax = selected.taxPercent;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const qtyStr = await prompt(rl, " Quantity [1]: ");
|
|
156
|
+
const qty = qtyStr.trim() || "1";
|
|
157
|
+
|
|
158
|
+
const rateStr = await prompt(rl, ` Unit Price [${defaultPrice || "0.00"}]: `);
|
|
159
|
+
const unitPrice = rateStr.trim() || defaultPrice || "0.00";
|
|
160
|
+
|
|
161
|
+
const taxStr = await prompt(rl, ` Tax % [${defaultTax}]: `);
|
|
162
|
+
const taxPercent = taxStr.trim() || defaultTax;
|
|
163
|
+
|
|
164
|
+
const discStr = await prompt(rl, " Discount % [0]: ");
|
|
165
|
+
const discountPercent = discStr.trim() || "0";
|
|
166
|
+
|
|
167
|
+
const amount = parseFloat(qty) * parseFloat(unitPrice) * (1 + parseFloat(taxPercent) / 100) * (1 - parseFloat(discountPercent) / 100);
|
|
168
|
+
console.log(` > ${description} x${qty} @${formatAmount(unitPrice)} ${taxPercent}% tax = ${formatAmount(String(amount))}\n`);
|
|
169
|
+
|
|
170
|
+
lineItems.push({ itemId, description, quantity: qty, unitPrice, taxPercent, discountPercent });
|
|
171
|
+
itemNum++;
|
|
172
|
+
}
|
|
173
|
+
rl.close();
|
|
174
|
+
|
|
175
|
+
if (lineItems.length === 0) {
|
|
176
|
+
fatalError("No line items added.", EXIT.USAGE);
|
|
177
|
+
}
|
|
178
|
+
} else {
|
|
179
|
+
fatalError("No items specified. Use --item flags.", EXIT.USAGE);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ── Summary & confirm ───────────────────────────────────────────
|
|
183
|
+
const subtotal = lineItems.reduce((s, item) => {
|
|
184
|
+
const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
|
|
185
|
+
return s + amt;
|
|
186
|
+
}, 0);
|
|
187
|
+
const taxTotal = lineItems.reduce((s, item) => {
|
|
188
|
+
const amt = parseFloat(item.quantity) * parseFloat(item.unitPrice);
|
|
189
|
+
const tax = parseFloat(item.taxPercent ?? "0") / 100;
|
|
190
|
+
return s + amt * tax;
|
|
191
|
+
}, 0);
|
|
192
|
+
|
|
193
|
+
let invoiceDate = todayISO();
|
|
194
|
+
let dueDate: string | undefined;
|
|
195
|
+
let deliveryMethod = opts.delivery;
|
|
196
|
+
let notes = opts.notes;
|
|
197
|
+
let terms = opts.terms;
|
|
198
|
+
|
|
199
|
+
if (!isNonInteractive) {
|
|
200
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
201
|
+
console.log("\n ─── Invoice Summary ───────────────────────────");
|
|
202
|
+
console.log(` Subtotal: ${formatAmount(String(subtotal))}`);
|
|
203
|
+
console.log(` Tax: ${formatAmount(String(taxTotal))}`);
|
|
204
|
+
console.log(` Total: ${formatAmount(String(subtotal + taxTotal))}`);
|
|
205
|
+
console.log(" ───────────────────────────────────────────────\n");
|
|
206
|
+
|
|
207
|
+
const dateStr = await prompt(rl, ` Invoice Date [${todayISO()}]: `);
|
|
208
|
+
if (dateStr.trim()) invoiceDate = dateStr.trim();
|
|
209
|
+
|
|
210
|
+
const dueStr = await prompt(rl, " Due Date [optional]: ");
|
|
211
|
+
if (dueStr.trim()) dueDate = dueStr.trim();
|
|
212
|
+
|
|
213
|
+
const delivStr = await prompt(rl, " Delivery Method [self_pickup]: ");
|
|
214
|
+
deliveryMethod = delivStr.trim() || "self_pickup";
|
|
215
|
+
|
|
216
|
+
const notesStr = await prompt(rl, " Notes: ");
|
|
217
|
+
if (notesStr.trim()) notes = notesStr.trim();
|
|
218
|
+
|
|
219
|
+
const termsStr = await prompt(rl, " Terms: ");
|
|
220
|
+
if (termsStr.trim()) terms = termsStr.trim();
|
|
221
|
+
|
|
222
|
+
console.log(" ───────────────────────────────────────────────");
|
|
223
|
+
const confirm = await prompt(rl, "\n Create this invoice? (y/n) [y]: ");
|
|
224
|
+
rl.close();
|
|
225
|
+
|
|
226
|
+
if (confirm.trim().toLowerCase() === "n") {
|
|
227
|
+
console.log(" Cancelled.");
|
|
228
|
+
process.exit(EXIT.SUCCESS);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ── Create ──────────────────────────────────────────────────────
|
|
233
|
+
const invoice = await client.invoice.create({
|
|
234
|
+
partyId: partyId!,
|
|
235
|
+
type: invoiceType,
|
|
236
|
+
invoiceDate,
|
|
237
|
+
dueDate,
|
|
238
|
+
deliveryMethod,
|
|
239
|
+
notes,
|
|
240
|
+
termsAndConditions: terms,
|
|
241
|
+
lineItems,
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
if (opts.json) {
|
|
245
|
+
outputJSON(invoice);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
success(`Created: ${invoice.invoiceNumber} for ${formatINR(invoice.totalAmount)}`);
|
|
250
|
+
console.log(` View: hisaabo invoice get ${invoice.invoiceNumber}`);
|
|
251
|
+
console.log(` PDF: hisaabo invoice pdf ${invoice.invoiceNumber}\n`);
|
|
252
|
+
|
|
253
|
+
} catch (e) {
|
|
254
|
+
if (e instanceof HisaaboApiError) {
|
|
255
|
+
const err = e.hisaaboError;
|
|
256
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
257
|
+
if (err.code === "validation_failed") fatalError(e.message, EXIT.VALIDATION);
|
|
258
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
259
|
+
}
|
|
260
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as readline from "readline";
|
|
2
|
+
import { HisaaboClient, HisaaboApiError } from "../../client.js";
|
|
3
|
+
import { requireAuth } from "../../config.js";
|
|
4
|
+
import { fatalError, outputJSON, EXIT, success } from "../../output.js";
|
|
5
|
+
|
|
6
|
+
export async function invoiceDeleteCommand(id: string, opts: { yes?: boolean; json?: boolean }): Promise<void> {
|
|
7
|
+
const cfg = requireAuth();
|
|
8
|
+
const client = new HisaaboClient(cfg);
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
const inv = await client.invoice.get(id);
|
|
12
|
+
|
|
13
|
+
if (!opts.yes && process.stdin.isTTY) {
|
|
14
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
15
|
+
const answer = await new Promise<string>((resolve) => {
|
|
16
|
+
rl.question(` Delete ${inv.invoiceNumber} (${inv.partyName}, ${inv.totalAmount})? (y/N): `, resolve);
|
|
17
|
+
});
|
|
18
|
+
rl.close();
|
|
19
|
+
if (answer.trim().toLowerCase() !== "y") {
|
|
20
|
+
console.log(" Cancelled.");
|
|
21
|
+
process.exit(0);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const result = await client.invoice.delete(id);
|
|
26
|
+
|
|
27
|
+
if (opts.json) {
|
|
28
|
+
outputJSON(result);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
success(`Deleted: ${inv.invoiceNumber}`);
|
|
33
|
+
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if (e instanceof HisaaboApiError) {
|
|
36
|
+
const err = e.hisaaboError;
|
|
37
|
+
if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
|
|
38
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
39
|
+
if (err.code === "forbidden") fatalError(err.message, EXIT.FORBIDDEN);
|
|
40
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
41
|
+
}
|
|
42
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { HisaaboClient, HisaaboApiError } from "../../client.js";
|
|
2
|
+
import { requireAuth } from "../../config.js";
|
|
3
|
+
import { fatalError, outputJSON, EXIT, termWidth, hasColor } from "../../output.js";
|
|
4
|
+
import { formatAmount, formatDate, formatStatus, deliveryMethodLabel } from "../../format.js";
|
|
5
|
+
import chalk from "chalk";
|
|
6
|
+
|
|
7
|
+
export async function invoiceGetCommand(id: string, opts: { json?: boolean }): Promise<void> {
|
|
8
|
+
const cfg = requireAuth();
|
|
9
|
+
const client = new HisaaboClient(cfg);
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const inv = await client.invoice.get(id);
|
|
13
|
+
|
|
14
|
+
if (opts.json) {
|
|
15
|
+
outputJSON(inv);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const w = Math.min(termWidth() - 2, 68);
|
|
20
|
+
const inner = w - 2;
|
|
21
|
+
|
|
22
|
+
function line(left: string, right?: string): void {
|
|
23
|
+
if (right !== undefined) {
|
|
24
|
+
const pad = Math.max(1, inner - left.length - right.length - 2);
|
|
25
|
+
process.stdout.write(`│ ${left}${" ".repeat(pad)}${right} │\n`);
|
|
26
|
+
} else {
|
|
27
|
+
const vis = left.length;
|
|
28
|
+
const pad = Math.max(0, inner - vis);
|
|
29
|
+
process.stdout.write(`│ ${left}${" ".repeat(pad)} │\n`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function divider(): void {
|
|
34
|
+
process.stdout.write(`├${"─".repeat(inner + 2)}┤\n`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const title = `SALE INVOICE ${inv.invoiceNumber}`;
|
|
38
|
+
const statusBadge = formatStatus(inv.status);
|
|
39
|
+
// eslint-disable-next-line no-control-regex
|
|
40
|
+
const topPad = Math.max(1, inner - title.length - statusBadge.replace(/\x1b\[[0-9;]*m/g, "").length);
|
|
41
|
+
|
|
42
|
+
process.stdout.write(`\n ┌${"─".repeat(inner + 2)}┐\n`);
|
|
43
|
+
process.stdout.write(`│ ${hasColor() ? chalk.bold(title) : title}${" ".repeat(topPad)}${statusBadge} │\n`);
|
|
44
|
+
divider();
|
|
45
|
+
line(`Party: ${inv.partyName}`);
|
|
46
|
+
line(`Date: ${formatDate(inv.invoiceDate)}`);
|
|
47
|
+
if (inv.dueDate) line(`Due: ${formatDate(inv.dueDate)}`);
|
|
48
|
+
if (inv.createdByName) line(`Created: ${inv.createdByName}${inv.createdAt ? ` (${formatDate(inv.createdAt)})` : ""}`);
|
|
49
|
+
if (inv.deliveryMethod) line(`Delivery: ${deliveryMethodLabel(inv.deliveryMethod)}`);
|
|
50
|
+
divider();
|
|
51
|
+
|
|
52
|
+
// Line items header
|
|
53
|
+
process.stdout.write(`│ │\n`);
|
|
54
|
+
process.stdout.write(`│ # ${"Item".padEnd(18)} ${"Qty".padStart(5)} ${"Rate (₹)".padStart(10)} ${"Tax%".padStart(5)} ${"Amount (₹)".padStart(12)} │\n`);
|
|
55
|
+
process.stdout.write(`│ ${"──".padEnd(2)} ${"─".repeat(18)} ${"─".repeat(5)} ${"─".repeat(10)} ${"─".repeat(5)} ${"─".repeat(12)} │\n`);
|
|
56
|
+
|
|
57
|
+
inv.lineItems.forEach((item, i) => {
|
|
58
|
+
const idx = String(i + 1).padStart(2);
|
|
59
|
+
const desc = item.description.slice(0, 18).padEnd(18);
|
|
60
|
+
const qty = item.quantity.padStart(5);
|
|
61
|
+
const rate = formatAmount(item.unitPrice).padStart(10);
|
|
62
|
+
const tax = `${item.taxPercent}%`.padStart(5);
|
|
63
|
+
const amt = formatAmount(item.amount).padStart(12);
|
|
64
|
+
process.stdout.write(`│ ${idx} ${desc} ${qty} ${rate} ${tax} ${amt} │\n`);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
process.stdout.write(`│ │\n`);
|
|
68
|
+
divider();
|
|
69
|
+
|
|
70
|
+
// Totals
|
|
71
|
+
const subtotal = inv.lineItems.reduce((s, i) => s + parseFloat(i.amount), 0);
|
|
72
|
+
const _tax = parseFloat(inv.totalAmount) - subtotal - parseFloat(inv.roundOff ?? "0") + parseFloat(inv.invoiceDiscount ?? "0");
|
|
73
|
+
|
|
74
|
+
line(`Subtotal:`, formatAmount(String(subtotal)).padStart(16));
|
|
75
|
+
if (parseFloat(inv.invoiceDiscount ?? "0") !== 0)
|
|
76
|
+
line(`Discount:`, ("-" + formatAmount(inv.invoiceDiscount)).padStart(16));
|
|
77
|
+
if (inv.charges && inv.charges.length > 0) {
|
|
78
|
+
inv.charges.forEach((c) => line(`${c.label}:`, formatAmount(c.amount).padStart(16)));
|
|
79
|
+
}
|
|
80
|
+
if (parseFloat(inv.roundOff ?? "0") !== 0)
|
|
81
|
+
line(`Round Off:`, formatAmount(inv.roundOff).padStart(16));
|
|
82
|
+
process.stdout.write(`│ ${"─".repeat(inner - 2)} │\n`);
|
|
83
|
+
line(`Total:`, (hasColor() ? chalk.bold(formatAmount(inv.totalAmount)) : formatAmount(inv.totalAmount)).padStart(16));
|
|
84
|
+
line(`Paid:`, formatAmount(inv.amountPaid).padStart(16));
|
|
85
|
+
line(`Balance:`, formatAmount(inv.balanceDue).padStart(16));
|
|
86
|
+
|
|
87
|
+
if (inv.notes || inv.termsAndConditions) {
|
|
88
|
+
divider();
|
|
89
|
+
if (inv.notes) line(`Notes: ${inv.notes}`);
|
|
90
|
+
if (inv.termsAndConditions) line(`Terms: ${inv.termsAndConditions}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
process.stdout.write(` └${"─".repeat(inner + 2)}┘\n\n`);
|
|
94
|
+
process.stdout.write(` Actions: [e] Edit [p] PDF [d] Delete [pay] Record Payment\n\n`);
|
|
95
|
+
|
|
96
|
+
} catch (e) {
|
|
97
|
+
if (e instanceof HisaaboApiError) {
|
|
98
|
+
const err = e.hisaaboError;
|
|
99
|
+
if (err.code === "not_found") fatalError(`Invoice not found: ${id}`, EXIT.NOT_FOUND);
|
|
100
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
101
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
102
|
+
}
|
|
103
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { HisaaboClient, HisaaboApiError, type InvoiceSummary } from "../../client.js";
|
|
2
|
+
import { requireAuth } from "../../config.js";
|
|
3
|
+
import {
|
|
4
|
+
fatalError, outputJSON, outputTable, outputTSV, outputCSV, outputIds,
|
|
5
|
+
paginationFooter, EXIT, getWidthTier, type ColumnDef,
|
|
6
|
+
} from "../../output.js";
|
|
7
|
+
import { formatAmount, formatDate, formatStatus, currentFY, fyStart, todayISO, monthStart, monthEnd } from "../../format.js";
|
|
8
|
+
|
|
9
|
+
interface ListOpts {
|
|
10
|
+
json?: boolean;
|
|
11
|
+
format?: string;
|
|
12
|
+
type?: string;
|
|
13
|
+
status?: string;
|
|
14
|
+
party?: string;
|
|
15
|
+
partyId?: string;
|
|
16
|
+
from?: string;
|
|
17
|
+
to?: string;
|
|
18
|
+
thisMonth?: boolean;
|
|
19
|
+
thisQuarter?: boolean;
|
|
20
|
+
thisFy?: boolean;
|
|
21
|
+
page?: number;
|
|
22
|
+
limit?: number;
|
|
23
|
+
search?: string;
|
|
24
|
+
sortBy?: string;
|
|
25
|
+
sortDir?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function invoiceListCommand(opts: ListOpts): Promise<void> {
|
|
29
|
+
const cfg = requireAuth();
|
|
30
|
+
const client = new HisaaboClient(cfg);
|
|
31
|
+
|
|
32
|
+
// Resolve date range
|
|
33
|
+
let from = opts.from;
|
|
34
|
+
let to = opts.to;
|
|
35
|
+
if (opts.thisFy) { from = fyStart(); to = todayISO(); }
|
|
36
|
+
else if (opts.thisMonth) { from = monthStart(); to = monthEnd(); }
|
|
37
|
+
else if (opts.thisQuarter) {
|
|
38
|
+
const now = new Date();
|
|
39
|
+
const month = now.getMonth() + 1;
|
|
40
|
+
const year = now.getFullYear();
|
|
41
|
+
if (month >= 4 && month <= 6) { from = `${year}-04-01`; to = `${year}-06-30`; }
|
|
42
|
+
else if (month >= 7 && month <= 9) { from = `${year}-07-01`; to = `${year}-09-30`; }
|
|
43
|
+
else if (month >= 10 && month <= 12) { from = `${year}-10-01`; to = `${year}-12-31`; }
|
|
44
|
+
else { from = `${year}-01-01`; to = `${year}-03-31`; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const page = opts.page ?? 1;
|
|
48
|
+
const limit = opts.limit ?? 20;
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const result = await client.invoice.list({
|
|
52
|
+
type: opts.type as "sale" | "purchase" | undefined ?? null,
|
|
53
|
+
status: opts.status as InvoiceSummary["status"] | undefined ?? null,
|
|
54
|
+
partyId: opts.partyId ?? null,
|
|
55
|
+
fromDate: from ?? null,
|
|
56
|
+
toDate: to ?? null,
|
|
57
|
+
search: opts.search ?? null,
|
|
58
|
+
sortBy: opts.sortBy as "date" | "amount" | "number" | undefined ?? null,
|
|
59
|
+
sortDir: opts.sortDir as "asc" | "desc" | undefined ?? null,
|
|
60
|
+
page,
|
|
61
|
+
limit,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (opts.json) {
|
|
65
|
+
outputJSON({
|
|
66
|
+
data: result.data,
|
|
67
|
+
pagination: { page: result.page, limit: result.limit, total: result.total, hasMore: result.page * result.limit < result.total },
|
|
68
|
+
});
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const tier = getWidthTier();
|
|
73
|
+
|
|
74
|
+
// Title
|
|
75
|
+
const typeLabel = opts.type === "purchase" ? "Purchase Bills" : "Sale Invoices";
|
|
76
|
+
console.log(`\n ${typeLabel}` + " ".repeat(40) + `FY ${currentFY()}`);
|
|
77
|
+
console.log(` ${"═".repeat(68)}\n`);
|
|
78
|
+
|
|
79
|
+
const narrowCols: ColumnDef<InvoiceSummary>[] = [
|
|
80
|
+
{ key: "invoiceNumber", header: "#", width: 10 },
|
|
81
|
+
{ key: "partyName", header: "Party", width: 18 },
|
|
82
|
+
{ key: "totalAmount", header: "Amount (₹)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
|
|
83
|
+
{ key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) },
|
|
84
|
+
];
|
|
85
|
+
|
|
86
|
+
const standardCols: ColumnDef<InvoiceSummary>[] = [
|
|
87
|
+
{ key: "invoiceNumber", header: "#", width: 10 },
|
|
88
|
+
{ key: "partyName", header: "Party", width: 18 },
|
|
89
|
+
{ key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
|
|
90
|
+
{ key: "totalAmount", header: "Amount (₹)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
|
|
91
|
+
{ key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) },
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
const wideCols: ColumnDef<InvoiceSummary>[] = [
|
|
95
|
+
{ key: "invoiceNumber", header: "#", width: 10 },
|
|
96
|
+
{ key: "partyName", header: "Party", width: 18 },
|
|
97
|
+
{ key: "invoiceDate", header: "Date", width: 12, format: (v) => formatDate(String(v ?? "")) },
|
|
98
|
+
{ key: "dueDate", header: "Due", width: 12, format: (v) => formatDate(v ? String(v) : null) },
|
|
99
|
+
{ key: "totalAmount", header: "Amount (₹)", align: "right", width: 13, format: (v) => formatAmount(String(v ?? "0")) },
|
|
100
|
+
{ key: "amountPaid", header: "Paid (₹)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
|
|
101
|
+
{ key: "balanceDue", header: "Balance (₹)", align: "right", width: 12, format: (v) => formatAmount(String(v ?? "0")) },
|
|
102
|
+
{ key: "status", header: "Status", width: 10, format: (v) => formatStatus(String(v ?? "")) },
|
|
103
|
+
];
|
|
104
|
+
|
|
105
|
+
const cols = tier === "narrow" ? narrowCols : tier === "wide" ? wideCols : standardCols;
|
|
106
|
+
|
|
107
|
+
if (opts.format === "tsv") {
|
|
108
|
+
outputTSV(result.data, cols);
|
|
109
|
+
} else if (opts.format === "csv") {
|
|
110
|
+
outputCSV(result.data, cols);
|
|
111
|
+
} else if (opts.format === "ids") {
|
|
112
|
+
outputIds(result.data.map((r) => r.id));
|
|
113
|
+
} else {
|
|
114
|
+
outputTable(result.data, cols);
|
|
115
|
+
paginationFooter(result.page, result.limit, result.total);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
} catch (e) {
|
|
119
|
+
if (e instanceof HisaaboApiError) {
|
|
120
|
+
const err = e.hisaaboError;
|
|
121
|
+
if (err.code === "unauthorized") fatalError("Session expired. Run: hisaabo login", EXIT.AUTH);
|
|
122
|
+
if (err.code === "network_error") fatalError(err.message, EXIT.NETWORK);
|
|
123
|
+
}
|
|
124
|
+
fatalError(String(e instanceof Error ? e.message : e));
|
|
125
|
+
}
|
|
126
|
+
}
|