@baseworks/invoice 0.1.0 → 1.0.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 +58 -14
- package/dist/{chunk-7P7ARN3X.js → chunk-ITMZVGLQ.js} +22 -22
- package/dist/cli.js +38 -38
- package/dist/client.d.ts +99 -23
- package/dist/client.js +81 -23
- package/dist/events.d.ts +68 -62
- package/dist/events.js +1 -1
- package/dist/graphql.d.ts +58 -0
- package/dist/graphql.js +75 -0
- package/dist/mcp.d.ts +13 -0
- package/dist/mcp.js +131 -0
- package/dist/projections.js +20 -20
- package/package.json +15 -3
- package/src/__tests__/cli.test.ts +25 -25
- package/src/__tests__/client.test.ts +108 -0
- package/src/__tests__/dts-exports.test.ts +75 -0
- package/src/__tests__/mcp.test.ts +150 -0
- package/src/cli.ts +49 -49
- package/src/client.ts +44 -25
- package/src/compat.ts +61 -0
- package/src/events.ts +28 -22
- package/src/graphql.ts +77 -0
- package/src/mcp.ts +179 -0
- package/src/projections.ts +19 -19
- package/src/types.ts +94 -20
package/src/cli.ts
CHANGED
|
@@ -23,16 +23,16 @@ export interface InvoiceCliDeps {
|
|
|
23
23
|
|
|
24
24
|
type InvoiceRow = {
|
|
25
25
|
id: string
|
|
26
|
-
|
|
26
|
+
short_id: string
|
|
27
27
|
number: number | null
|
|
28
28
|
status: string
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
customer_name: string | null
|
|
30
|
+
customer_id: string
|
|
31
31
|
currency: string
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
total_cents: number
|
|
33
|
+
amount_paid_cents: number
|
|
34
|
+
balance_cents: number
|
|
35
|
+
created_at?: number
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
const die = (e: unknown): never => fatal(e instanceof Error ? e.message : String(e))
|
|
@@ -52,14 +52,14 @@ function toCents(amount: string, flag = '--amount'): number {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
/** `"<description>|<qty>|<unitPrice>"` → a line input. */
|
|
55
|
-
function parseLine(spec: string): { description: string; quantity: number;
|
|
55
|
+
function parseLine(spec: string): { description: string; quantity: number; unit_price_cents: number } {
|
|
56
56
|
const parts = spec.split('|')
|
|
57
57
|
if (parts.length !== 3) fatal(`--line expects "description|qty|unitPrice", got '${spec}'`)
|
|
58
58
|
const description = parts[0]!.trim()
|
|
59
59
|
const quantity = Number(parts[1])
|
|
60
60
|
if (!description) fatal(`--line description is empty in '${spec}'`)
|
|
61
61
|
if (!Number.isFinite(quantity) || quantity <= 0) fatal(`--line qty must be > 0 in '${spec}'`)
|
|
62
|
-
return { description, quantity,
|
|
62
|
+
return { description, quantity, unit_price_cents: toCents(parts[2]!.trim(), '--line unitPrice') }
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
const NUMBER_COL = (v: unknown): string => (v ? `#${v}` : '—')
|
|
@@ -70,16 +70,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
70
70
|
|
|
71
71
|
const listInvoices = async (opts: { output: string; status?: string }) => {
|
|
72
72
|
const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : ''
|
|
73
|
-
const res = await http.get<{ invoices: InvoiceRow[] }>(`/
|
|
73
|
+
const res = await http.get<{ invoices: InvoiceRow[] }>(`/invoices${q}`).catch(die)
|
|
74
74
|
printOutput(res.invoices, opts.output, (wide) => {
|
|
75
75
|
table(res.invoices, [
|
|
76
|
-
{ key: '
|
|
76
|
+
{ key: 'short_id', label: 'ID' },
|
|
77
77
|
{ key: 'number', label: 'NO', fmt: NUMBER_COL },
|
|
78
78
|
{ key: 'status', label: 'STATUS' },
|
|
79
|
-
{ key: '
|
|
80
|
-
{ key: '
|
|
81
|
-
{ key: '
|
|
82
|
-
{ key: '
|
|
79
|
+
{ key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
|
|
80
|
+
{ key: 'total_cents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
|
|
81
|
+
{ key: 'balance_cents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
|
|
82
|
+
{ key: 'created_at', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
|
|
83
83
|
{ key: 'id', label: 'FULL ID', wide: true },
|
|
84
84
|
] as ColDef<InvoiceRow>[], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` })
|
|
85
85
|
summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? 's' : ''}`)
|
|
@@ -116,13 +116,13 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
116
116
|
.requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
|
|
117
117
|
.action(async (opts: { customer: string; currency: string; line: string[] }) => {
|
|
118
118
|
const lines = opts.line.map(parseLine)
|
|
119
|
-
const res = await http.post<{ invoice: InvoiceRow }>('/
|
|
120
|
-
|
|
119
|
+
const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
|
|
120
|
+
customer_id: opts.customer,
|
|
121
121
|
currency: opts.currency,
|
|
122
122
|
lines,
|
|
123
123
|
}).catch(die)
|
|
124
|
-
success(`Draft invoice created for ${res.invoice.
|
|
125
|
-
kv([['id', res.invoice.
|
|
124
|
+
success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`)
|
|
125
|
+
kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
|
|
126
126
|
}),
|
|
127
127
|
)
|
|
128
128
|
|
|
@@ -131,33 +131,33 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
131
131
|
.description('Show invoice details (lines, totals, balance)')
|
|
132
132
|
.option(...outputOption())
|
|
133
133
|
.action(async (ref: string, opts: { output: string }) => {
|
|
134
|
-
const res = await http.get<{ invoice: Record<string, unknown> }>(`/
|
|
134
|
+
const res = await http.get<{ invoice: Record<string, unknown> }>(`/invoices/${ref}`).catch(die)
|
|
135
135
|
const inv = res.invoice as Record<string, unknown>
|
|
136
136
|
const cur = String(inv['currency'])
|
|
137
137
|
printOutput(inv, opts.output, () => {
|
|
138
138
|
kv([
|
|
139
|
-
['id', String(inv['
|
|
139
|
+
['id', String(inv['short_id'])],
|
|
140
140
|
['number', inv['number'] ? `#${inv['number']}` : '— (draft)'],
|
|
141
141
|
['status', String(inv['status'])],
|
|
142
|
-
['customer', String(inv['
|
|
143
|
-
['issued', inv['
|
|
144
|
-
['due', inv['
|
|
142
|
+
['customer', String(inv['customer_name'] ?? inv['customer_id'])],
|
|
143
|
+
['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
|
|
144
|
+
['due', inv['due_at'] ? fmtDate(inv['due_at'] as number) : '—'],
|
|
145
145
|
])
|
|
146
|
-
const lines = (inv['lines'] as Array<{ description: string; quantity: number;
|
|
146
|
+
const lines = (inv['lines'] as Array<{ description: string; quantity: number; unit_price_cents: number; amount_cents: number }>) ?? []
|
|
147
147
|
if (lines.length) {
|
|
148
148
|
console.log(` ${clr.dim}── lines ──${clr.reset}`)
|
|
149
149
|
table(lines, [
|
|
150
150
|
{ key: 'description', label: 'DESCRIPTION' },
|
|
151
151
|
{ key: 'quantity', label: 'QTY' },
|
|
152
|
-
{ key: '
|
|
153
|
-
{ key: '
|
|
152
|
+
{ key: 'unit_price_cents', label: 'UNIT', fmt: (v) => fmtMoney(v as number, cur) },
|
|
153
|
+
{ key: 'amount_cents', label: 'AMOUNT', fmt: (v) => fmtMoney(v as number, cur) },
|
|
154
154
|
] as ColDef<(typeof lines)[number]>[])
|
|
155
155
|
}
|
|
156
156
|
kv([
|
|
157
|
-
['subtotal', fmtMoney(inv['
|
|
158
|
-
['total', fmtMoney(inv['
|
|
159
|
-
['paid', fmtMoney(inv['
|
|
160
|
-
['balance', fmtMoney(inv['
|
|
157
|
+
['subtotal', fmtMoney(inv['subtotal_cents'] as number, cur)],
|
|
158
|
+
['total', fmtMoney(inv['total_cents'] as number, cur)],
|
|
159
|
+
['paid', fmtMoney(inv['amount_paid_cents'] as number, cur)],
|
|
160
|
+
['balance', fmtMoney(inv['balance_cents'] as number, cur)],
|
|
161
161
|
['full_id', String(inv['id'])],
|
|
162
162
|
])
|
|
163
163
|
}, 'id')
|
|
@@ -171,12 +171,12 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
171
171
|
.option('--line <spec...>', 'Replace lines: "description|qty|unitPrice" (repeatable)')
|
|
172
172
|
.action(async (ref: string, opts: { customer?: string; line?: string[] }) => {
|
|
173
173
|
const body: Record<string, unknown> = {}
|
|
174
|
-
if (opts.customer !== undefined) body['
|
|
174
|
+
if (opts.customer !== undefined) body['customer_id'] = opts.customer
|
|
175
175
|
if (opts.line !== undefined) body['lines'] = opts.line.map(parseLine)
|
|
176
176
|
if (!Object.keys(body).length) fatal('Provide --customer and/or --line')
|
|
177
|
-
const res = await http.patch<{ invoice: InvoiceRow }>(`/
|
|
177
|
+
const res = await http.patch<{ invoice: InvoiceRow }>(`/invoices/${ref}`, body).catch(die)
|
|
178
178
|
success('Draft updated.')
|
|
179
|
-
kv([['id', res.invoice.
|
|
179
|
+
kv([['id', res.invoice.short_id], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
|
|
180
180
|
}),
|
|
181
181
|
)
|
|
182
182
|
|
|
@@ -189,11 +189,11 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
189
189
|
if (opts.due) {
|
|
190
190
|
const ms = Date.parse(opts.due)
|
|
191
191
|
if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
|
|
192
|
-
body['
|
|
192
|
+
body['due_at'] = ms
|
|
193
193
|
}
|
|
194
|
-
const res = await http.post<{ invoice: InvoiceRow }>(`/
|
|
194
|
+
const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
|
|
195
195
|
success(`Invoice finalized: #${res.invoice.number}`)
|
|
196
|
-
kv([['id', res.invoice.
|
|
196
|
+
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)]])
|
|
197
197
|
}),
|
|
198
198
|
)
|
|
199
199
|
|
|
@@ -204,13 +204,13 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
204
204
|
.option('--method <method>', 'e.g. bank, cash, card')
|
|
205
205
|
.option('--ref <reference>', 'External payment reference')
|
|
206
206
|
.action(async (ref: string, opts: { amount: string; method?: string; ref?: string }) => {
|
|
207
|
-
const res = await http.post<{ invoice: InvoiceRow }>(`/
|
|
208
|
-
|
|
207
|
+
const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/payments`, {
|
|
208
|
+
amount_cents: toCents(opts.amount),
|
|
209
209
|
...(opts.method ? { method: opts.method } : {}),
|
|
210
210
|
...(opts.ref ? { reference: opts.ref } : {}),
|
|
211
211
|
}).catch(die)
|
|
212
212
|
success(`Payment recorded. Invoice is now ${res.invoice.status}.`)
|
|
213
|
-
kv([['id', res.invoice.
|
|
213
|
+
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)]])
|
|
214
214
|
}),
|
|
215
215
|
)
|
|
216
216
|
|
|
@@ -219,29 +219,29 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
219
219
|
.description('Void a finalized invoice')
|
|
220
220
|
.option('--reason <reason>', 'Reason')
|
|
221
221
|
.action(async (ref: string, opts: { reason?: string }) => {
|
|
222
|
-
const res = await http.post<{ invoice: InvoiceRow }>(`/
|
|
223
|
-
success(`Invoice voided: ${res.invoice.
|
|
222
|
+
const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
|
|
223
|
+
success(`Invoice voided: ${res.invoice.short_id}`)
|
|
224
224
|
}),
|
|
225
225
|
)
|
|
226
226
|
|
|
227
227
|
type TxnRow = {
|
|
228
|
-
id: string;
|
|
229
|
-
kind: string;
|
|
228
|
+
id: string; invoice_number: number; customer_name: string | null; customer_id: string
|
|
229
|
+
kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
|
|
230
230
|
}
|
|
231
231
|
cmd.addCommand(
|
|
232
232
|
new Command('payments').alias('transactions').argument('[ref]', 'invoice id/short_id (omit for all org transactions)')
|
|
233
233
|
.description('List payments / transactions (the money ledger)')
|
|
234
234
|
.option(...outputOption())
|
|
235
235
|
.action(async (ref: string | undefined, opts: { output: string }) => {
|
|
236
|
-
const path = ref ? `/
|
|
236
|
+
const path = ref ? `/invoices/${ref}/payments` : '/transactions'
|
|
237
237
|
const res = await http.get<{ transactions: TxnRow[] }>(path).catch(die)
|
|
238
238
|
printOutput(res.transactions, opts.output, (wide) => {
|
|
239
239
|
table(res.transactions, [
|
|
240
|
-
{ key: '
|
|
241
|
-
{ key: '
|
|
242
|
-
{ key: '
|
|
240
|
+
{ key: 'created_at', label: 'DATE', fmt: (v) => fmtDate(v as number) },
|
|
241
|
+
{ key: 'invoice_number', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
|
|
242
|
+
{ key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customer_id },
|
|
243
243
|
{ key: 'kind', label: 'KIND' },
|
|
244
|
-
{ key: '
|
|
244
|
+
{ key: 'amount_cents', label: 'AMOUNT', fmt: (v, r) => fmtMoney(v as number, (r as TxnRow).currency) },
|
|
245
245
|
{ key: 'method', label: 'METHOD', fmt: (v) => (v as string) ?? '' },
|
|
246
246
|
{ key: 'reference', label: 'REF', wide: true, fmt: (v) => (v as string) ?? '' },
|
|
247
247
|
{ key: 'id', label: 'TXN ID', wide: true },
|
package/src/client.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { newNamesOnFinalize, newNamesOnLines, newNamesOnPayment, oldNamesOnInvoice, oldNamesOnTransaction } from './compat.js'
|
|
1
2
|
import type {
|
|
2
3
|
Invoice,
|
|
3
4
|
Transaction,
|
|
@@ -10,10 +11,16 @@ import type {
|
|
|
10
11
|
export type {
|
|
11
12
|
Invoice,
|
|
12
13
|
InvoiceRow,
|
|
14
|
+
InvoiceDto,
|
|
13
15
|
InvoiceLine,
|
|
16
|
+
InvoiceLineDto,
|
|
17
|
+
InvoiceDeprecated,
|
|
18
|
+
InvoiceLineDeprecated,
|
|
19
|
+
TransactionDeprecated,
|
|
14
20
|
InvoiceLineInput,
|
|
15
21
|
InvoiceStatus,
|
|
16
22
|
Transaction,
|
|
23
|
+
TransactionDto,
|
|
17
24
|
TransactionRow,
|
|
18
25
|
CreateInvoiceInput,
|
|
19
26
|
UpdateInvoiceInput,
|
|
@@ -23,10 +30,14 @@ export type {
|
|
|
23
30
|
|
|
24
31
|
export interface InvoiceClientOptions {
|
|
25
32
|
/** Base URL of invoice-service (resolved by the SDK, e.g. INVOICE_SERVICE_URL). */
|
|
26
|
-
|
|
27
|
-
/** Bearer token — the caller's
|
|
33
|
+
base_url?: string
|
|
34
|
+
/** Bearer token — the caller's token (a service forwards its request's `realm_token`). */
|
|
28
35
|
token?: string
|
|
29
36
|
/** Active org id — sent as X-Org-Id (invoices are org-scoped, tenant = org). */
|
|
37
|
+
org_id?: string
|
|
38
|
+
/** @deprecated Read `base_url`. Accepted until the last caller has moved. */
|
|
39
|
+
baseUrl?: string
|
|
40
|
+
/** @deprecated Read `org_id`. Accepted until the last caller has moved. */
|
|
30
41
|
orgId?: string
|
|
31
42
|
/** Injectable fetch (tests / non-global environments). */
|
|
32
43
|
fetch?: typeof fetch
|
|
@@ -58,28 +69,36 @@ export interface HttpClient {
|
|
|
58
69
|
* service validates + owns the ledger math. Every call carries the org id
|
|
59
70
|
* (X-Org-Id) — invoices are per-org, and the identity JWT is org-less (ADR-009).
|
|
60
71
|
*/
|
|
72
|
+
/**
|
|
73
|
+
* Paths here are the service's own — `/invoices`, not `/v1/invoices`. A gateway
|
|
74
|
+
* publishes the service at `/v1/<name>` and strips that prefix (ADR-042 §4), so
|
|
75
|
+
* the client says what the service serves and `baseUrl` says where it is.
|
|
76
|
+
*/
|
|
61
77
|
export class InvoiceClient {
|
|
62
|
-
private readonly
|
|
78
|
+
private readonly root: string
|
|
63
79
|
private readonly fetchImpl: typeof fetch
|
|
64
80
|
constructor(private readonly opts: InvoiceClientOptions) {
|
|
65
|
-
|
|
81
|
+
const base = opts.base_url ?? opts.baseUrl // deprecated spelling, read until the last caller has moved
|
|
82
|
+
if (!base) throw new Error('InvoiceClient needs base_url')
|
|
83
|
+
this.root = base.replace(/\/$/, '')
|
|
66
84
|
this.fetchImpl = opts.fetch ?? globalThis.fetch
|
|
67
85
|
}
|
|
68
86
|
|
|
69
87
|
withOrg(orgId: string): InvoiceClient {
|
|
70
|
-
return new InvoiceClient({ ...this.opts, orgId })
|
|
88
|
+
return new InvoiceClient({ ...this.opts, org_id: orgId, orgId }) // orgId: deprecated spelling, kept in step
|
|
71
89
|
}
|
|
72
90
|
|
|
73
91
|
private headers(json: boolean, extra: Record<string, string> = {}): Record<string, string> {
|
|
74
92
|
const h: Record<string, string> = {}
|
|
75
93
|
if (json) h['Content-Type'] = 'application/json'
|
|
76
94
|
if (this.opts.token) h['Authorization'] = `Bearer ${this.opts.token}`
|
|
77
|
-
|
|
95
|
+
const org = this.opts.org_id ?? this.opts.orgId // deprecated spelling, read until the last caller has moved
|
|
96
|
+
if (org) h['X-Org-Id'] = org
|
|
78
97
|
return { ...h, ...extra }
|
|
79
98
|
}
|
|
80
99
|
|
|
81
100
|
async api<T>(method: string, path: string, body?: unknown, extra: Record<string, string> = {}): Promise<T> {
|
|
82
|
-
const res = await this.fetchImpl(`${this.
|
|
101
|
+
const res = await this.fetchImpl(`${this.root}${path}`, {
|
|
83
102
|
method,
|
|
84
103
|
headers: this.headers(body !== undefined, extra),
|
|
85
104
|
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
@@ -115,32 +134,32 @@ export class InvoiceClient {
|
|
|
115
134
|
if (opts.offset !== undefined) q.set('offset', String(opts.offset))
|
|
116
135
|
if (opts.status) q.set('status', opts.status)
|
|
117
136
|
const qs = q.toString()
|
|
118
|
-
const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/
|
|
119
|
-
return invoices
|
|
137
|
+
const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
|
|
138
|
+
return invoices.map(oldNamesOnInvoice)
|
|
120
139
|
}
|
|
121
140
|
async get(ref: string): Promise<Invoice> {
|
|
122
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/
|
|
123
|
-
return invoice
|
|
141
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/invoices/${ref}`)
|
|
142
|
+
return oldNamesOnInvoice(invoice)
|
|
124
143
|
}
|
|
125
144
|
async create(input: CreateInvoiceInput): Promise<Invoice> {
|
|
126
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('POST', '/
|
|
127
|
-
return invoice
|
|
145
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('POST', '/invoices', newNamesOnLines(input))
|
|
146
|
+
return oldNamesOnInvoice(invoice)
|
|
128
147
|
}
|
|
129
148
|
async update(ref: string, input: UpdateInvoiceInput): Promise<Invoice> {
|
|
130
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/
|
|
131
|
-
return invoice
|
|
149
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/invoices/${ref}`, newNamesOnLines(input))
|
|
150
|
+
return oldNamesOnInvoice(invoice)
|
|
132
151
|
}
|
|
133
152
|
async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
|
|
134
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/
|
|
135
|
-
return invoice
|
|
153
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
|
|
154
|
+
return oldNamesOnInvoice(invoice)
|
|
136
155
|
}
|
|
137
156
|
async recordPayment(ref: string, input: RecordPaymentInput): Promise<Invoice> {
|
|
138
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/
|
|
139
|
-
return invoice
|
|
157
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/payments`, newNamesOnPayment(input))
|
|
158
|
+
return oldNamesOnInvoice(invoice)
|
|
140
159
|
}
|
|
141
160
|
async void(ref: string, reason?: string): Promise<Invoice> {
|
|
142
|
-
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/
|
|
143
|
-
return invoice
|
|
161
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/void`, { reason: reason ?? '' })
|
|
162
|
+
return oldNamesOnInvoice(invoice)
|
|
144
163
|
}
|
|
145
164
|
|
|
146
165
|
// ── transactions (the payment ledger) ───────────────────────────────────────
|
|
@@ -151,14 +170,14 @@ export class InvoiceClient {
|
|
|
151
170
|
if (opts.limit !== undefined) q.set('limit', String(opts.limit))
|
|
152
171
|
if (opts.offset !== undefined) q.set('offset', String(opts.offset))
|
|
153
172
|
const qs = q.toString()
|
|
154
|
-
const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/
|
|
155
|
-
return transactions
|
|
173
|
+
const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/transactions${qs ? `?${qs}` : ''}`)
|
|
174
|
+
return transactions.map(oldNamesOnTransaction)
|
|
156
175
|
}
|
|
157
176
|
|
|
158
177
|
/** Transactions recorded against one invoice. */
|
|
159
178
|
async invoiceTransactions(ref: string): Promise<Transaction[]> {
|
|
160
|
-
const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/
|
|
161
|
-
return transactions
|
|
179
|
+
const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/invoices/${ref}/payments`)
|
|
180
|
+
return transactions.map(oldNamesOnTransaction)
|
|
162
181
|
}
|
|
163
182
|
}
|
|
164
183
|
|
package/src/compat.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The camelCase names this client spoke until 0.3.0, kept for callers that have not moved
|
|
3
|
+
* (billing-service, stripe-service, apps). Everything here is deprecated and goes when the last
|
|
4
|
+
* caller has moved:
|
|
5
|
+
*
|
|
6
|
+
* - answers: each old name is put back on the object as a non-enumerable getter of the snake_case
|
|
7
|
+
* field, so `invoice.totalCents` still reads while `JSON.stringify` and `toEqual` see only the
|
|
8
|
+
* snake_case object;
|
|
9
|
+
* - requests: old input names are renamed to snake_case before they are sent. The new name wins
|
|
10
|
+
* when both are given.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const INVOICE: Record<string, string> = {
|
|
14
|
+
shortId: 'short_id', customerId: 'customer_id', customerName: 'customer_name', subtotalCents: 'subtotal_cents',
|
|
15
|
+
totalCents: 'total_cents', amountPaidCents: 'amount_paid_cents', balanceCents: 'balance_cents', issuedAt: 'issued_at',
|
|
16
|
+
dueAt: 'due_at', createdAt: 'created_at', updatedAt: 'updated_at',
|
|
17
|
+
}
|
|
18
|
+
const LINE: Record<string, string> = { unitPriceCents: 'unit_price_cents', amountCents: 'amount_cents', productId: 'product_id' }
|
|
19
|
+
const TRANSACTION: Record<string, string> = {
|
|
20
|
+
invoiceId: 'invoice_id', invoiceNumber: 'invoice_number', customerId: 'customer_id', customerName: 'customer_name',
|
|
21
|
+
amountCents: 'amount_cents', createdAt: 'created_at',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function alias<T extends object>(o: T, names: Record<string, string>): T {
|
|
25
|
+
for (const [old, now] of Object.entries(names)) {
|
|
26
|
+
if (old in o) continue
|
|
27
|
+
Object.defineProperty(o, old, { get: () => (o as Record<string, unknown>)[now], enumerable: false, configurable: true })
|
|
28
|
+
}
|
|
29
|
+
return o
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** An invoice as the service answered it, with the old names readable. */
|
|
33
|
+
export function oldNamesOnInvoice<T extends { lines?: unknown }>(invoice: T): T {
|
|
34
|
+
const o = invoice as T & { lines?: object[] }
|
|
35
|
+
if (Array.isArray(o.lines)) o.lines.forEach((l) => alias(l, LINE))
|
|
36
|
+
return alias(o, INVOICE)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function oldNamesOnTransaction<T extends object>(t: T): T {
|
|
40
|
+
return alias(t, TRANSACTION)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A request body with the old names renamed to snake_case; `rename` lists the old → new pairs; `lines` are renamed too. */
|
|
44
|
+
function renamed(body: object | undefined, names: Record<string, string>): Record<string, unknown> {
|
|
45
|
+
const out: Record<string, unknown> = {}
|
|
46
|
+
for (const [k, v] of Object.entries(body ?? {})) {
|
|
47
|
+
const key = names[k] ?? k
|
|
48
|
+
if (key !== k && key in (body as object)) continue // the new name wins
|
|
49
|
+
out[key] = v
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function newNamesOnLines<T extends { lines?: unknown }>(body: T): Record<string, unknown> {
|
|
55
|
+
const out = renamed(body, { customerId: 'customer_id' })
|
|
56
|
+
if (Array.isArray(out['lines'])) out['lines'] = (out['lines'] as object[]).map((l) => renamed(l, LINE))
|
|
57
|
+
return out
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const newNamesOnFinalize = (b: object) => renamed(b, { issuedAt: 'issued_at', dueAt: 'due_at' })
|
|
61
|
+
export const newNamesOnPayment = (b: object) => renamed(b, { amountCents: 'amount_cents' })
|
package/src/events.ts
CHANGED
|
@@ -15,6 +15,12 @@ import { defineAggregate } from '@baseworks/foldbase'
|
|
|
15
15
|
* absolute values in the event, so the projection is a plain upsert (no
|
|
16
16
|
* accumulation). `lines` is a serialized JSON array. Timestamps are epoch millis.
|
|
17
17
|
* A FINALIZED invoice is immutable: only PaymentRecorded / InvoiceVoided follow.
|
|
18
|
+
*
|
|
19
|
+
* Payload fields are snake_case (0.3.0). Events written before are camelCase
|
|
20
|
+
* (`customerId`, `totalCents`, …) and stay so in the log: foldbase reads a
|
|
21
|
+
* snake_case path from a camelCase payload when the snake_case key is absent, so
|
|
22
|
+
* the projections fold both. The `lines` JSON inside a payload is the same: old
|
|
23
|
+
* lines carry `unitPriceCents`, `amountCents`, `productId`; the service reads both.
|
|
18
24
|
*/
|
|
19
25
|
|
|
20
26
|
export const InvoiceStatus = z.enum(['draft', 'finalized', 'paid', 'void'])
|
|
@@ -24,40 +30,40 @@ export const InvoiceEvents = defineAggregate('invoice', {
|
|
|
24
30
|
// Draft created (with its initial lines + computed totals). Numeric fields are
|
|
25
31
|
// initialised to 0 so their read-model columns are stable integers.
|
|
26
32
|
InvoiceDrafted: z.object({
|
|
27
|
-
|
|
28
|
-
|
|
33
|
+
customer_id: z.string().min(1),
|
|
34
|
+
customer_name: z.string(), // snapshot at draft time; '' if unknown
|
|
29
35
|
currency: z.string().length(3),
|
|
30
|
-
lines: z.string(), // JSON array of { description, quantity,
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
36
|
+
lines: z.string(), // JSON array of { description, quantity, unit_price_cents, amount_cents, product_id }
|
|
37
|
+
subtotal_cents: z.number().int(),
|
|
38
|
+
total_cents: z.number().int(),
|
|
39
|
+
short_id: z.string().min(1),
|
|
34
40
|
at: z.number().int(),
|
|
35
41
|
}),
|
|
36
42
|
// Draft edited (customer / lines). Only valid while status = draft.
|
|
37
43
|
InvoiceUpdated: z.object({
|
|
38
|
-
|
|
39
|
-
|
|
44
|
+
customer_id: z.string().min(1),
|
|
45
|
+
customer_name: z.string(),
|
|
40
46
|
lines: z.string(),
|
|
41
|
-
|
|
42
|
-
|
|
47
|
+
subtotal_cents: z.number().int(),
|
|
48
|
+
total_cents: z.number().int(),
|
|
43
49
|
at: z.number().int(),
|
|
44
50
|
}),
|
|
45
51
|
// Finalize: assign the per-org number, freeze lines + totals, set issue/due.
|
|
46
52
|
InvoiceFinalized: z.object({
|
|
47
53
|
number: z.number().int(),
|
|
48
54
|
lines: z.string(),
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
55
|
+
subtotal_cents: z.number().int(),
|
|
56
|
+
total_cents: z.number().int(),
|
|
57
|
+
issued_at: z.number().int(),
|
|
58
|
+
due_at: z.number().int(), // 0 = no due date
|
|
53
59
|
at: z.number().int(),
|
|
54
60
|
}),
|
|
55
|
-
// A payment applied to a finalized invoice. `
|
|
61
|
+
// A payment applied to a finalized invoice. `amount_paid_cents` is the new running
|
|
56
62
|
// total; `status` is the resulting status ('paid' when balance ≤ 0, else
|
|
57
63
|
// 'finalized') — both computed by the store.
|
|
58
64
|
PaymentRecorded: z.object({
|
|
59
|
-
|
|
60
|
-
|
|
65
|
+
amount_cents: z.number().int(),
|
|
66
|
+
amount_paid_cents: z.number().int(),
|
|
61
67
|
status: InvoiceStatus,
|
|
62
68
|
method: z.string(),
|
|
63
69
|
reference: z.string(),
|
|
@@ -81,12 +87,12 @@ export type TransactionKind = z.infer<typeof TransactionKind>
|
|
|
81
87
|
|
|
82
88
|
export const TransactionEvents = defineAggregate('transaction', {
|
|
83
89
|
TransactionRecorded: z.object({
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
90
|
+
invoice_id: z.string().min(1),
|
|
91
|
+
invoice_number: z.number().int(), // the invoice's number at the time
|
|
92
|
+
customer_id: z.string(),
|
|
93
|
+
customer_name: z.string(),
|
|
88
94
|
kind: TransactionKind,
|
|
89
|
-
|
|
95
|
+
amount_cents: z.number().int(),
|
|
90
96
|
currency: z.string().length(3),
|
|
91
97
|
method: z.string(),
|
|
92
98
|
reference: z.string(),
|
package/src/graphql.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { createInvoiceClient, Invoice } from './client.js'
|
|
2
|
+
|
|
3
|
+
/** GraphQL read module for invoices — invoices + transactions, `extend`s Customer. */
|
|
4
|
+
export interface InvoiceGraphContext {
|
|
5
|
+
invoice: ReturnType<typeof createInvoiceClient>
|
|
6
|
+
customerLoader: { load(id: string): Promise<unknown> }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const typeDefs = /* GraphQL */ `
|
|
10
|
+
type Invoice {
|
|
11
|
+
id: ID!
|
|
12
|
+
number: Int
|
|
13
|
+
status: String!
|
|
14
|
+
currency: String!
|
|
15
|
+
subtotalCents: Int!
|
|
16
|
+
totalCents: Int!
|
|
17
|
+
amountPaidCents: Int!
|
|
18
|
+
balanceCents: Int!
|
|
19
|
+
dueAt: Float
|
|
20
|
+
createdAt: Float!
|
|
21
|
+
lines: [InvoiceLine!]!
|
|
22
|
+
customer: Customer
|
|
23
|
+
transactions: [Transaction!]!
|
|
24
|
+
}
|
|
25
|
+
type InvoiceLine {
|
|
26
|
+
description: String!
|
|
27
|
+
quantity: Float!
|
|
28
|
+
unitPriceCents: Int!
|
|
29
|
+
amountCents: Int!
|
|
30
|
+
}
|
|
31
|
+
type Transaction {
|
|
32
|
+
id: ID!
|
|
33
|
+
kind: String!
|
|
34
|
+
amountCents: Int!
|
|
35
|
+
currency: String!
|
|
36
|
+
method: String
|
|
37
|
+
reference: String
|
|
38
|
+
createdAt: Float!
|
|
39
|
+
}
|
|
40
|
+
extend type Query {
|
|
41
|
+
invoice(ref: String!): Invoice
|
|
42
|
+
invoices(status: String): [Invoice!]!
|
|
43
|
+
}
|
|
44
|
+
extend type Customer {
|
|
45
|
+
invoices(status: String): [Invoice!]!
|
|
46
|
+
}
|
|
47
|
+
`
|
|
48
|
+
|
|
49
|
+
export const resolvers = {
|
|
50
|
+
Query: {
|
|
51
|
+
invoice: (_: unknown, { ref }: { ref: string }, ctx: InvoiceGraphContext) => ctx.invoice.get(ref).catch(() => null),
|
|
52
|
+
invoices: (_: unknown, { status }: { status?: string }, ctx: InvoiceGraphContext) => ctx.invoice.list(status ? { status } : {}),
|
|
53
|
+
},
|
|
54
|
+
Customer: {
|
|
55
|
+
invoices: async (parent: { id: string }, { status }: { status?: string }, ctx: InvoiceGraphContext) =>
|
|
56
|
+
(await ctx.invoice.list(status ? { status } : {})).filter((i) => i.customer_id === parent.id),
|
|
57
|
+
},
|
|
58
|
+
InvoiceLine: {
|
|
59
|
+
unitPriceCents: (l: { unit_price_cents: number }) => l.unit_price_cents,
|
|
60
|
+
amountCents: (l: { amount_cents: number }) => l.amount_cents,
|
|
61
|
+
},
|
|
62
|
+
Transaction: {
|
|
63
|
+
amountCents: (t: { amount_cents: number }) => t.amount_cents,
|
|
64
|
+
createdAt: (t: { created_at: number }) => t.created_at,
|
|
65
|
+
},
|
|
66
|
+
Invoice: {
|
|
67
|
+
// The schema is camelCase (that contract's own); the data is snake_case.
|
|
68
|
+
subtotalCents: (p: Invoice) => p.subtotal_cents,
|
|
69
|
+
totalCents: (p: Invoice) => p.total_cents,
|
|
70
|
+
amountPaidCents: (p: Invoice) => p.amount_paid_cents,
|
|
71
|
+
balanceCents: (p: Invoice) => p.balance_cents,
|
|
72
|
+
dueAt: (p: Invoice) => p.due_at,
|
|
73
|
+
createdAt: (p: Invoice) => p.created_at,
|
|
74
|
+
customer: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.customerLoader.load(parent.customer_id),
|
|
75
|
+
transactions: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.invoice.invoiceTransactions(parent.id).catch(() => []),
|
|
76
|
+
},
|
|
77
|
+
}
|