@baseworks/invoice 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/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # @baseworks/invoice
2
+
3
+ Typed client, event catalog, projections, and CLI plugin for **invoice-service** —
4
+ the per-org **AR ledger** (invoices + a transaction ledger). Contract-first,
5
+ versioned with the service.
6
+
7
+ ```bash
8
+ pnpm add @baseworks/invoice
9
+ ```
10
+
11
+ ## Client
12
+
13
+ Invoices are **org-scoped** (`X-Org-Id` + identity token). **Money is integer
14
+ cents** throughout. Status machine: `draft → finalized → paid | void`. A finalized
15
+ invoice is immutable (only payments / void follow).
16
+
17
+ ```ts
18
+ import { createInvoiceClient } from '@baseworks/invoice'
19
+
20
+ const invoices = createInvoiceClient({
21
+ baseUrl: process.env.INVOICE_SERVICE_URL!,
22
+ token: identityJwt,
23
+ orgId: activeOrgId,
24
+ })
25
+
26
+ // 1. draft — customerId is a customers-service ref (validated + name snapshotted)
27
+ const draft = await invoices.create({
28
+ customerId: 'acct-42',
29
+ currency: 'USD',
30
+ lines: [
31
+ { description: 'Consulting', quantity: 10, unitPriceCents: 15000 }, // $150.00 × 10
32
+ { description: 'Setup', quantity: 1, unitPriceCents: 50000 },
33
+ ],
34
+ })
35
+
36
+ // 2. finalize — assigns a per-org number, freezes lines + totals
37
+ const final = await invoices.finalize(draft.id, { dueAt: Date.parse('2026-08-01') })
38
+
39
+ // 3. record payments — balance can't go below zero (overpayment is rejected)
40
+ await invoices.recordPayment(final.id, { amountCents: 100000, method: 'bank', reference: 'TXN-1' })
41
+ await invoices.recordPayment(final.id, { amountCents: 100000 }) // → status 'paid'
42
+
43
+ // 4. the ledger — one row per money movement
44
+ await invoices.transactions() // all org transactions
45
+ await invoices.invoiceTransactions(final.id) // this invoice's payments
46
+
47
+ await invoices.list({ status: 'finalized' })
48
+ await invoices.get(final.id)
49
+ await invoices.void(final.id, 'issued in error')
50
+ ```
51
+
52
+ Errors throw `InvoiceError` (`.status`, `.code`): `409 not_draft` (edit a finalized
53
+ invoice), `409 overpayment` / `409 already_paid`, `404 customer_not_found`.
54
+
55
+ ## CLI plugin
56
+
57
+ ```ts
58
+ import { buildInvoiceCommand } from '@baseworks/invoice/cli'
59
+
60
+ program.addCommand(buildInvoiceCommand({ http, cliName: 'dtab' }))
61
+ // dtab invoices | inv list (--status) · create · get · update · finalize · pay · void
62
+ // dtab invoices create --customer <ref> --currency USD --line "Consulting|10|150.00"
63
+ // dtab invoices pay <ref> --amount 150.00 --method bank
64
+ // dtab invoices payments [<ref>] (the transaction ledger)
65
+ ```
66
+
67
+ ## Service integration
68
+
69
+ ```ts
70
+ import { PROJECTIONS, POLICIES } from '@baseworks/invoice/projections'
71
+ import { InvoiceEvents, TransactionEvents } from '@baseworks/invoice/events'
72
+ ```
73
+
74
+ Projections `invoices` → `read_invoices`, `transactions` → `read_transactions`
75
+ (one row per payment). Tenant = org id.
76
+
77
+ ## See also
78
+
79
+ Service: `projects/invoice-service` · [ADR-010](../../../../docs/decisions/010-driptab-erp-decomposition.md).
@@ -0,0 +1,78 @@
1
+ // src/events.ts
2
+ import { z } from "zod";
3
+ import { defineAggregate } from "@baseworks/foldbase";
4
+ var InvoiceStatus = z.enum(["draft", "finalized", "paid", "void"]);
5
+ var InvoiceEvents = defineAggregate("invoice", {
6
+ // Draft created (with its initial lines + computed totals). Numeric fields are
7
+ // initialised to 0 so their read-model columns are stable integers.
8
+ InvoiceDrafted: z.object({
9
+ customerId: z.string().min(1),
10
+ customerName: z.string(),
11
+ // snapshot at draft time; '' if unknown
12
+ currency: z.string().length(3),
13
+ lines: z.string(),
14
+ // JSON array of { description, quantity, unitPriceCents, amountCents, productId }
15
+ subtotalCents: z.number().int(),
16
+ totalCents: z.number().int(),
17
+ shortId: z.string().min(1),
18
+ at: z.number().int()
19
+ }),
20
+ // Draft edited (customer / lines). Only valid while status = draft.
21
+ InvoiceUpdated: z.object({
22
+ customerId: z.string().min(1),
23
+ customerName: z.string(),
24
+ lines: z.string(),
25
+ subtotalCents: z.number().int(),
26
+ totalCents: z.number().int(),
27
+ at: z.number().int()
28
+ }),
29
+ // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
30
+ InvoiceFinalized: z.object({
31
+ number: z.number().int(),
32
+ lines: z.string(),
33
+ subtotalCents: z.number().int(),
34
+ totalCents: z.number().int(),
35
+ issuedAt: z.number().int(),
36
+ dueAt: z.number().int(),
37
+ // 0 = no due date
38
+ at: z.number().int()
39
+ }),
40
+ // A payment applied to a finalized invoice. `amountPaidCents` is the new running
41
+ // total; `status` is the resulting status ('paid' when balance ≤ 0, else
42
+ // 'finalized') — both computed by the store.
43
+ PaymentRecorded: z.object({
44
+ amountCents: z.number().int(),
45
+ amountPaidCents: z.number().int(),
46
+ status: InvoiceStatus,
47
+ method: z.string(),
48
+ reference: z.string(),
49
+ at: z.number().int()
50
+ }),
51
+ InvoiceVoided: z.object({
52
+ reason: z.string(),
53
+ at: z.number().int()
54
+ })
55
+ });
56
+ var TransactionKind = z.enum(["payment", "refund", "adjustment"]);
57
+ var TransactionEvents = defineAggregate("transaction", {
58
+ TransactionRecorded: z.object({
59
+ invoiceId: z.string().min(1),
60
+ invoiceNumber: z.number().int(),
61
+ // the invoice's number at the time
62
+ customerId: z.string(),
63
+ customerName: z.string(),
64
+ kind: TransactionKind,
65
+ amountCents: z.number().int(),
66
+ currency: z.string().length(3),
67
+ method: z.string(),
68
+ reference: z.string(),
69
+ at: z.number().int()
70
+ })
71
+ });
72
+
73
+ export {
74
+ InvoiceStatus,
75
+ InvoiceEvents,
76
+ TransactionKind,
77
+ TransactionEvents
78
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Command } from 'commander';
2
+ import { ApiClient } from '@baseworks/cli/client';
3
+
4
+ /**
5
+ * Importable `invoices` command group. The `http` ApiClient points at the app's
6
+ * invoice mount, carries the caller's identity token, and must send the active
7
+ * org (X-Org-Id) — invoices are org-scoped. Mounts as:
8
+ *
9
+ * program.addCommand(buildInvoiceCommand({ http, cliName: 'dtab' }))
10
+ *
11
+ * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
12
+ * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
13
+ * `invoices finalize <ref>` · `invoices pay <ref> --amount 150.00` ·
14
+ * `invoices void <ref>`
15
+ */
16
+ interface InvoiceCliDeps {
17
+ http: ApiClient;
18
+ cliName?: string;
19
+ }
20
+ declare function buildInvoiceCommand(deps: InvoiceCliDeps): Command;
21
+
22
+ export { type InvoiceCliDeps, buildInvoiceCommand };
package/dist/cli.js ADDED
@@ -0,0 +1,167 @@
1
+ // src/cli.ts
2
+ import { Command } from "commander";
3
+ import { clr, kv, table, summary, success, fatal, printOutput, outputOption } from "@baseworks/cli/display";
4
+ import { fmtDate } from "@baseworks/cli/fmt";
5
+ var die = (e) => fatal(e instanceof Error ? e.message : String(e));
6
+ function fmtMoney(cents, currency) {
7
+ return `${(cents / 100).toFixed(2)} ${currency}`;
8
+ }
9
+ function toCents(amount, flag = "--amount") {
10
+ const n = Number(amount);
11
+ if (!Number.isFinite(n) || n < 0) fatal(`${flag} must be a non-negative number, got '${amount}'`);
12
+ const cents = Math.round(n * 100);
13
+ if (Math.abs(cents - n * 100) > 1e-6) fatal(`${flag} has sub-cent precision: '${amount}'`);
14
+ return cents;
15
+ }
16
+ function parseLine(spec) {
17
+ const parts = spec.split("|");
18
+ if (parts.length !== 3) fatal(`--line expects "description|qty|unitPrice", got '${spec}'`);
19
+ const description = parts[0].trim();
20
+ const quantity = Number(parts[1]);
21
+ if (!description) fatal(`--line description is empty in '${spec}'`);
22
+ if (!Number.isFinite(quantity) || quantity <= 0) fatal(`--line qty must be > 0 in '${spec}'`);
23
+ return { description, quantity, unitPriceCents: toCents(parts[2].trim(), "--line unitPrice") };
24
+ }
25
+ var NUMBER_COL = (v) => v ? `#${v}` : "\u2014";
26
+ function buildInvoiceCommand(deps) {
27
+ const { http } = deps;
28
+ const cli = deps.cliName ?? "cli";
29
+ const listInvoices = async (opts) => {
30
+ const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : "";
31
+ const res = await http.get(`/v1/invoices${q}`).catch(die);
32
+ printOutput(res.invoices, opts.output, (wide) => {
33
+ table(res.invoices, [
34
+ { key: "shortId", label: "ID" },
35
+ { key: "number", label: "NO", fmt: NUMBER_COL },
36
+ { key: "status", label: "STATUS" },
37
+ { key: "customerName", label: "CUSTOMER", fmt: (v, r) => v ?? r.customerId },
38
+ { key: "totalCents", label: "TOTAL", fmt: (v, r) => fmtMoney(v, r.currency) },
39
+ { key: "balanceCents", label: "BALANCE", fmt: (v, r) => fmtMoney(v, r.currency) },
40
+ { key: "createdAt", label: "CREATED", wide: true, fmt: (v) => fmtDate(v) },
41
+ { key: "id", label: "FULL ID", wide: true }
42
+ ], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` });
43
+ summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? "s" : ""}`);
44
+ }, "id");
45
+ };
46
+ const cmd = new Command("invoices").aliases(["inv", "invoice"]).description("Manage invoices (org-scoped \u2014 run `use <org>` first)").option(...outputOption()).option("--status <status>", "Filter: draft | finalized | paid | void").action(listInvoices);
47
+ cmd.addCommand(
48
+ new Command("ls").description("List invoices (alias of the bare command)").option(...outputOption()).option("--status <status>", "Filter by status").action(function() {
49
+ const self = this.opts();
50
+ const parent = this.parent?.opts() ?? {};
51
+ return listInvoices({
52
+ output: self.output && self.output !== "table" ? self.output : parent.output ?? "table",
53
+ status: self.status ?? parent.status
54
+ });
55
+ })
56
+ );
57
+ cmd.addCommand(
58
+ new Command("create").description("Create a draft invoice").requiredOption("--customer <ref>", "Customer id, short_id, or external_id").requiredOption("--currency <cur>", "ISO-4217 currency (e.g. USD)").requiredOption("--line <spec...>", 'Line "description|qty|unitPrice" (repeatable)').action(async (opts) => {
59
+ const lines = opts.line.map(parseLine);
60
+ const res = await http.post("/v1/invoices", {
61
+ customerId: opts.customer,
62
+ currency: opts.currency,
63
+ lines
64
+ }).catch(die);
65
+ success(`Draft invoice created for ${res.invoice.customerName ?? res.invoice.customerId}`);
66
+ kv([["id", res.invoice.shortId], ["status", res.invoice.status], ["total", fmtMoney(res.invoice.totalCents, res.invoice.currency)]]);
67
+ })
68
+ );
69
+ cmd.addCommand(
70
+ new Command("get").argument("<ref>", "id or short_id").description("Show invoice details (lines, totals, balance)").option(...outputOption()).action(async (ref, opts) => {
71
+ const res = await http.get(`/v1/invoices/${ref}`).catch(die);
72
+ const inv = res.invoice;
73
+ const cur = String(inv["currency"]);
74
+ printOutput(inv, opts.output, () => {
75
+ kv([
76
+ ["id", String(inv["shortId"])],
77
+ ["number", inv["number"] ? `#${inv["number"]}` : "\u2014 (draft)"],
78
+ ["status", String(inv["status"])],
79
+ ["customer", String(inv["customerName"] ?? inv["customerId"])],
80
+ ["issued", inv["issuedAt"] ? fmtDate(inv["issuedAt"]) : "\u2014"],
81
+ ["due", inv["dueAt"] ? fmtDate(inv["dueAt"]) : "\u2014"]
82
+ ]);
83
+ const lines = inv["lines"] ?? [];
84
+ if (lines.length) {
85
+ console.log(` ${clr.dim}\u2500\u2500 lines \u2500\u2500${clr.reset}`);
86
+ table(lines, [
87
+ { key: "description", label: "DESCRIPTION" },
88
+ { key: "quantity", label: "QTY" },
89
+ { key: "unitPriceCents", label: "UNIT", fmt: (v) => fmtMoney(v, cur) },
90
+ { key: "amountCents", label: "AMOUNT", fmt: (v) => fmtMoney(v, cur) }
91
+ ]);
92
+ }
93
+ kv([
94
+ ["subtotal", fmtMoney(inv["subtotalCents"], cur)],
95
+ ["total", fmtMoney(inv["totalCents"], cur)],
96
+ ["paid", fmtMoney(inv["amountPaidCents"], cur)],
97
+ ["balance", fmtMoney(inv["balanceCents"], cur)],
98
+ ["full_id", String(inv["id"])]
99
+ ]);
100
+ }, "id");
101
+ })
102
+ );
103
+ cmd.addCommand(
104
+ new Command("update").argument("<ref>").description("Edit a DRAFT invoice (replaces lines / customer)").option("--customer <ref>", "New customer ref").option("--line <spec...>", 'Replace lines: "description|qty|unitPrice" (repeatable)').action(async (ref, opts) => {
105
+ const body = {};
106
+ if (opts.customer !== void 0) body["customerId"] = opts.customer;
107
+ if (opts.line !== void 0) body["lines"] = opts.line.map(parseLine);
108
+ if (!Object.keys(body).length) fatal("Provide --customer and/or --line");
109
+ const res = await http.patch(`/v1/invoices/${ref}`, body).catch(die);
110
+ success("Draft updated.");
111
+ kv([["id", res.invoice.shortId], ["total", fmtMoney(res.invoice.totalCents, res.invoice.currency)]]);
112
+ })
113
+ );
114
+ cmd.addCommand(
115
+ new Command("finalize").argument("<ref>").description("Finalize a draft \u2014 assigns a number, freezes it (immutable)").option("--due <date>", "Due date YYYY-MM-DD").action(async (ref, opts) => {
116
+ const body = {};
117
+ if (opts.due) {
118
+ const ms = Date.parse(opts.due);
119
+ if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`);
120
+ body["dueAt"] = ms;
121
+ }
122
+ const res = await http.post(`/v1/invoices/${ref}/finalize`, body).catch(die);
123
+ success(`Invoice finalized: #${res.invoice.number}`);
124
+ kv([["id", res.invoice.shortId], ["number", `#${res.invoice.number}`], ["total", fmtMoney(res.invoice.totalCents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balanceCents, res.invoice.currency)]]);
125
+ })
126
+ );
127
+ cmd.addCommand(
128
+ new Command("pay").argument("<ref>").description("Record a payment against a finalized invoice").requiredOption("--amount <amount>", "Amount, e.g. 150.00").option("--method <method>", "e.g. bank, cash, card").option("--ref <reference>", "External payment reference").action(async (ref, opts) => {
129
+ const res = await http.post(`/v1/invoices/${ref}/payments`, {
130
+ amountCents: toCents(opts.amount),
131
+ ...opts.method ? { method: opts.method } : {},
132
+ ...opts.ref ? { reference: opts.ref } : {}
133
+ }).catch(die);
134
+ success(`Payment recorded. Invoice is now ${res.invoice.status}.`);
135
+ kv([["id", res.invoice.shortId], ["paid", fmtMoney(res.invoice.amountPaidCents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balanceCents, res.invoice.currency)]]);
136
+ })
137
+ );
138
+ cmd.addCommand(
139
+ new Command("void").argument("<ref>").description("Void a finalized invoice").option("--reason <reason>", "Reason").action(async (ref, opts) => {
140
+ const res = await http.post(`/v1/invoices/${ref}/void`, { reason: opts.reason ?? "" }).catch(die);
141
+ success(`Invoice voided: ${res.invoice.shortId}`);
142
+ })
143
+ );
144
+ cmd.addCommand(
145
+ new Command("payments").alias("transactions").argument("[ref]", "invoice id/short_id (omit for all org transactions)").description("List payments / transactions (the money ledger)").option(...outputOption()).action(async (ref, opts) => {
146
+ const path = ref ? `/v1/invoices/${ref}/payments` : "/v1/transactions";
147
+ const res = await http.get(path).catch(die);
148
+ printOutput(res.transactions, opts.output, (wide) => {
149
+ table(res.transactions, [
150
+ { key: "createdAt", label: "DATE", fmt: (v) => fmtDate(v) },
151
+ { key: "invoiceNumber", label: "INVOICE", fmt: (v) => v ? `#${v}` : "\u2014" },
152
+ { key: "customerName", label: "CUSTOMER", fmt: (v, r) => v ?? r.customerId },
153
+ { key: "kind", label: "KIND" },
154
+ { key: "amountCents", label: "AMOUNT", fmt: (v, r) => fmtMoney(v, r.currency) },
155
+ { key: "method", label: "METHOD", fmt: (v) => v ?? "" },
156
+ { key: "reference", label: "REF", wide: true, fmt: (v) => v ?? "" },
157
+ { key: "id", label: "TXN ID", wide: true }
158
+ ], { wide, emptyHint: "No transactions yet." });
159
+ summary(`${res.transactions.length} transaction${res.transactions.length !== 1 ? "s" : ""}`);
160
+ }, "id");
161
+ })
162
+ );
163
+ return cmd;
164
+ }
165
+ export {
166
+ buildInvoiceCommand
167
+ };
@@ -0,0 +1,169 @@
1
+ import { InvoiceStatus } from './events.js';
2
+ import '@baseworks/foldbase';
3
+ import 'zod';
4
+
5
+ interface InvoiceRow {
6
+ id: string;
7
+ short_id: string;
8
+ number: number;
9
+ status: InvoiceStatus;
10
+ customer_id: string;
11
+ customer_name: string;
12
+ currency: string;
13
+ lines: string;
14
+ subtotal_cents: number;
15
+ total_cents: number;
16
+ amount_paid_cents: number;
17
+ issued_at: number;
18
+ due_at: number;
19
+ created_at: number;
20
+ updated_at: number;
21
+ }
22
+ interface InvoiceLine {
23
+ description: string;
24
+ /** May be fractional (e.g. hours). */
25
+ quantity: number;
26
+ /** Unit price in integer cents. */
27
+ unitPriceCents: number;
28
+ /** quantity × unitPriceCents, rounded to cents. */
29
+ amountCents: number;
30
+ /** Optional catalog product reference. */
31
+ productId: string | null;
32
+ }
33
+ interface Invoice {
34
+ id: string;
35
+ shortId: string;
36
+ /** Per-org invoice number; `null` while draft. */
37
+ number: number | null;
38
+ status: InvoiceStatus;
39
+ customerId: string;
40
+ customerName: string | null;
41
+ currency: string;
42
+ lines: InvoiceLine[];
43
+ subtotalCents: number;
44
+ totalCents: number;
45
+ amountPaidCents: number;
46
+ /** totalCents − amountPaidCents (0 for draft/void semantics aside). */
47
+ balanceCents: number;
48
+ issuedAt: number | null;
49
+ dueAt: number | null;
50
+ createdAt: number;
51
+ updatedAt: number;
52
+ }
53
+ /** A line as supplied by the caller (amountCents is computed server-side). */
54
+ interface InvoiceLineInput {
55
+ description: string;
56
+ quantity: number;
57
+ unitPriceCents: number;
58
+ productId?: string;
59
+ }
60
+ interface CreateInvoiceInput {
61
+ customerId: string;
62
+ currency: string;
63
+ lines: InvoiceLineInput[];
64
+ }
65
+ interface UpdateInvoiceInput {
66
+ customerId?: string;
67
+ lines?: InvoiceLineInput[];
68
+ }
69
+ interface FinalizeInvoiceInput {
70
+ /** Epoch millis; defaults to now server-side. */
71
+ issuedAt?: number;
72
+ /** Epoch millis; 0/omitted = no due date. */
73
+ dueAt?: number;
74
+ }
75
+ interface RecordPaymentInput {
76
+ amountCents: number;
77
+ method?: string;
78
+ reference?: string;
79
+ }
80
+ interface TransactionRow {
81
+ id: string;
82
+ invoice_id: string;
83
+ invoice_number: number;
84
+ customer_id: string;
85
+ customer_name: string;
86
+ kind: string;
87
+ amount_cents: number;
88
+ currency: string;
89
+ method: string;
90
+ reference: string;
91
+ created_at: number;
92
+ updated_at: number;
93
+ }
94
+ interface Transaction {
95
+ id: string;
96
+ invoiceId: string;
97
+ invoiceNumber: number;
98
+ customerId: string;
99
+ customerName: string | null;
100
+ kind: string;
101
+ amountCents: number;
102
+ currency: string;
103
+ method: string | null;
104
+ reference: string | null;
105
+ createdAt: number;
106
+ }
107
+
108
+ interface InvoiceClientOptions {
109
+ /** Base URL of invoice-service (resolved by the SDK, e.g. INVOICE_SERVICE_URL). */
110
+ baseUrl: string;
111
+ /** Bearer token — the caller's identity JWT. */
112
+ token?: string;
113
+ /** Active org id — sent as X-Org-Id (invoices are org-scoped, tenant = org). */
114
+ orgId?: string;
115
+ /** Injectable fetch (tests / non-global environments). */
116
+ fetch?: typeof fetch;
117
+ }
118
+ /** Thrown on any non-2xx response from invoice-service. */
119
+ declare class InvoiceError extends Error {
120
+ readonly status: number;
121
+ readonly code: string;
122
+ constructor(status: number, code: string, message?: string);
123
+ }
124
+ /** Minimal ApiClient shape — structurally compatible with @baseworks/cli. */
125
+ interface HttpClient {
126
+ api<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
127
+ get<T>(path: string, headers?: Record<string, string>): Promise<T>;
128
+ post<T>(path: string, body: unknown, headers?: Record<string, string>): Promise<T>;
129
+ patch<T>(path: string, body: unknown, headers?: Record<string, string>): Promise<T>;
130
+ del<T>(path: string, headers?: Record<string, string>): Promise<T>;
131
+ }
132
+ /**
133
+ * Typed HTTP client for invoice-service. Thin wrapper over the REST surface; the
134
+ * service validates + owns the ledger math. Every call carries the org id
135
+ * (X-Org-Id) — invoices are per-org, and the identity JWT is org-less (ADR-009).
136
+ */
137
+ declare class InvoiceClient {
138
+ private readonly opts;
139
+ private readonly baseUrl;
140
+ private readonly fetchImpl;
141
+ constructor(opts: InvoiceClientOptions);
142
+ withOrg(orgId: string): InvoiceClient;
143
+ private headers;
144
+ api<T>(method: string, path: string, body?: unknown, extra?: Record<string, string>): Promise<T>;
145
+ /** Generic ApiClient (get/post/patch/del) — used by the CLI plugin. */
146
+ get http(): HttpClient;
147
+ list(opts?: {
148
+ limit?: number;
149
+ offset?: number;
150
+ status?: string;
151
+ }): Promise<Invoice[]>;
152
+ get(ref: string): Promise<Invoice>;
153
+ create(input: CreateInvoiceInput): Promise<Invoice>;
154
+ update(ref: string, input: UpdateInvoiceInput): Promise<Invoice>;
155
+ finalize(ref: string, input?: FinalizeInvoiceInput): Promise<Invoice>;
156
+ recordPayment(ref: string, input: RecordPaymentInput): Promise<Invoice>;
157
+ void(ref: string, reason?: string): Promise<Invoice>;
158
+ /** All transactions for the org, newest first. */
159
+ transactions(opts?: {
160
+ limit?: number;
161
+ offset?: number;
162
+ }): Promise<Transaction[]>;
163
+ /** Transactions recorded against one invoice. */
164
+ invoiceTransactions(ref: string): Promise<Transaction[]>;
165
+ }
166
+ /** Factory used by the SDK capability registry. */
167
+ declare function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient;
168
+
169
+ export { type CreateInvoiceInput, type FinalizeInvoiceInput, type HttpClient, type Invoice, InvoiceClient, type InvoiceClientOptions, InvoiceError, type InvoiceLine, type InvoiceLineInput, type InvoiceRow, InvoiceStatus, type RecordPaymentInput, type Transaction, type TransactionRow, type UpdateInvoiceInput, createInvoiceClient };
package/dist/client.js ADDED
@@ -0,0 +1,115 @@
1
+ // src/client.ts
2
+ var InvoiceError = class extends Error {
3
+ constructor(status, code, message) {
4
+ super(message ?? code);
5
+ this.status = status;
6
+ this.code = code;
7
+ this.name = "InvoiceError";
8
+ }
9
+ status;
10
+ code;
11
+ };
12
+ var InvoiceClient = class _InvoiceClient {
13
+ constructor(opts) {
14
+ this.opts = opts;
15
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
16
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
17
+ }
18
+ opts;
19
+ baseUrl;
20
+ fetchImpl;
21
+ withOrg(orgId) {
22
+ return new _InvoiceClient({ ...this.opts, orgId });
23
+ }
24
+ headers(json, extra = {}) {
25
+ const h = {};
26
+ if (json) h["Content-Type"] = "application/json";
27
+ if (this.opts.token) h["Authorization"] = `Bearer ${this.opts.token}`;
28
+ if (this.opts.orgId) h["X-Org-Id"] = this.opts.orgId;
29
+ return { ...h, ...extra };
30
+ }
31
+ async api(method, path, body, extra = {}) {
32
+ const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
33
+ method,
34
+ headers: this.headers(body !== void 0, extra),
35
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
36
+ });
37
+ if (res.status === 204) return null;
38
+ const text = await res.text();
39
+ const data = text ? JSON.parse(text) : void 0;
40
+ if (!res.ok) {
41
+ const e = data ?? {};
42
+ const code = typeof e.error === "string" ? e.error : e.error?.code ?? "error";
43
+ const msg = typeof e.error === "object" ? e.error?.message : e.message;
44
+ throw new InvoiceError(res.status, code, msg);
45
+ }
46
+ return data;
47
+ }
48
+ /** Generic ApiClient (get/post/patch/del) — used by the CLI plugin. */
49
+ get http() {
50
+ return {
51
+ api: this.api.bind(this),
52
+ get: (p, h) => this.api("GET", p, void 0, h),
53
+ post: (p, b, h) => this.api("POST", p, b, h),
54
+ patch: (p, b, h) => this.api("PATCH", p, b, h),
55
+ del: (p, h) => this.api("DELETE", p, void 0, h)
56
+ };
57
+ }
58
+ // ── invoices ──────────────────────────────────────────────────────────────
59
+ async list(opts = {}) {
60
+ const q = new URLSearchParams();
61
+ if (opts.limit !== void 0) q.set("limit", String(opts.limit));
62
+ if (opts.offset !== void 0) q.set("offset", String(opts.offset));
63
+ if (opts.status) q.set("status", opts.status);
64
+ const qs = q.toString();
65
+ const { invoices } = await this.api("GET", `/v1/invoices${qs ? `?${qs}` : ""}`);
66
+ return invoices;
67
+ }
68
+ async get(ref) {
69
+ const { invoice } = await this.api("GET", `/v1/invoices/${ref}`);
70
+ return invoice;
71
+ }
72
+ async create(input) {
73
+ const { invoice } = await this.api("POST", "/v1/invoices", input);
74
+ return invoice;
75
+ }
76
+ async update(ref, input) {
77
+ const { invoice } = await this.api("PATCH", `/v1/invoices/${ref}`, input);
78
+ return invoice;
79
+ }
80
+ async finalize(ref, input = {}) {
81
+ const { invoice } = await this.api("POST", `/v1/invoices/${ref}/finalize`, input);
82
+ return invoice;
83
+ }
84
+ async recordPayment(ref, input) {
85
+ const { invoice } = await this.api("POST", `/v1/invoices/${ref}/payments`, input);
86
+ return invoice;
87
+ }
88
+ async void(ref, reason) {
89
+ const { invoice } = await this.api("POST", `/v1/invoices/${ref}/void`, { reason: reason ?? "" });
90
+ return invoice;
91
+ }
92
+ // ── transactions (the payment ledger) ───────────────────────────────────────
93
+ /** All transactions for the org, newest first. */
94
+ async transactions(opts = {}) {
95
+ const q = new URLSearchParams();
96
+ if (opts.limit !== void 0) q.set("limit", String(opts.limit));
97
+ if (opts.offset !== void 0) q.set("offset", String(opts.offset));
98
+ const qs = q.toString();
99
+ const { transactions } = await this.api("GET", `/v1/transactions${qs ? `?${qs}` : ""}`);
100
+ return transactions;
101
+ }
102
+ /** Transactions recorded against one invoice. */
103
+ async invoiceTransactions(ref) {
104
+ const { transactions } = await this.api("GET", `/v1/invoices/${ref}/payments`);
105
+ return transactions;
106
+ }
107
+ };
108
+ function createInvoiceClient(opts) {
109
+ return new InvoiceClient(opts);
110
+ }
111
+ export {
112
+ InvoiceClient,
113
+ InvoiceError,
114
+ createInvoiceClient
115
+ };