@baseworks/invoice 0.1.1 → 1.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 +81 -14
- package/dist/chunk-335MPCTE.js +133 -0
- package/dist/cli.js +58 -42
- package/dist/client.d.ts +216 -29
- package/dist/client.js +99 -23
- package/dist/events.d.ts +180 -69
- package/dist/events.js +5 -1
- package/dist/graphql.d.ts +22 -0
- package/dist/graphql.js +17 -2
- package/dist/mcp.d.ts +13 -0
- package/dist/mcp.js +146 -0
- package/dist/projections.js +55 -20
- package/package.json +14 -3
- package/src/__tests__/cli.test.ts +43 -25
- package/src/__tests__/client.test.ts +147 -0
- package/src/__tests__/dts-exports.test.ts +75 -0
- package/src/__tests__/mcp.test.ts +163 -0
- package/src/cli.ts +85 -60
- package/src/client.ts +78 -26
- package/src/compat.ts +61 -0
- package/src/events.ts +72 -22
- package/src/graphql.ts +17 -2
- package/src/mcp.ts +191 -0
- package/src/projections.ts +54 -19
- package/src/types.ts +208 -22
- package/dist/chunk-7P7ARN3X.js +0 -78
package/README.md
CHANGED
|
@@ -10,35 +10,38 @@ pnpm add @baseworks/invoice
|
|
|
10
10
|
|
|
11
11
|
## Client
|
|
12
12
|
|
|
13
|
-
Invoices are **org-scoped** (`X-Org-Id` +
|
|
13
|
+
Invoices are **org-scoped** (`X-Org-Id` + token). **Money is integer
|
|
14
14
|
cents** throughout. Status machine: `draft → finalized → paid | void`. A finalized
|
|
15
15
|
invoice is immutable (only payments / void follow).
|
|
16
16
|
|
|
17
|
+
Every field is **snake_case** (since 0.3.0, as the service speaks): options `base_url`, `org_id`; inputs and answers
|
|
18
|
+
`customer_id`, `unit_price_cents`, `total_cents`, `short_id`, …
|
|
19
|
+
|
|
17
20
|
```ts
|
|
18
21
|
import { createInvoiceClient } from '@baseworks/invoice'
|
|
19
22
|
|
|
20
23
|
const invoices = createInvoiceClient({
|
|
21
|
-
|
|
22
|
-
token:
|
|
23
|
-
|
|
24
|
+
base_url: process.env.INVOICE_SERVICE_URL!,
|
|
25
|
+
token: realmToken, // a service forwards its request's `c.get('realm_token')`, never the raw Authorization header
|
|
26
|
+
org_id: activeOrgId,
|
|
24
27
|
})
|
|
25
28
|
|
|
26
|
-
// 1. draft —
|
|
29
|
+
// 1. draft — customer_id is a customers-service ref (validated + name snapshotted)
|
|
27
30
|
const draft = await invoices.create({
|
|
28
|
-
|
|
31
|
+
customer_id: 'acct-42',
|
|
29
32
|
currency: 'USD',
|
|
30
33
|
lines: [
|
|
31
|
-
{ description: 'Consulting', quantity: 10,
|
|
32
|
-
{ description: 'Setup', quantity: 1,
|
|
34
|
+
{ description: 'Consulting', quantity: 10, unit_price_cents: 15000 }, // $150.00 × 10
|
|
35
|
+
{ description: 'Setup', quantity: 1, unit_price_cents: 50000 },
|
|
33
36
|
],
|
|
34
37
|
})
|
|
35
38
|
|
|
36
39
|
// 2. finalize — assigns a per-org number, freezes lines + totals
|
|
37
|
-
const final = await invoices.finalize(draft.id, {
|
|
40
|
+
const final = await invoices.finalize(draft.id, { due_at: Date.parse('2026-08-01') })
|
|
38
41
|
|
|
39
42
|
// 3. record payments — balance can't go below zero (overpayment is rejected)
|
|
40
|
-
await invoices.recordPayment(final.id, {
|
|
41
|
-
await invoices.recordPayment(final.id, {
|
|
43
|
+
await invoices.recordPayment(final.id, { amount_cents: 100000, method: 'bank', reference: 'TXN-1' })
|
|
44
|
+
await invoices.recordPayment(final.id, { amount_cents: 100000 }) // → status 'paid'
|
|
42
45
|
|
|
43
46
|
// 4. the ledger — one row per money movement
|
|
44
47
|
await invoices.transactions() // all org transactions
|
|
@@ -49,8 +52,50 @@ await invoices.get(final.id)
|
|
|
49
52
|
await invoices.void(final.id, 'issued in error')
|
|
50
53
|
```
|
|
51
54
|
|
|
52
|
-
Errors throw `InvoiceError` (`.status`, `.code`): `
|
|
53
|
-
invoice), `409 overpayment` / `409 already_paid`, `404 customer_not_found`.
|
|
55
|
+
Errors throw `InvoiceError` (`.status`, `.code`): `403 forbidden` (with the missing permission, e.g. `invoice.write`),
|
|
56
|
+
`409 not_draft` (edit a finalized invoice), `409 overpayment` / `409 already_paid`, `404 customer_not_found`.
|
|
57
|
+
|
|
58
|
+
### 1.1.0: sources, payment status, filters, fiscal state
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// what is still owed, and what is late
|
|
62
|
+
await invoices.list({ payment_status: ['unpaid', 'partially_paid'] })
|
|
63
|
+
await invoices.list({ overdue: true, source: 'local', customer_id: 'cus_1' }) // filters combine
|
|
64
|
+
|
|
65
|
+
const inv = await invoices.get(id) // inv.payment_status, inv.source, inv.external_refs, inv.metadata, inv.fiscal, inv.payments
|
|
66
|
+
|
|
67
|
+
// a provider's document, whole: creates or replaces by external_ref (system + id); `created`, `stale`
|
|
68
|
+
await invoices.mirror({ source: 'stripe', external_ref: { system: 'stripe', id: 'in_…', number, url, pdf_url, account_id, livemode },
|
|
69
|
+
customer_id, currency, lines, subtotal_cents, tax_cents, total_cents, status: 'finalized', issued_at, provider_updated_at })
|
|
70
|
+
|
|
71
|
+
await invoices.recordPayment(id, { amount_cents: 990, payment_id: 'pay_…' }) // the same payment_id twice records it once
|
|
72
|
+
await invoices.setFiscal(id, { status: 'submitted', system: 'gib', external_id }) // needs invoice.fiscal_update
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The CLI lists with `--payment-status unpaid,partially_paid`, `--overdue`, `--source`, `--fiscal-status`, `--customer-id`, and shows
|
|
76
|
+
a PAYMENT column. A mirror (`source: stripe | manual`) is read-only except through `mirror`: `update`, `finalize` and `void`
|
|
77
|
+
throw `InvoiceError` `409 mirrored`.
|
|
78
|
+
|
|
79
|
+
### Deprecated names
|
|
80
|
+
|
|
81
|
+
Until 0.3.0 the client and the service spoke camelCase. A caller that has not moved (billing-service, stripe-service, apps)
|
|
82
|
+
still builds and runs: **every old name is kept as a deprecated alias** and goes when the last caller has moved.
|
|
83
|
+
|
|
84
|
+
| | Old | Now |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| options | `baseUrl`, `orgId` | `base_url`, `org_id` |
|
|
87
|
+
| invoice | `shortId`, `customerId`, `customerName`, `subtotalCents`, `totalCents`, `amountPaidCents`, `balanceCents`, `issuedAt`, `dueAt`, `createdAt`, `updatedAt` | `short_id`, `customer_id`, `customer_name`, `subtotal_cents`, `total_cents`, `amount_paid_cents`, `balance_cents`, `issued_at`, `due_at`, `created_at`, `updated_at` |
|
|
88
|
+
| line | `unitPriceCents`, `amountCents`, `productId` | `unit_price_cents`, `amount_cents`, `product_id` |
|
|
89
|
+
| transaction | `invoiceId`, `invoiceNumber`, `customerId`, `customerName`, `amountCents`, `createdAt` | `invoice_id`, `invoice_number`, `customer_id`, `customer_name`, `amount_cents`, `created_at` |
|
|
90
|
+
| inputs | `customerId`, `unitPriceCents`, `productId`, `issuedAt`, `dueAt`, `amountCents` | `customer_id`, `unit_price_cents`, `product_id`, `issued_at`, `due_at`, `amount_cents` |
|
|
91
|
+
|
|
92
|
+
On **answers** the old names are readable properties (`invoice.totalCents`) but not data: they are non-enumerable getters of
|
|
93
|
+
the snake_case field, so `JSON.stringify`, spreading and `toEqual` see the snake_case object only. On **inputs** the old names
|
|
94
|
+
are renamed to snake_case before they are sent, and the new name wins when both are given. The types carry the aliases
|
|
95
|
+
marked `@deprecated`. The method names (`recordPayment`, `invoiceTransactions`, …) are unchanged. The GraphQL module's schema is
|
|
96
|
+
camelCase, as that contract's own, and resolves from the snake_case data.
|
|
97
|
+
|
|
98
|
+
The service needs **invoice-service 0.3.0**: an older service answers camelCase and this client no longer reads it.
|
|
54
99
|
|
|
55
100
|
## CLI plugin
|
|
56
101
|
|
|
@@ -58,12 +103,33 @@ invoice), `409 overpayment` / `409 already_paid`, `404 customer_not_found`.
|
|
|
58
103
|
import { buildInvoiceCommand } from '@baseworks/invoice/cli'
|
|
59
104
|
|
|
60
105
|
program.addCommand(buildInvoiceCommand({ http, cliName: 'dtab' }))
|
|
106
|
+
// the CLI reads and sends the service's snake_case, so it needs invoice-service 0.3.0
|
|
61
107
|
// dtab invoices | inv list (--status) · create · get · update · finalize · pay · void
|
|
62
108
|
// dtab invoices create --customer <ref> --currency USD --line "Consulting|10|150.00"
|
|
63
109
|
// dtab invoices pay <ref> --amount 150.00 --method bank
|
|
64
110
|
// dtab invoices payments [<ref>] (the transaction ledger)
|
|
65
111
|
```
|
|
66
112
|
|
|
113
|
+
## MCP tools
|
|
114
|
+
|
|
115
|
+
`@baseworks/invoice/mcp` is the tool set a model uses, for an MCP server built with `@baseworks/mcp` (`composeTools(invoiceTools())`;
|
|
116
|
+
`ctx.clients.invoice` is an `InvoiceClient` built from the realm token). `@baseworks/mcp` is a dependency, the MCP SDK an
|
|
117
|
+
optional peer.
|
|
118
|
+
|
|
119
|
+
| Tool | Access | Permission |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `invoice_list`, `invoice_get`, `invoice_transactions` | read | `invoice.read` |
|
|
122
|
+
| `invoice_create`, `invoice_update` (drafts only) | write | `invoice.write` |
|
|
123
|
+
| `invoice_finalize` (irreversible) | write | `invoice.finalize` |
|
|
124
|
+
| `invoice_record_payment` | write | `invoice.record_payment` |
|
|
125
|
+
|
|
126
|
+
`invoice_list` takes the same filters as the client; `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension.
|
|
127
|
+
| `invoice_void` (irreversible) | write | `invoice.void` |
|
|
128
|
+
|
|
129
|
+
A tool is a thin wrapper over the same client, so it can never do what the API would refuse, and `permission` is the name
|
|
130
|
+
the service registered with org-service, used to hide a tool from somebody who may not use it. Money is integer cents; a
|
|
131
|
+
finalized invoice is never edited.
|
|
132
|
+
|
|
67
133
|
## Service integration
|
|
68
134
|
|
|
69
135
|
```ts
|
|
@@ -72,7 +138,8 @@ import { InvoiceEvents, TransactionEvents } from '@baseworks/invoice/events'
|
|
|
72
138
|
```
|
|
73
139
|
|
|
74
140
|
Projections `invoices` → `read_invoices`, `transactions` → `read_transactions`
|
|
75
|
-
(one row per payment). Tenant = org id.
|
|
141
|
+
(one row per payment). Tenant = org id. Event payloads are snake_case since 0.3.0; older camelCase events still fold
|
|
142
|
+
(foldbase reads a snake_case path from a camelCase payload).
|
|
76
143
|
|
|
77
144
|
## See also
|
|
78
145
|
|
|
@@ -0,0 +1,133 @@
|
|
|
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
|
+
customer_id: z.string().min(1),
|
|
10
|
+
customer_name: 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, unit_price_cents, amount_cents, product_id }
|
|
15
|
+
subtotal_cents: z.number().int(),
|
|
16
|
+
total_cents: z.number().int(),
|
|
17
|
+
short_id: z.string().min(1),
|
|
18
|
+
// 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
|
|
19
|
+
source: z.string().optional(),
|
|
20
|
+
metadata: z.string().optional(),
|
|
21
|
+
// JSON object, serialized
|
|
22
|
+
at: z.number().int()
|
|
23
|
+
}),
|
|
24
|
+
// Draft edited (customer / lines). Only valid while status = draft.
|
|
25
|
+
InvoiceUpdated: z.object({
|
|
26
|
+
customer_id: z.string().min(1),
|
|
27
|
+
customer_name: z.string(),
|
|
28
|
+
lines: z.string(),
|
|
29
|
+
subtotal_cents: z.number().int(),
|
|
30
|
+
total_cents: z.number().int(),
|
|
31
|
+
metadata: z.string().optional(),
|
|
32
|
+
// 1.1.0
|
|
33
|
+
at: z.number().int()
|
|
34
|
+
}),
|
|
35
|
+
// Finalize: assign the per-org number, freeze lines + totals, set issue/due.
|
|
36
|
+
InvoiceFinalized: z.object({
|
|
37
|
+
number: z.number().int(),
|
|
38
|
+
lines: z.string(),
|
|
39
|
+
subtotal_cents: z.number().int(),
|
|
40
|
+
total_cents: z.number().int(),
|
|
41
|
+
issued_at: z.number().int(),
|
|
42
|
+
due_at: z.number().int(),
|
|
43
|
+
// 0 = no due date
|
|
44
|
+
at: z.number().int()
|
|
45
|
+
}),
|
|
46
|
+
// A payment applied to a finalized invoice. `amount_paid_cents` is the new running
|
|
47
|
+
// total; `status` is the resulting status ('paid' when balance ≤ 0, else
|
|
48
|
+
// 'finalized') — both computed by the store.
|
|
49
|
+
PaymentRecorded: z.object({
|
|
50
|
+
amount_cents: z.number().int(),
|
|
51
|
+
amount_paid_cents: z.number().int(),
|
|
52
|
+
status: InvoiceStatus,
|
|
53
|
+
method: z.string(),
|
|
54
|
+
reference: z.string(),
|
|
55
|
+
payment_id: z.string().optional(),
|
|
56
|
+
// 1.1.0: the pay record this settles; the idempotency key when present
|
|
57
|
+
at: z.number().int()
|
|
58
|
+
}),
|
|
59
|
+
InvoiceVoided: z.object({
|
|
60
|
+
reason: z.string(),
|
|
61
|
+
at: z.number().int()
|
|
62
|
+
}),
|
|
63
|
+
// 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
|
|
64
|
+
// first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
|
|
65
|
+
InvoiceMirrored: z.object({
|
|
66
|
+
source: z.string(),
|
|
67
|
+
// 'stripe' | 'manual'
|
|
68
|
+
mirror_key: z.string().min(1),
|
|
69
|
+
// `${system}:${external_id}`
|
|
70
|
+
external_refs: z.string(),
|
|
71
|
+
// JSON array, serialized
|
|
72
|
+
customer_id: z.string().min(1),
|
|
73
|
+
customer_name: z.string(),
|
|
74
|
+
currency: z.string().length(3),
|
|
75
|
+
lines: z.string(),
|
|
76
|
+
subtotal_cents: z.number().int(),
|
|
77
|
+
tax_cents: z.number().int(),
|
|
78
|
+
total_cents: z.number().int(),
|
|
79
|
+
amount_paid_cents: z.number().int(),
|
|
80
|
+
// from the payment entries, not from the provider
|
|
81
|
+
status: InvoiceStatus,
|
|
82
|
+
issued_at: z.number().int(),
|
|
83
|
+
due_at: z.number().int(),
|
|
84
|
+
// 0 = none
|
|
85
|
+
paid_at: z.number().int(),
|
|
86
|
+
// 0 = none
|
|
87
|
+
voided_at: z.number().int(),
|
|
88
|
+
// 0 = none
|
|
89
|
+
provider_updated_at: z.number().int(),
|
|
90
|
+
metadata: z.string(),
|
|
91
|
+
short_id: z.string().min(1),
|
|
92
|
+
created_at: z.number().int(),
|
|
93
|
+
at: z.number().int()
|
|
94
|
+
}),
|
|
95
|
+
// 1.1.0. Where the invoice stands with a tax system. Only changed through `invoice.fiscal_update`.
|
|
96
|
+
InvoiceFiscalChanged: z.object({
|
|
97
|
+
status: z.string(),
|
|
98
|
+
// FISCAL_STATUSES
|
|
99
|
+
system: z.string(),
|
|
100
|
+
external_id: z.string(),
|
|
101
|
+
message: z.string(),
|
|
102
|
+
at: z.number().int()
|
|
103
|
+
})
|
|
104
|
+
});
|
|
105
|
+
var FISCAL_STATUSES = ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
|
|
106
|
+
var INVOICE_SOURCES = ["local", "stripe", "manual"];
|
|
107
|
+
var TransactionKind = z.enum(["payment", "refund", "adjustment"]);
|
|
108
|
+
var TransactionEvents = defineAggregate("transaction", {
|
|
109
|
+
TransactionRecorded: z.object({
|
|
110
|
+
invoice_id: z.string().min(1),
|
|
111
|
+
invoice_number: z.number().int(),
|
|
112
|
+
// the invoice's number at the time
|
|
113
|
+
customer_id: z.string(),
|
|
114
|
+
customer_name: z.string(),
|
|
115
|
+
kind: TransactionKind,
|
|
116
|
+
amount_cents: z.number().int(),
|
|
117
|
+
currency: z.string().length(3),
|
|
118
|
+
method: z.string(),
|
|
119
|
+
reference: z.string(),
|
|
120
|
+
payment_id: z.string().optional(),
|
|
121
|
+
// 1.1.0
|
|
122
|
+
at: z.number().int()
|
|
123
|
+
})
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
export {
|
|
127
|
+
InvoiceStatus,
|
|
128
|
+
InvoiceEvents,
|
|
129
|
+
FISCAL_STATUSES,
|
|
130
|
+
INVOICE_SOURCES,
|
|
131
|
+
TransactionKind,
|
|
132
|
+
TransactionEvents
|
|
133
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -20,65 +20,81 @@ function parseLine(spec) {
|
|
|
20
20
|
const quantity = Number(parts[1]);
|
|
21
21
|
if (!description) fatal(`--line description is empty in '${spec}'`);
|
|
22
22
|
if (!Number.isFinite(quantity) || quantity <= 0) fatal(`--line qty must be > 0 in '${spec}'`);
|
|
23
|
-
return { description, quantity,
|
|
23
|
+
return { description, quantity, unit_price_cents: toCents(parts[2].trim(), "--line unitPrice") };
|
|
24
24
|
}
|
|
25
25
|
var NUMBER_COL = (v) => v ? `#${v}` : "\u2014";
|
|
26
|
+
var filterOptions = (c) => c.option("--status <status>", "Filter: draft | finalized | paid | void").option("--payment-status <list>", "unpaid | partially_paid | paid | not_due (comma-separated)").option("--overdue", "Owed, with a due date in the past").option("--source <source>", "local | stripe | manual").option("--fiscal-status <status>", "not_submitted | queued | submitted | accepted | rejected | cancelled").option("--customer-id <id>", "Only this customer (its id)");
|
|
26
27
|
function buildInvoiceCommand(deps) {
|
|
27
28
|
const { http } = deps;
|
|
28
29
|
const cli = deps.cliName ?? "cli";
|
|
29
30
|
const listInvoices = async (opts) => {
|
|
30
|
-
const
|
|
31
|
-
|
|
31
|
+
const params = new URLSearchParams();
|
|
32
|
+
if (opts.status) params.set("status", opts.status);
|
|
33
|
+
if (opts.paymentStatus) params.set("payment_status", opts.paymentStatus);
|
|
34
|
+
if (opts.overdue) params.set("overdue", "true");
|
|
35
|
+
if (opts.source) params.set("source", opts.source);
|
|
36
|
+
if (opts.fiscalStatus) params.set("fiscal_status", opts.fiscalStatus);
|
|
37
|
+
if (opts.customerId) params.set("customer_id", opts.customerId);
|
|
38
|
+
const q = params.toString() ? `?${params}` : "";
|
|
39
|
+
const res = await http.get(`/invoices${q}`).catch(die);
|
|
32
40
|
printOutput(res.invoices, opts.output, (wide) => {
|
|
33
41
|
table(res.invoices, [
|
|
34
|
-
{ key: "
|
|
42
|
+
{ key: "short_id", label: "ID" },
|
|
35
43
|
{ key: "number", label: "NO", fmt: NUMBER_COL },
|
|
36
44
|
{ key: "status", label: "STATUS" },
|
|
37
|
-
{ key: "
|
|
38
|
-
{ key: "
|
|
39
|
-
{ key: "
|
|
40
|
-
{ key: "
|
|
45
|
+
{ key: "payment_status", label: "PAYMENT", fmt: (v) => v ?? "" },
|
|
46
|
+
{ key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
|
|
47
|
+
{ key: "total_cents", label: "TOTAL", fmt: (v, r) => fmtMoney(v, r.currency) },
|
|
48
|
+
{ key: "balance_cents", label: "BALANCE", fmt: (v, r) => fmtMoney(v, r.currency) },
|
|
49
|
+
{ key: "source", label: "SOURCE", wide: true, fmt: (v) => v ?? "local" },
|
|
50
|
+
{ key: "created_at", label: "CREATED", wide: true, fmt: (v) => fmtDate(v) },
|
|
41
51
|
{ key: "id", label: "FULL ID", wide: true }
|
|
42
52
|
], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` });
|
|
43
53
|
summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? "s" : ""}`);
|
|
44
54
|
}, "id");
|
|
45
55
|
};
|
|
46
|
-
const cmd = new Command("invoices").aliases(["inv", "invoice"]).description("Manage invoices (org-scoped \u2014 run `use <org>` first)").option(...outputOption())
|
|
56
|
+
const cmd = new Command("invoices").aliases(["inv", "invoice"]).description("Manage invoices (org-scoped \u2014 run `use <org>` first)").option(...outputOption());
|
|
57
|
+
filterOptions(cmd).action(listInvoices);
|
|
47
58
|
cmd.addCommand(
|
|
48
|
-
new Command("ls").description("List invoices (alias of the bare command)").option(...outputOption())
|
|
59
|
+
filterOptions(new Command("ls").description("List invoices (alias of the bare command)").option(...outputOption())).action(function() {
|
|
49
60
|
const self = this.opts();
|
|
50
61
|
const parent = this.parent?.opts() ?? {};
|
|
51
62
|
return listInvoices({
|
|
52
63
|
output: self.output && self.output !== "table" ? self.output : parent.output ?? "table",
|
|
53
|
-
status: self.status ?? parent.status
|
|
64
|
+
...self.status ?? parent.status ? { status: self.status ?? parent.status } : {},
|
|
65
|
+
...self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: self.paymentStatus ?? parent.paymentStatus } : {},
|
|
66
|
+
...self.overdue ?? parent.overdue ? { overdue: true } : {},
|
|
67
|
+
...self.source ?? parent.source ? { source: self.source ?? parent.source } : {},
|
|
68
|
+
...self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: self.fiscalStatus ?? parent.fiscalStatus } : {},
|
|
69
|
+
...self.customerId ?? parent.customerId ? { customerId: self.customerId ?? parent.customerId } : {}
|
|
54
70
|
});
|
|
55
71
|
})
|
|
56
72
|
);
|
|
57
73
|
cmd.addCommand(
|
|
58
74
|
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
75
|
const lines = opts.line.map(parseLine);
|
|
60
|
-
const res = await http.post("/
|
|
61
|
-
|
|
76
|
+
const res = await http.post("/invoices", {
|
|
77
|
+
customer_id: opts.customer,
|
|
62
78
|
currency: opts.currency,
|
|
63
79
|
lines
|
|
64
80
|
}).catch(die);
|
|
65
|
-
success(`Draft invoice created for ${res.invoice.
|
|
66
|
-
kv([["id", res.invoice.
|
|
81
|
+
success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`);
|
|
82
|
+
kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)]]);
|
|
67
83
|
})
|
|
68
84
|
);
|
|
69
85
|
cmd.addCommand(
|
|
70
86
|
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(`/
|
|
87
|
+
const res = await http.get(`/invoices/${ref}`).catch(die);
|
|
72
88
|
const inv = res.invoice;
|
|
73
89
|
const cur = String(inv["currency"]);
|
|
74
90
|
printOutput(inv, opts.output, () => {
|
|
75
91
|
kv([
|
|
76
|
-
["id", String(inv["
|
|
92
|
+
["id", String(inv["short_id"])],
|
|
77
93
|
["number", inv["number"] ? `#${inv["number"]}` : "\u2014 (draft)"],
|
|
78
94
|
["status", String(inv["status"])],
|
|
79
|
-
["customer", String(inv["
|
|
80
|
-
["issued", inv["
|
|
81
|
-
["due", inv["
|
|
95
|
+
["customer", String(inv["customer_name"] ?? inv["customer_id"])],
|
|
96
|
+
["issued", inv["issued_at"] ? fmtDate(inv["issued_at"]) : "\u2014"],
|
|
97
|
+
["due", inv["due_at"] ? fmtDate(inv["due_at"]) : "\u2014"]
|
|
82
98
|
]);
|
|
83
99
|
const lines = inv["lines"] ?? [];
|
|
84
100
|
if (lines.length) {
|
|
@@ -86,15 +102,15 @@ function buildInvoiceCommand(deps) {
|
|
|
86
102
|
table(lines, [
|
|
87
103
|
{ key: "description", label: "DESCRIPTION" },
|
|
88
104
|
{ key: "quantity", label: "QTY" },
|
|
89
|
-
{ key: "
|
|
90
|
-
{ key: "
|
|
105
|
+
{ key: "unit_price_cents", label: "UNIT", fmt: (v) => fmtMoney(v, cur) },
|
|
106
|
+
{ key: "amount_cents", label: "AMOUNT", fmt: (v) => fmtMoney(v, cur) }
|
|
91
107
|
]);
|
|
92
108
|
}
|
|
93
109
|
kv([
|
|
94
|
-
["subtotal", fmtMoney(inv["
|
|
95
|
-
["total", fmtMoney(inv["
|
|
96
|
-
["paid", fmtMoney(inv["
|
|
97
|
-
["balance", fmtMoney(inv["
|
|
110
|
+
["subtotal", fmtMoney(inv["subtotal_cents"], cur)],
|
|
111
|
+
["total", fmtMoney(inv["total_cents"], cur)],
|
|
112
|
+
["paid", fmtMoney(inv["amount_paid_cents"], cur)],
|
|
113
|
+
["balance", fmtMoney(inv["balance_cents"], cur)],
|
|
98
114
|
["full_id", String(inv["id"])]
|
|
99
115
|
]);
|
|
100
116
|
}, "id");
|
|
@@ -103,12 +119,12 @@ function buildInvoiceCommand(deps) {
|
|
|
103
119
|
cmd.addCommand(
|
|
104
120
|
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
121
|
const body = {};
|
|
106
|
-
if (opts.customer !== void 0) body["
|
|
122
|
+
if (opts.customer !== void 0) body["customer_id"] = opts.customer;
|
|
107
123
|
if (opts.line !== void 0) body["lines"] = opts.line.map(parseLine);
|
|
108
124
|
if (!Object.keys(body).length) fatal("Provide --customer and/or --line");
|
|
109
|
-
const res = await http.patch(`/
|
|
125
|
+
const res = await http.patch(`/invoices/${ref}`, body).catch(die);
|
|
110
126
|
success("Draft updated.");
|
|
111
|
-
kv([["id", res.invoice.
|
|
127
|
+
kv([["id", res.invoice.short_id], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)]]);
|
|
112
128
|
})
|
|
113
129
|
);
|
|
114
130
|
cmd.addCommand(
|
|
@@ -117,41 +133,41 @@ function buildInvoiceCommand(deps) {
|
|
|
117
133
|
if (opts.due) {
|
|
118
134
|
const ms = Date.parse(opts.due);
|
|
119
135
|
if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`);
|
|
120
|
-
body["
|
|
136
|
+
body["due_at"] = ms;
|
|
121
137
|
}
|
|
122
|
-
const res = await http.post(`/
|
|
138
|
+
const res = await http.post(`/invoices/${ref}/finalize`, body).catch(die);
|
|
123
139
|
success(`Invoice finalized: #${res.invoice.number}`);
|
|
124
|
-
kv([["id", res.invoice.
|
|
140
|
+
kv([["id", res.invoice.short_id], ["number", `#${res.invoice.number}`], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balance_cents, res.invoice.currency)]]);
|
|
125
141
|
})
|
|
126
142
|
);
|
|
127
143
|
cmd.addCommand(
|
|
128
144
|
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(`/
|
|
130
|
-
|
|
145
|
+
const res = await http.post(`/invoices/${ref}/payments`, {
|
|
146
|
+
amount_cents: toCents(opts.amount),
|
|
131
147
|
...opts.method ? { method: opts.method } : {},
|
|
132
148
|
...opts.ref ? { reference: opts.ref } : {}
|
|
133
149
|
}).catch(die);
|
|
134
150
|
success(`Payment recorded. Invoice is now ${res.invoice.status}.`);
|
|
135
|
-
kv([["id", res.invoice.
|
|
151
|
+
kv([["id", res.invoice.short_id], ["paid", fmtMoney(res.invoice.amount_paid_cents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balance_cents, res.invoice.currency)]]);
|
|
136
152
|
})
|
|
137
153
|
);
|
|
138
154
|
cmd.addCommand(
|
|
139
155
|
new Command("void").argument("<ref>").description("Void a finalized invoice").option("--reason <reason>", "Reason").action(async (ref, opts) => {
|
|
140
|
-
const res = await http.post(`/
|
|
141
|
-
success(`Invoice voided: ${res.invoice.
|
|
156
|
+
const res = await http.post(`/invoices/${ref}/void`, { reason: opts.reason ?? "" }).catch(die);
|
|
157
|
+
success(`Invoice voided: ${res.invoice.short_id}`);
|
|
142
158
|
})
|
|
143
159
|
);
|
|
144
160
|
cmd.addCommand(
|
|
145
161
|
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 ? `/
|
|
162
|
+
const path = ref ? `/invoices/${ref}/payments` : "/transactions";
|
|
147
163
|
const res = await http.get(path).catch(die);
|
|
148
164
|
printOutput(res.transactions, opts.output, (wide) => {
|
|
149
165
|
table(res.transactions, [
|
|
150
|
-
{ key: "
|
|
151
|
-
{ key: "
|
|
152
|
-
{ key: "
|
|
166
|
+
{ key: "created_at", label: "DATE", fmt: (v) => fmtDate(v) },
|
|
167
|
+
{ key: "invoice_number", label: "INVOICE", fmt: (v) => v ? `#${v}` : "\u2014" },
|
|
168
|
+
{ key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
|
|
153
169
|
{ key: "kind", label: "KIND" },
|
|
154
|
-
{ key: "
|
|
170
|
+
{ key: "amount_cents", label: "AMOUNT", fmt: (v, r) => fmtMoney(v, r.currency) },
|
|
155
171
|
{ key: "method", label: "METHOD", fmt: (v) => v ?? "" },
|
|
156
172
|
{ key: "reference", label: "REF", wide: true, fmt: (v) => v ?? "" },
|
|
157
173
|
{ key: "id", label: "TXN ID", wide: true }
|