@baseworks/invoice 0.1.1 → 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/src/cli.ts CHANGED
@@ -23,16 +23,16 @@ export interface InvoiceCliDeps {
23
23
 
24
24
  type InvoiceRow = {
25
25
  id: string
26
- shortId: string
26
+ short_id: string
27
27
  number: number | null
28
28
  status: string
29
- customerName: string | null
30
- customerId: string
29
+ customer_name: string | null
30
+ customer_id: string
31
31
  currency: string
32
- totalCents: number
33
- amountPaidCents: number
34
- balanceCents: number
35
- createdAt?: number
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; unitPriceCents: 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, unitPriceCents: toCents(parts[2]!.trim(), '--line unitPrice') }
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[] }>(`/v1/invoices${q}`).catch(die)
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: 'shortId', label: 'ID' },
76
+ { key: 'short_id', label: 'ID' },
77
77
  { key: 'number', label: 'NO', fmt: NUMBER_COL },
78
78
  { key: 'status', label: 'STATUS' },
79
- { key: 'customerName', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customerId },
80
- { key: 'totalCents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
81
- { key: 'balanceCents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
82
- { key: 'createdAt', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
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 }>('/v1/invoices', {
120
- customerId: opts.customer,
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.customerName ?? res.invoice.customerId}`)
125
- kv([['id', res.invoice.shortId], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)]])
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> }>(`/v1/invoices/${ref}`).catch(die)
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['shortId'])],
139
+ ['id', String(inv['short_id'])],
140
140
  ['number', inv['number'] ? `#${inv['number']}` : '— (draft)'],
141
141
  ['status', String(inv['status'])],
142
- ['customer', String(inv['customerName'] ?? inv['customerId'])],
143
- ['issued', inv['issuedAt'] ? fmtDate(inv['issuedAt'] as number) : '—'],
144
- ['due', inv['dueAt'] ? fmtDate(inv['dueAt'] as number) : '—'],
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; unitPriceCents: number; amountCents: 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: 'unitPriceCents', label: 'UNIT', fmt: (v) => fmtMoney(v as number, cur) },
153
- { key: 'amountCents', label: 'AMOUNT', fmt: (v) => fmtMoney(v as number, cur) },
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['subtotalCents'] as number, cur)],
158
- ['total', fmtMoney(inv['totalCents'] as number, cur)],
159
- ['paid', fmtMoney(inv['amountPaidCents'] as number, cur)],
160
- ['balance', fmtMoney(inv['balanceCents'] as number, cur)],
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['customerId'] = opts.customer
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 }>(`/v1/invoices/${ref}`, body).catch(die)
177
+ const res = await http.patch<{ invoice: InvoiceRow }>(`/invoices/${ref}`, body).catch(die)
178
178
  success('Draft updated.')
179
- kv([['id', res.invoice.shortId], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)]])
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['dueAt'] = ms
192
+ body['due_at'] = ms
193
193
  }
194
- const res = await http.post<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}/finalize`, body).catch(die)
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.shortId], ['number', `#${res.invoice.number}`], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balanceCents, res.invoice.currency)]])
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 }>(`/v1/invoices/${ref}/payments`, {
208
- amountCents: toCents(opts.amount),
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.shortId], ['paid', fmtMoney(res.invoice.amountPaidCents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balanceCents, res.invoice.currency)]])
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 }>(`/v1/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
223
- success(`Invoice voided: ${res.invoice.shortId}`)
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; invoiceNumber: number; customerName: string | null; customerId: string
229
- kind: string; amountCents: number; currency: string; method: string | null; reference: string | null; createdAt?: number
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 ? `/v1/invoices/${ref}/payments` : '/v1/transactions'
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: 'createdAt', label: 'DATE', fmt: (v) => fmtDate(v as number) },
241
- { key: 'invoiceNumber', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
242
- { key: 'customerName', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customerId },
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: 'amountCents', label: 'AMOUNT', fmt: (v, r) => fmtMoney(v as number, (r as TxnRow).currency) },
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
- baseUrl: string
27
- /** Bearer token — the caller's identity JWT. */
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 baseUrl: string
78
+ private readonly root: string
63
79
  private readonly fetchImpl: typeof fetch
64
80
  constructor(private readonly opts: InvoiceClientOptions) {
65
- this.baseUrl = opts.baseUrl.replace(/\/$/, '')
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
- if (this.opts.orgId) h['X-Org-Id'] = this.opts.orgId
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.baseUrl}${path}`, {
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', `/v1/invoices${qs ? `?${qs}` : ''}`)
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', `/v1/invoices/${ref}`)
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', '/v1/invoices', input)
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', `/v1/invoices/${ref}`, input)
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', `/v1/invoices/${ref}/finalize`, input)
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', `/v1/invoices/${ref}/payments`, input)
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', `/v1/invoices/${ref}/void`, { reason: reason ?? '' })
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', `/v1/transactions${qs ? `?${qs}` : ''}`)
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', `/v1/invoices/${ref}/payments`)
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
- customerId: z.string().min(1),
28
- customerName: z.string(), // snapshot at draft time; '' if unknown
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, unitPriceCents, amountCents, productId }
31
- subtotalCents: z.number().int(),
32
- totalCents: z.number().int(),
33
- shortId: z.string().min(1),
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
- customerId: z.string().min(1),
39
- customerName: z.string(),
44
+ customer_id: z.string().min(1),
45
+ customer_name: z.string(),
40
46
  lines: z.string(),
41
- subtotalCents: z.number().int(),
42
- totalCents: z.number().int(),
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
- subtotalCents: z.number().int(),
50
- totalCents: z.number().int(),
51
- issuedAt: z.number().int(),
52
- dueAt: z.number().int(), // 0 = no due date
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. `amountPaidCents` is the new running
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
- amountCents: z.number().int(),
60
- amountPaidCents: z.number().int(),
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
- invoiceId: z.string().min(1),
85
- invoiceNumber: z.number().int(), // the invoice's number at the time
86
- customerId: z.string(),
87
- customerName: z.string(),
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
- amountCents: z.number().int(),
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 CHANGED
@@ -53,10 +53,25 @@ export const resolvers = {
53
53
  },
54
54
  Customer: {
55
55
  invoices: async (parent: { id: string }, { status }: { status?: string }, ctx: InvoiceGraphContext) =>
56
- (await ctx.invoice.list(status ? { status } : {})).filter((i) => i.customerId === parent.id),
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,
57
65
  },
58
66
  Invoice: {
59
- customer: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.customerLoader.load(parent.customerId),
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),
60
75
  transactions: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.invoice.invoiceTransactions(parent.id).catch(() => []),
61
76
  },
62
77
  }