Add backup/restore, daily auto-backup and history CSV/JSON export (Phase E3)
- create_backup writes a zip (manifest with sha256 per file, a VACUUM INTO database snapshot, assets, archive, fonts) atomically. restore_backup validates the manifest, rejects tampered files, path traversal, symlinks and newer schemas, checks the staged DB with integrity_check, then stages a pending restore. The swap runs on the next start before the database opens, moves the current data to backups/pre-restore-<ts>/ and rolls back on any failure. - Daily automatic backup (migration M9 auto_backup, default on) keeps the newest 14 and never blocks startup. - Settings Data tab: back up now, restore with confirmation and restart, auto-backup toggle, last backup time. - History exports the filtered rows as CSV (UTF-8 BOM, CRLF, formula-injection guard) or JSON (voiced.history.v1) with CA-friendly tax columns from a new list_invoice_ledger command. - Rust round-trip, rejection, swap-rollback and retention tests; vitest for the export and backup helpers. Adds the zip 8.6.0 and typed-path 0.12.3 crates (pure Rust); package builds must vendor them. PDF output and fingerprint goldens are unchanged. The new UI has not been run in a webview yet.
This commit is contained in:
@@ -12,6 +12,8 @@ import type {
|
||||
} from "./types";
|
||||
import type { LogoAsset } from "./logo";
|
||||
import type { Payment, PaymentInput } from "./payments";
|
||||
import type { BackupStatus, BackupSummary, PendingRestore } from "./backup";
|
||||
import type { LedgerRow } from "./historyExport";
|
||||
import type { FontInspection, ImportMeta, RemoveOutcome, UserFontRow } from "./fontImport";
|
||||
|
||||
export interface ArchiveStatus {
|
||||
@@ -48,6 +50,7 @@ export const api = {
|
||||
cancelInvoice: (id: number, reason: string) =>
|
||||
invoke<Invoice>("cancel_invoice", { id, reason }),
|
||||
listInvoices: () => invoke<InvoiceSummary[]>("list_invoices"),
|
||||
listInvoiceLedger: () => invoke<LedgerRow[]>("list_invoice_ledger"),
|
||||
getInvoice: (id: number) => invoke<Invoice>("get_invoice", { id }),
|
||||
|
||||
recordPayment: (input: PaymentInput) => invoke<Payment>("record_payment", { input }),
|
||||
@@ -102,4 +105,12 @@ export const api = {
|
||||
getLastExportDir: () => invoke<string>("get_last_export_dir"),
|
||||
revealInFolder: (path: string) => invoke<void>("reveal_in_folder", { path }),
|
||||
openFile: (path: string) => invoke<void>("open_file", { path }),
|
||||
|
||||
// Backup and restore. A restore is staged now and applied by the next start (see commands/backup.rs).
|
||||
createBackup: (dest: string) => invoke<BackupSummary>("create_backup", { dest }),
|
||||
restoreBackup: (path: string) => invoke<PendingRestore>("restore_backup", { path }),
|
||||
cancelPendingRestore: () => invoke<void>("cancel_pending_restore"),
|
||||
getBackupStatus: () => invoke<BackupStatus>("get_backup_status"),
|
||||
setAutoBackup: (enabled: boolean) => invoke<boolean>("set_auto_backup", { enabled }),
|
||||
restartApp: () => invoke<void>("restart_app"),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { backupFileName, ensureZipExtension, formatBytes, formatWhen } from "./backup";
|
||||
|
||||
describe("backup helpers", () => {
|
||||
it("names backups by local date and time", () => {
|
||||
expect(backupFileName(new Date(2026, 2, 4, 9, 5))).toBe("voiced-backup-20260304-0905.zip");
|
||||
});
|
||||
it("adds the zip extension only when missing", () => {
|
||||
expect(ensureZipExtension("/a/b")).toBe("/a/b.zip");
|
||||
expect(ensureZipExtension("/a/b.ZIP")).toBe("/a/b.ZIP");
|
||||
expect(ensureZipExtension("/a/b.zip")).toBe("/a/b.zip");
|
||||
});
|
||||
it("formats sizes", () => {
|
||||
expect(formatBytes(512)).toBe("512 B");
|
||||
expect(formatBytes(1536)).toBe("1.5 KB");
|
||||
expect(formatBytes(5 * 1024 * 1024)).toBe("5.0 MB");
|
||||
expect(formatBytes(300 * 1024 * 1024)).toBe("300 MB");
|
||||
});
|
||||
it("falls back to the raw text for an unparseable time", () => {
|
||||
expect(formatWhen("not a date")).toBe("not a date");
|
||||
expect(formatWhen("2026-03-04T10:00:00Z")).toMatch(/2026/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
/** Shapes returned by the backup commands (src-tauri/src/commands/backup.rs). */
|
||||
export interface BackupSummary {
|
||||
path: string;
|
||||
createdAt: string;
|
||||
schemaVersion: number;
|
||||
fileCount: number;
|
||||
totalBytes: number;
|
||||
}
|
||||
|
||||
export interface PendingRestore {
|
||||
backupName: string;
|
||||
backupCreatedAt: string;
|
||||
appVersion: string;
|
||||
schemaVersion: number;
|
||||
fileCount: number;
|
||||
totalBytes: number;
|
||||
stagedAt: string;
|
||||
}
|
||||
|
||||
export interface LastRestore {
|
||||
ok: boolean;
|
||||
at: string;
|
||||
backupName: string;
|
||||
message: string;
|
||||
safetyDir: string | null;
|
||||
}
|
||||
|
||||
export interface BackupStatus {
|
||||
autoBackup: boolean;
|
||||
autoDir: string;
|
||||
lastAutoBackup: string | null;
|
||||
autoBackupCount: number;
|
||||
pendingRestore: PendingRestore | null;
|
||||
lastRestore: LastRestore | null;
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
/** `voiced-backup-20260304-1530.zip` in local time. */
|
||||
export function backupFileName(now: Date = new Date()): string {
|
||||
const day = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
|
||||
return `voiced-backup-${day}-${pad(now.getHours())}${pad(now.getMinutes())}.zip`;
|
||||
}
|
||||
|
||||
/** The save dialog does not always add the extension (notably on Linux). */
|
||||
export function ensureZipExtension(path: string): string {
|
||||
return /\.zip$/i.test(path) ? path : `${path}.zip`;
|
||||
}
|
||||
|
||||
/** 1536 -> "1.5 KB". Sizes of backup contents are display-only, so plain division is fine. */
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ["KB", "MB", "GB", "TB"];
|
||||
let value = bytes / 1024;
|
||||
let i = 0;
|
||||
while (value >= 1024 && i < units.length - 1) {
|
||||
value /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[i]}`;
|
||||
}
|
||||
|
||||
/** "4 Mar 2026, 3:30 pm" for an ISO timestamp; the raw text if it does not parse. */
|
||||
export function formatWhen(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleString("en-GB", { day: "numeric", month: "short", year: "numeric", hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildHistoryRows,
|
||||
csvField,
|
||||
exportHistory,
|
||||
guardFormula,
|
||||
HISTORY_COLUMNS,
|
||||
historyExportName,
|
||||
paiseToDecimal,
|
||||
toCsv,
|
||||
toJson,
|
||||
type HistoryExportDeps,
|
||||
type LedgerRow,
|
||||
} from "./historyExport";
|
||||
import { NO_FILTERS } from "./historyFilter";
|
||||
import type { InvoiceSummary } from "./types";
|
||||
|
||||
const summary = (over: Partial<InvoiceSummary> = {}): InvoiceSummary => ({
|
||||
id: 1,
|
||||
number: "INV/2025-001",
|
||||
invoiceDate: "2025-06-10",
|
||||
dueDate: "2025-07-10",
|
||||
clientName: "Acme, Inc.",
|
||||
total: 0,
|
||||
status: "issued",
|
||||
createdAt: "",
|
||||
poNumber: "PO-1",
|
||||
totalPaise: 1_180_050,
|
||||
paidPaise: 1_000_000,
|
||||
tdsPaise: 50_000,
|
||||
balancePaise: 130_050,
|
||||
paymentStatus: "partially_paid",
|
||||
...over,
|
||||
});
|
||||
|
||||
const ledger = (over: Partial<LedgerRow> = {}): LedgerRow => ({
|
||||
id: 1,
|
||||
clientGstin: "29ABCDE1234F1Z5",
|
||||
placeOfSupplyCode: "29",
|
||||
docType: "tax_invoice",
|
||||
hsnSac: ["9983", "9984", "9983"],
|
||||
taxablePaise: 1_000_000,
|
||||
cgstPaise: 90_025,
|
||||
sgstPaise: 90_025,
|
||||
igstPaise: 0,
|
||||
reverseCharge: false,
|
||||
...over,
|
||||
});
|
||||
|
||||
const columnIndex = (key: string) => HISTORY_COLUMNS.findIndex((c) => c.key === key);
|
||||
|
||||
describe("paiseToDecimal", () => {
|
||||
it("formats from integer paise without float math", () => {
|
||||
expect(paiseToDecimal(0)).toBe("0.00");
|
||||
expect(paiseToDecimal(5)).toBe("0.05");
|
||||
expect(paiseToDecimal(100)).toBe("1.00");
|
||||
expect(paiseToDecimal(123_450)).toBe("1234.50");
|
||||
expect(paiseToDecimal(-5)).toBe("-0.05");
|
||||
expect(paiseToDecimal(-123_456)).toBe("-1234.56");
|
||||
// 1.005 * 100 style float traps cannot happen: 100_100_000_000_005 paise.
|
||||
expect(paiseToDecimal(100_100_000_000_005)).toBe("1001000000000.05");
|
||||
});
|
||||
it("rejects non-integers", () => {
|
||||
expect(() => paiseToDecimal(1.5)).toThrow();
|
||||
expect(() => paiseToDecimal(Number.NaN)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("rows", () => {
|
||||
it("builds the CA-friendly columns", () => {
|
||||
const [row] = buildHistoryRows([summary()], [ledger()]);
|
||||
const get = (key: string) => row[columnIndex(key)];
|
||||
expect(HISTORY_COLUMNS.map((c) => c.header)).toEqual([
|
||||
"Invoice No", "Date", "Due Date", "Client", "Client GSTIN", "Place of Supply Code", "Place of Supply",
|
||||
"Document Type", "HSN/SAC", "Taxable Value", "CGST", "SGST", "IGST", "Total Tax", "Invoice Total",
|
||||
"Received", "TDS", "Balance", "Status", "Payment Status", "PO Number", "Cancelled",
|
||||
]);
|
||||
expect(get("invoiceNo")).toBe("INV/2025-001");
|
||||
expect(get("placeOfSupplyCode")).toBe("29");
|
||||
expect(get("placeOfSupply")).toBe("Karnataka");
|
||||
expect(get("documentType")).toBe("Tax Invoice");
|
||||
expect(get("hsnSac")).toBe("9983; 9984");
|
||||
expect(get("taxableValue")).toBe("10000.00");
|
||||
expect(get("cgst")).toBe("900.25");
|
||||
expect(get("igst")).toBe("0.00");
|
||||
expect(get("totalTax")).toBe("1800.50");
|
||||
expect(get("invoiceTotal")).toBe("11800.50");
|
||||
expect(get("received")).toBe("10000.00");
|
||||
expect(get("tds")).toBe("500.00");
|
||||
expect(get("balance")).toBe("1300.50");
|
||||
expect(get("status")).toBe("Issued");
|
||||
expect(get("paymentStatus")).toBe("Partly paid");
|
||||
expect(get("cancelled")).toBe("No");
|
||||
});
|
||||
|
||||
it("flags cancelled invoices and leaves ledger fields blank when the row is missing", () => {
|
||||
const [row] = buildHistoryRows([summary({ status: "cancelled", paymentStatus: "none" })], []);
|
||||
expect(row[columnIndex("cancelled")]).toBe("Yes");
|
||||
expect(row[columnIndex("status")]).toBe("Cancelled");
|
||||
expect(row[columnIndex("paymentStatus")]).toBe("");
|
||||
expect(row[columnIndex("taxableValue")]).toBe("");
|
||||
expect(row[columnIndex("invoiceTotal")]).toBe("11800.50");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CSV", () => {
|
||||
it("quotes per RFC 4180", () => {
|
||||
expect(csvField("plain")).toBe("plain");
|
||||
expect(csvField("a,b")).toBe('"a,b"');
|
||||
expect(csvField('say "hi"')).toBe('"say ""hi"""');
|
||||
expect(csvField("two\nlines")).toBe('"two\nlines"');
|
||||
expect(csvField("cr\rhere")).toBe('"cr\rhere"');
|
||||
expect(csvField(" padded")).toBe('" padded"');
|
||||
});
|
||||
|
||||
it("guards text cells against formula injection but leaves amounts numeric", () => {
|
||||
for (const bad of ["=1+1", "+SUM(A1)", "-2+3", "@cmd", "\tTAB", "\rCR"]) {
|
||||
expect(guardFormula(bad)).toBe(`'${bad}`);
|
||||
}
|
||||
expect(guardFormula("INV/2025-001")).toBe("INV/2025-001");
|
||||
const cells = buildHistoryRows(
|
||||
[summary({ clientName: "=HYPERLINK(\"http://x\")", poNumber: "-5", balancePaise: -2_500, paidPaise: 0 })],
|
||||
[ledger()],
|
||||
);
|
||||
const csv = toCsv(cells);
|
||||
const dataLine = csv.split("\r\n")[1];
|
||||
expect(dataLine).toContain(`"'=HYPERLINK(""http://x"")"`);
|
||||
expect(dataLine).toContain(",'-5,"); // PO number text is guarded
|
||||
expect(dataLine).toContain(",-25.00,"); // the numeric balance is not
|
||||
expect(dataLine).not.toContain("'-25.00");
|
||||
});
|
||||
|
||||
it("has a BOM, CRLF line ends and a trailing newline", () => {
|
||||
const csv = toCsv(buildHistoryRows([summary(), summary({ id: 2, number: "INV/2025-002" })], [ledger(), ledger({ id: 2 })]));
|
||||
expect(csv.startsWith("Invoice No,Date,")).toBe(true);
|
||||
expect(csv.endsWith("\r\n")).toBe(true);
|
||||
expect(csv.split("\r\n")).toHaveLength(4); // header, two rows, empty after the last CRLF
|
||||
expect(csv.replace(/\r\n/g, "").includes("\n")).toBe(false);
|
||||
expect(new TextEncoder().encode(csv).slice(0, 3)).toEqual(new Uint8Array([0xef, 0xbb, 0xbf]));
|
||||
});
|
||||
|
||||
it("an empty set is a header-only file", () => {
|
||||
const csv = toCsv(buildHistoryRows([], []));
|
||||
expect(csv.split("\r\n")).toEqual([expect.stringMatching(/^Invoice No,.*Cancelled$/), ""]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON", () => {
|
||||
it("wraps the rows with schema, time and filters", () => {
|
||||
const filters = { ...NO_FILTERS, fy: 2025 as const, search: "acme" };
|
||||
const parsed = JSON.parse(toJson(buildHistoryRows([summary()], [ledger()]), filters, "2026-01-02T03:04:05.000Z"));
|
||||
expect(parsed.schema).toBe("voiced.history.v1");
|
||||
expect(parsed.exported_at).toBe("2026-01-02T03:04:05.000Z");
|
||||
expect(parsed.filters).toEqual(filters);
|
||||
expect(parsed.count).toBe(1);
|
||||
expect(parsed.rows[0]).toMatchObject({ invoiceNo: "INV/2025-001", taxableValue: "10000.00", totalTax: "1800.50", cancelled: "No" });
|
||||
});
|
||||
|
||||
it("an empty set has no rows", () => {
|
||||
const parsed = JSON.parse(toJson([], NO_FILTERS, "t"));
|
||||
expect(parsed.rows).toEqual([]);
|
||||
expect(parsed.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("historyExportName", () => {
|
||||
it("uses the financial year when one is picked", () => {
|
||||
expect(historyExportName({ ...NO_FILTERS, fy: 2025 }, [], "csv")).toBe("voiced-history-FY2025-26.csv");
|
||||
expect(historyExportName({ ...NO_FILTERS, fy: 2025, month: 4 }, [], "json")).toBe("voiced-history-FY2025-26-m04.json");
|
||||
});
|
||||
it("otherwise the date range of the rows", () => {
|
||||
const rows = [summary({ invoiceDate: "2025-06-10" }), summary({ invoiceDate: "2025-04-02" })];
|
||||
expect(historyExportName(NO_FILTERS, rows, "csv")).toBe("voiced-history-2025-04-02_to_2025-06-10.csv");
|
||||
expect(historyExportName(NO_FILTERS, [rows[0]], "csv")).toBe("voiced-history-2025-06-10.csv");
|
||||
expect(historyExportName(NO_FILTERS, [], "csv")).toBe("voiced-history-all.csv");
|
||||
});
|
||||
});
|
||||
|
||||
describe("exportHistory", () => {
|
||||
const make = (chosen: string | null) => {
|
||||
const written: { path: string; text: string }[] = [];
|
||||
const saves: { defaultPath: string; format: string }[] = [];
|
||||
const deps: HistoryExportDeps = {
|
||||
listLedger: async () => [ledger()],
|
||||
getLastExportDir: async () => "/home/a/Exports",
|
||||
save: async (o) => {
|
||||
saves.push(o);
|
||||
return chosen;
|
||||
},
|
||||
writeExportFile: async (path, bytes) => {
|
||||
written.push({ path, text: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) });
|
||||
return path;
|
||||
},
|
||||
now: () => new Date("2026-01-02T03:04:05Z"),
|
||||
};
|
||||
return { deps, written, saves };
|
||||
};
|
||||
|
||||
it("writes exactly the rows given, through the save dialog", async () => {
|
||||
const { deps, written, saves } = make("/home/a/Exports/out.csv");
|
||||
const out = await exportHistory(deps, [summary()], { ...NO_FILTERS, fy: 2025 }, "csv");
|
||||
expect(out).toEqual({ path: "/home/a/Exports/out.csv", count: 1 });
|
||||
expect(saves[0]).toEqual({ defaultPath: "/home/a/Exports/voiced-history-FY2025-26.csv", format: "csv" });
|
||||
expect(written).toHaveLength(1);
|
||||
expect(written[0].text.startsWith("Invoice No")).toBe(true);
|
||||
expect(written[0].text.split("\r\n")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("writes nothing when the dialog is cancelled, and a header-only file for an empty set", async () => {
|
||||
const cancelled = make(null);
|
||||
expect(await exportHistory(cancelled.deps, [summary()], NO_FILTERS, "json")).toBeNull();
|
||||
expect(cancelled.written).toEqual([]);
|
||||
const empty = make("/x/e.json");
|
||||
expect(await exportHistory(empty.deps, [], NO_FILTERS, "json")).toEqual({ path: "/x/e.json", count: 0 });
|
||||
expect(JSON.parse(empty.written[0].text).rows).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import { fyLabel } from "./fiscal";
|
||||
import type { HistoryFilters } from "./historyFilter";
|
||||
import { INDIAN_STATES, type InvoiceSummary } from "./types";
|
||||
|
||||
/** Per-invoice fields the History list does not carry (from the `list_invoice_ledger` command). Money is integer paise. */
|
||||
export interface LedgerRow {
|
||||
id: number;
|
||||
clientGstin: string;
|
||||
placeOfSupplyCode: string;
|
||||
docType: string;
|
||||
hsnSac: string[];
|
||||
taxablePaise: number;
|
||||
cgstPaise: number;
|
||||
sgstPaise: number;
|
||||
igstPaise: number;
|
||||
reverseCharge: boolean;
|
||||
}
|
||||
|
||||
export const HISTORY_SCHEMA = "voiced.history.v1";
|
||||
|
||||
/** 123450 -> "1234.50", -5 -> "-0.05". Integer arithmetic only; throws on anything that is not a safe integer. */
|
||||
export function paiseToDecimal(paise: number): string {
|
||||
if (!Number.isSafeInteger(paise)) throw new Error(`Not an amount in paise: ${paise}`);
|
||||
const abs = Math.abs(paise);
|
||||
const whole = Math.floor(abs / 100);
|
||||
const frac = abs % 100;
|
||||
return `${paise < 0 ? "-" : ""}${whole}.${frac < 10 ? "0" : ""}${frac}`;
|
||||
}
|
||||
|
||||
/** Text cells are guarded against spreadsheet formula injection; amount cells are known numbers and stay numeric. */
|
||||
type Kind = "text" | "amount";
|
||||
|
||||
interface Column {
|
||||
key: string;
|
||||
header: string;
|
||||
kind: Kind;
|
||||
value: (s: InvoiceSummary, l: LedgerRow | undefined) => string;
|
||||
}
|
||||
|
||||
const DOC_TYPES: Record<string, string> = { tax_invoice: "Tax Invoice", invoice: "Invoice" };
|
||||
const PAYMENT_STATUS: Record<string, string> = {
|
||||
unpaid: "Unpaid",
|
||||
partially_paid: "Partly paid",
|
||||
paid: "Paid",
|
||||
overdue: "Overdue",
|
||||
none: "",
|
||||
};
|
||||
const STATUS: Record<string, string> = { issued: "Issued", cancelled: "Cancelled", draft: "Draft" };
|
||||
|
||||
/** An amount that comes from the ledger row; blank (not a made-up zero) if the row is missing. */
|
||||
const ledgerAmount = (pick: (l: LedgerRow) => number) => (_s: InvoiceSummary, l: LedgerRow | undefined) =>
|
||||
l ? paiseToDecimal(pick(l)) : "";
|
||||
|
||||
/**
|
||||
* Column order and meaning for both formats. Cancelled invoices keep their figures (the document exists and
|
||||
* keeps its number); filter on the Cancelled column to leave them out of a sum.
|
||||
*/
|
||||
export const HISTORY_COLUMNS: readonly Column[] = [
|
||||
{ key: "invoiceNo", header: "Invoice No", kind: "text", value: (s) => s.number },
|
||||
{ key: "date", header: "Date", kind: "text", value: (s) => s.invoiceDate },
|
||||
{ key: "dueDate", header: "Due Date", kind: "text", value: (s) => s.dueDate },
|
||||
{ key: "client", header: "Client", kind: "text", value: (s) => s.clientName },
|
||||
{ key: "clientGstin", header: "Client GSTIN", kind: "text", value: (_s, l) => l?.clientGstin ?? "" },
|
||||
{ key: "placeOfSupplyCode", header: "Place of Supply Code", kind: "text", value: (_s, l) => l?.placeOfSupplyCode ?? "" },
|
||||
{
|
||||
key: "placeOfSupply",
|
||||
header: "Place of Supply",
|
||||
kind: "text",
|
||||
value: (_s, l) => INDIAN_STATES.find((st) => st.code === l?.placeOfSupplyCode)?.name ?? "",
|
||||
},
|
||||
{ key: "documentType", header: "Document Type", kind: "text", value: (_s, l) => (l ? (DOC_TYPES[l.docType] ?? l.docType) : "") },
|
||||
{ key: "hsnSac", header: "HSN/SAC", kind: "text", value: (_s, l) => (l ? [...new Set(l.hsnSac)].join("; ") : "") },
|
||||
{ key: "taxableValue", header: "Taxable Value", kind: "amount", value: ledgerAmount((l) => l.taxablePaise) },
|
||||
{ key: "cgst", header: "CGST", kind: "amount", value: ledgerAmount((l) => l.cgstPaise) },
|
||||
{ key: "sgst", header: "SGST", kind: "amount", value: ledgerAmount((l) => l.sgstPaise) },
|
||||
{ key: "igst", header: "IGST", kind: "amount", value: ledgerAmount((l) => l.igstPaise) },
|
||||
{ key: "totalTax", header: "Total Tax", kind: "amount", value: ledgerAmount((l) => l.cgstPaise + l.sgstPaise + l.igstPaise) },
|
||||
{ key: "invoiceTotal", header: "Invoice Total", kind: "amount", value: (s) => paiseToDecimal(s.totalPaise) },
|
||||
{ key: "received", header: "Received", kind: "amount", value: (s) => paiseToDecimal(s.paidPaise) },
|
||||
{ key: "tds", header: "TDS", kind: "amount", value: (s) => paiseToDecimal(s.tdsPaise) },
|
||||
{ key: "balance", header: "Balance", kind: "amount", value: (s) => paiseToDecimal(s.balancePaise) },
|
||||
{ key: "status", header: "Status", kind: "text", value: (s) => STATUS[s.status] ?? s.status },
|
||||
{ key: "paymentStatus", header: "Payment Status", kind: "text", value: (s) => PAYMENT_STATUS[s.paymentStatus] ?? s.paymentStatus },
|
||||
{ key: "poNumber", header: "PO Number", kind: "text", value: (s) => s.poNumber },
|
||||
{ key: "cancelled", header: "Cancelled", kind: "text", value: (s) => (s.status === "cancelled" ? "Yes" : "No") },
|
||||
];
|
||||
|
||||
/** The cells of every exported row, in column order. `ledger` is looked up by invoice id. */
|
||||
export function buildHistoryRows(summaries: InvoiceSummary[], ledger: LedgerRow[]): string[][] {
|
||||
const byId = new Map(ledger.map((l) => [l.id, l]));
|
||||
return summaries.map((s) => HISTORY_COLUMNS.map((c) => c.value(s, byId.get(s.id))));
|
||||
}
|
||||
|
||||
/** A text cell that a spreadsheet would read as a formula gets a leading apostrophe. */
|
||||
export function guardFormula(text: string): string {
|
||||
return /^[=+\-@\t\r]/.test(text) ? `'${text}` : text;
|
||||
}
|
||||
|
||||
/** RFC 4180 field: quoted when it holds a quote, comma or line break (or edge spaces), inner quotes doubled. */
|
||||
export function csvField(text: string): string {
|
||||
return /[",\r\n]|^\s|\s$/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
||||
}
|
||||
|
||||
/** UTF-8 BOM (so Excel reads it as UTF-8), CRLF line ends, header row always present. */
|
||||
export function toCsv(cells: string[][]): string {
|
||||
const lines = [HISTORY_COLUMNS.map((c) => csvField(c.header))];
|
||||
for (const row of cells) {
|
||||
lines.push(
|
||||
row.map((value, i) => {
|
||||
const column = HISTORY_COLUMNS[i];
|
||||
return csvField(column.kind === "text" ? guardFormula(value) : value);
|
||||
}),
|
||||
);
|
||||
}
|
||||
return `${lines.map((l) => l.join(",")).join("\r\n")}\r\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ schema, exported_at, filters, count, rows }`. Rows are objects keyed like the CSV columns; amounts are the same
|
||||
* 2-decimal rupee strings as in the CSV (no binary floats anywhere).
|
||||
*/
|
||||
export function toJson(cells: string[][], filters: HistoryFilters, exportedAt: string): string {
|
||||
const rows = cells.map((row) => Object.fromEntries(HISTORY_COLUMNS.map((c, i) => [c.key, row[i]])));
|
||||
return `${JSON.stringify({ schema: HISTORY_SCHEMA, exported_at: exportedAt, filters, count: rows.length, rows }, null, 2)}\n`;
|
||||
}
|
||||
|
||||
const safeName = (s: string) => s.replace(/[^A-Za-z0-9._-]+/g, "-");
|
||||
|
||||
/** `voiced-history-FY2025-26.csv`, or the date range of the rows when no year is picked, or `all` when empty. */
|
||||
export function historyExportName(
|
||||
filters: HistoryFilters,
|
||||
summaries: InvoiceSummary[],
|
||||
ext: "csv" | "json",
|
||||
): string {
|
||||
let part: string;
|
||||
if (filters.fy !== "all") {
|
||||
part = fyLabel(filters.fy).replace(/^FY /, "FY");
|
||||
if (filters.month !== "all") part += `-m${String(filters.month).padStart(2, "0")}`;
|
||||
} else {
|
||||
const dates = summaries.map((s) => s.invoiceDate).filter(Boolean).sort();
|
||||
if (dates.length === 0) part = "all";
|
||||
else part = dates[0] === dates[dates.length - 1] ? dates[0] : `${dates[0]}_to_${dates[dates.length - 1]}`;
|
||||
}
|
||||
return `voiced-history-${safeName(part)}.${ext}`;
|
||||
}
|
||||
|
||||
export type HistoryFormat = "csv" | "json";
|
||||
|
||||
export interface HistoryExportDeps {
|
||||
listLedger(): Promise<LedgerRow[]>;
|
||||
getLastExportDir(): Promise<string>;
|
||||
save(opts: { defaultPath: string; format: HistoryFormat }): Promise<string | null>;
|
||||
writeExportFile(path: string, bytes: Uint8Array): Promise<string>;
|
||||
now(): Date;
|
||||
}
|
||||
|
||||
function joinPath(dir: string, name: string): string {
|
||||
if (!dir) return name;
|
||||
if (/[\\/]$/.test(dir)) return `${dir}${name}`;
|
||||
return `${dir}${dir.includes("\\") && !dir.includes("/") ? "\\" : "/"}${name}`;
|
||||
}
|
||||
|
||||
/** Exports exactly `summaries` (the filtered, sorted rows) through the save dialog. Returns the path, or null if cancelled. */
|
||||
export async function exportHistory(
|
||||
deps: HistoryExportDeps,
|
||||
summaries: InvoiceSummary[],
|
||||
filters: HistoryFilters,
|
||||
format: HistoryFormat,
|
||||
): Promise<{ path: string; count: number } | null> {
|
||||
const ledger = await deps.listLedger();
|
||||
const cells = buildHistoryRows(summaries, ledger);
|
||||
const text = format === "csv" ? toCsv(cells) : toJson(cells, filters, deps.now().toISOString());
|
||||
let dir = "";
|
||||
try {
|
||||
dir = await deps.getLastExportDir();
|
||||
} catch {
|
||||
// No remembered folder: the dialog opens wherever the system prefers.
|
||||
}
|
||||
const chosen = await deps.save({ defaultPath: joinPath(dir, historyExportName(filters, summaries, format)), format });
|
||||
if (!chosen) return null;
|
||||
const path = (await deps.writeExportFile(chosen, new TextEncoder().encode(text))) || chosen;
|
||||
return { path, count: cells.length };
|
||||
}
|
||||
Reference in New Issue
Block a user