@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.
@@ -0,0 +1,163 @@
1
+ /** The invoice tools: names, access, permissions, inputs, what they call, what a model is told. */
2
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
3
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
4
+ import { describe, expect, it } from 'vitest'
5
+ import { composeTools, runStdio } from '@baseworks/mcp'
6
+ import { InvoiceError } from '../client.js'
7
+ import { invoiceTools } from '../mcp.js'
8
+
9
+ const calls: Array<[string, ...unknown[]]> = []
10
+ const fake = {
11
+ list: async (o: unknown) => { calls.push(['list', o]); return [{ id: 'i1' }] },
12
+ get: async (ref: string) => { calls.push(['get', ref]); if (ref === 'gone') throw new InvoiceError(404, 'not_found', 'Invoice not found'); return { id: 'i2', short_id: ref } },
13
+ create: async (a: unknown) => { calls.push(['create', a]); return { id: 'new', ...(a as object) } },
14
+ update: async (ref: string, a: unknown) => { calls.push(['update', ref, a]); return { id: ref } },
15
+ finalize: async (ref: string, a: unknown) => { calls.push(['finalize', ref, a]); return { id: ref, status: 'finalized' } },
16
+ recordPayment: async (ref: string, a: unknown) => { calls.push(['recordPayment', ref, a]); return { id: ref, status: 'paid' } },
17
+ void: async (ref: string, reason?: string) => { calls.push(['void', ref, reason]); return { id: ref, status: 'void' } },
18
+ transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
19
+ invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
20
+ }
21
+
22
+ async function session(over: Partial<Parameters<typeof runStdio>[0]> = {}) {
23
+ const [a, b] = InMemoryTransport.createLinkedPair()
24
+ await runStdio({ tools: composeTools(invoiceTools()), token: 'x.y.z', transport: a, clients: () => ({ invoice: fake }), ...over } as never)
25
+ const client = new Client({ name: 'c', version: '1' })
26
+ await client.connect(b)
27
+ calls.length = 0
28
+ return client
29
+ }
30
+ const out = (r: { content?: unknown }) => JSON.parse(((r.content as Array<{ text: string }>)[0]!).text)
31
+ const refused = async (c: Client, name: string, args: Record<string, unknown>) => {
32
+ const r = await c.callTool({ name, arguments: args }).catch((e) => e)
33
+ return r instanceof Error || (r as { isError?: boolean }).isError
34
+ }
35
+
36
+ describe('the tool set', () => {
37
+ it('is invoice_<verb>, composes with itself once, and says read or write with the permission the service registered', () => {
38
+ const tools = invoiceTools()
39
+ expect(tools.map((t) => [t.name, t.access, t.permission])).toEqual([
40
+ ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
41
+ ['invoice_create', 'write', 'invoice.write'], ['invoice_update', 'write', 'invoice.write'],
42
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_record_payment', 'write', 'invoice.record_payment'], ['invoice_void', 'write', 'invoice.void'],
43
+ ])
44
+ expect(composeTools(tools)).toHaveLength(8)
45
+ expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
46
+ })
47
+ it('permission names are the ones invoice-service registers', async () => {
48
+ const { INVOICE_ACTIONS } = await import('../../../../src/lib/org.js')
49
+ for (const t of invoiceTools()) expect(Object.keys(INVOICE_ACTIONS)).toContain(t.permission)
50
+ // and the access each tool declares is the one the manifest declares for it
51
+ for (const t of invoiceTools()) expect(INVOICE_ACTIONS[t.permission as keyof typeof INVOICE_ACTIONS].access, t.name).toBe(t.access)
52
+ })
53
+ it('descriptions are written for a model: what it returns, what it writes, what needs a confirmation', () => {
54
+ const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
55
+ expect(d['invoice_list']).toMatch(/balance_cents/)
56
+ expect(d['invoice_create']).toMatch(/WRITES/)
57
+ expect(d['invoice_create']).toMatch(/customer_not_found/)
58
+ expect(d['invoice_create']).toMatch(/integer cents/)
59
+ expect(d['invoice_finalize']).toMatch(/cannot be undone/)
60
+ expect(d['invoice_finalize']).toMatch(/confirm/i)
61
+ expect(d['invoice_record_payment']).toMatch(/reference/)
62
+ expect(d['invoice_void']).toMatch(/cannot be undone/)
63
+ for (const t of invoiceTools()) expect(t.description.length, t.name).toBeGreaterThan(120)
64
+ })
65
+ })
66
+
67
+ describe('through a real MCP client', () => {
68
+ it('lists the eight tools; reads are hinted read-only, writes are not', async () => {
69
+ const t = (await (await session()).listTools()).tools
70
+ expect(t).toHaveLength(8)
71
+ expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
72
+ for (const n of ['invoice_create', 'invoice_finalize', 'invoice_record_payment', 'invoice_void']) expect(t.find((x) => x.name === n)!.annotations, n).toMatchObject({ readOnlyHint: false })
73
+ expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
74
+ })
75
+
76
+ it('list: the filters reach the client; payment_status is a list', async () => {
77
+ const c = await session()
78
+ await c.callTool({ name: 'invoice_list', arguments: { payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' } })
79
+ expect(calls).toEqual([['list', { limit: 25, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
80
+ for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
81
+ })
82
+
83
+ it('record_payment: payment_id is passed on', async () => {
84
+ const c = await session()
85
+ await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
86
+ expect(calls).toEqual([['recordPayment', 'i1', { amount_cents: 5, payment_id: 'pay_1' }]])
87
+ })
88
+
89
+ it('list: a status and a page; defaults to 25', async () => {
90
+ const c = await session()
91
+ expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
92
+ expect(calls).toEqual([['list', { limit: 5, offset: 10, status: 'finalized' }]])
93
+ calls.length = 0
94
+ await c.callTool({ name: 'invoice_list', arguments: {} })
95
+ expect(calls).toEqual([['list', { limit: 25 }]])
96
+ calls.length = 0
97
+ for (const args of [{ limit: 0 }, { limit: 101 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
98
+ expect(calls).toEqual([])
99
+ })
100
+
101
+ it('get: a miss is a tool error carrying the service\'s code', async () => {
102
+ const c = await session()
103
+ expect(out(await c.callTool({ name: 'invoice_get', arguments: { ref: 'abc' } }))).toEqual({ invoice: { id: 'i2', short_id: 'abc' } })
104
+ const r = await c.callTool({ name: 'invoice_get', arguments: { ref: 'gone' } })
105
+ expect(r.isError).toBe(true)
106
+ expect(out(r)).toEqual({ error: 'not_found', status: 404, message: 'Invoice not found' })
107
+ })
108
+
109
+ it('transactions: one invoice\'s, or the organization\'s', async () => {
110
+ const c = await session()
111
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }] })
112
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }] })
113
+ expect(calls).toEqual([['invoiceTransactions', 'i1'], ['transactions', { limit: 3 }]])
114
+ })
115
+
116
+ it('create: lines in snake_case reach the client; what the API would refuse is refused here', async () => {
117
+ const c = await session()
118
+ const args = { customer_id: 'cus-1', currency: 'EUR', lines: [{ description: 'Consulting', quantity: 2.5, unit_price_cents: 15000, product_id: 'p1' }] }
119
+ expect(out(await c.callTool({ name: 'invoice_create', arguments: args })).invoice).toMatchObject({ id: 'new', customer_id: 'cus-1' })
120
+ expect(calls).toEqual([['create', args]])
121
+ calls.length = 0
122
+ for (const bad of [{}, { ...args, lines: [] }, { ...args, currency: 'EURO' }, { ...args, lines: [{ description: 'x', quantity: 0, unit_price_cents: 1 }] },
123
+ { ...args, lines: [{ description: 'x', quantity: 1, unit_price_cents: 1.5 }] }, { ...args, lines: [{ description: 'x', quantity: 1, unit_price_cents: -1 }] }, { ...args, customer_id: '' }]) {
124
+ expect(await refused(c, 'invoice_create', bad), JSON.stringify(bad)).toBeTruthy()
125
+ }
126
+ expect(calls).toEqual([])
127
+ })
128
+ it('create: an unknown customer is the service\'s error', async () => {
129
+ const c = await session({ clients: () => ({ invoice: { ...fake, create: async () => { throw new InvoiceError(404, 'customer_not_found', 'Customer not found: x') } } }) } as never)
130
+ const r = await c.callTool({ name: 'invoice_create', arguments: { customer_id: 'x', currency: 'EUR', lines: [{ description: 'a', quantity: 1, unit_price_cents: 1 }] } })
131
+ expect(r.isError).toBe(true)
132
+ expect(out(r)).toMatchObject({ error: 'customer_not_found', status: 404 })
133
+ })
134
+
135
+ it('update: the ref is split from the patch; nothing to change is refused', async () => {
136
+ const c = await session()
137
+ await c.callTool({ name: 'invoice_update', arguments: { ref: 'i1', customer_id: 'cus-2' } })
138
+ expect(calls).toEqual([['update', 'i1', { customer_id: 'cus-2' }]])
139
+ calls.length = 0
140
+ const none = await c.callTool({ name: 'invoice_update', arguments: { ref: 'i1' } })
141
+ expect(none.isError).toBe(true)
142
+ expect(out(none).error).toBe('nothing_to_update')
143
+ expect(calls).toEqual([])
144
+ })
145
+
146
+ it('finalize, record_payment, void: each calls the one client method with the rest of the arguments', async () => {
147
+ const c = await session()
148
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', due_at: 5 } })
149
+ await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 100, method: 'bank', reference: 'R1' } })
150
+ await c.callTool({ name: 'invoice_void', arguments: { ref: 'i1', reason: 'oops' } })
151
+ expect(calls).toEqual([['finalize', 'i1', { due_at: 5 }], ['recordPayment', 'i1', { amount_cents: 100, method: 'bank', reference: 'R1' }], ['void', 'i1', 'oops']])
152
+ calls.length = 0
153
+ for (const bad of [{ ref: 'i1' }, { ref: 'i1', amount_cents: 0 }, { ref: 'i1', amount_cents: 1.5 }, { ref: 'i1', amount_cents: -5 }]) {
154
+ expect(await refused(c, 'invoice_record_payment', bad), JSON.stringify(bad)).toBeTruthy()
155
+ }
156
+ expect(calls).toEqual([])
157
+ })
158
+
159
+ it('a permission reader hides what the person may not do', async () => {
160
+ const c = await session({ permissions: async () => ['invoice.read', 'invoice.write'] })
161
+ expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_transactions', 'invoice_create', 'invoice_update'])
162
+ })
163
+ })
package/src/cli.ts CHANGED
@@ -23,16 +23,19 @@ 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
+ payment_status?: string
37
+ source?: string
38
+ fiscal?: { status: string } | null
36
39
  }
37
40
 
38
41
  const die = (e: unknown): never => fatal(e instanceof Error ? e.message : String(e))
@@ -52,58 +55,80 @@ function toCents(amount: string, flag = '--amount'): number {
52
55
  }
53
56
 
54
57
  /** `"<description>|<qty>|<unitPrice>"` → a line input. */
55
- function parseLine(spec: string): { description: string; quantity: number; unitPriceCents: number } {
58
+ function parseLine(spec: string): { description: string; quantity: number; unit_price_cents: number } {
56
59
  const parts = spec.split('|')
57
60
  if (parts.length !== 3) fatal(`--line expects "description|qty|unitPrice", got '${spec}'`)
58
61
  const description = parts[0]!.trim()
59
62
  const quantity = Number(parts[1])
60
63
  if (!description) fatal(`--line description is empty in '${spec}'`)
61
64
  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') }
65
+ return { description, quantity, unit_price_cents: toCents(parts[2]!.trim(), '--line unitPrice') }
63
66
  }
64
67
 
65
68
  const NUMBER_COL = (v: unknown): string => (v ? `#${v}` : '—')
66
69
 
70
+ /** The list's filters, on the bare command and on `ls`. */
71
+ const filterOptions = (c: Command): Command =>
72
+ c.option('--status <status>', 'Filter: draft | finalized | paid | void')
73
+ .option('--payment-status <list>', 'unpaid | partially_paid | paid | not_due (comma-separated)')
74
+ .option('--overdue', 'Owed, with a due date in the past')
75
+ .option('--source <source>', 'local | stripe | manual')
76
+ .option('--fiscal-status <status>', 'not_submitted | queued | submitted | accepted | rejected | cancelled')
77
+ .option('--customer-id <id>', 'Only this customer (its id)')
78
+
67
79
  export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
68
80
  const { http } = deps
69
81
  const cli = deps.cliName ?? 'cli'
70
82
 
71
- const listInvoices = async (opts: { output: string; status?: string }) => {
72
- const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : ''
73
- const res = await http.get<{ invoices: InvoiceRow[] }>(`/v1/invoices${q}`).catch(die)
83
+ type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string }
84
+ const listInvoices = async (opts: ListOpts) => {
85
+ const params = new URLSearchParams()
86
+ if (opts.status) params.set('status', opts.status)
87
+ if (opts.paymentStatus) params.set('payment_status', opts.paymentStatus)
88
+ if (opts.overdue) params.set('overdue', 'true')
89
+ if (opts.source) params.set('source', opts.source)
90
+ if (opts.fiscalStatus) params.set('fiscal_status', opts.fiscalStatus)
91
+ if (opts.customerId) params.set('customer_id', opts.customerId)
92
+ const q = params.toString() ? `?${params}` : ''
93
+ const res = await http.get<{ invoices: InvoiceRow[] }>(`/invoices${q}`).catch(die)
74
94
  printOutput(res.invoices, opts.output, (wide) => {
75
95
  table(res.invoices, [
76
- { key: 'shortId', label: 'ID' },
96
+ { key: 'short_id', label: 'ID' },
77
97
  { key: 'number', label: 'NO', fmt: NUMBER_COL },
78
98
  { 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) },
99
+ { key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
100
+ { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
101
+ { key: 'total_cents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
102
+ { key: 'balance_cents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
103
+ { key: 'source', label: 'SOURCE', wide: true, fmt: (v) => (v as string) ?? 'local' },
104
+ { key: 'created_at', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
83
105
  { key: 'id', label: 'FULL ID', wide: true },
84
106
  ] as ColDef<InvoiceRow>[], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` })
85
107
  summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? 's' : ''}`)
86
108
  }, 'id')
87
109
  }
88
110
 
89
- const cmd = new Command('invoices')
111
+ const cmd: Command = new Command('invoices')
90
112
  .aliases(['inv', 'invoice'])
91
113
  .description('Manage invoices (org-scoped — run `use <org>` first)')
92
114
  .option(...outputOption())
93
- .option('--status <status>', 'Filter: draft | finalized | paid | void')
94
- .action(listInvoices)
115
+ filterOptions(cmd).action(listInvoices)
95
116
 
96
117
  cmd.addCommand(
97
- new Command('ls')
118
+ filterOptions(new Command('ls')
98
119
  .description('List invoices (alias of the bare command)')
99
- .option(...outputOption())
100
- .option('--status <status>', 'Filter by status')
120
+ .option(...outputOption()))
101
121
  .action(function (this: Command) {
102
- const self = this.opts() as { output?: string; status?: string }
103
- const parent = (this.parent?.opts() ?? {}) as { output?: string; status?: string }
122
+ const self = this.opts() as ListOpts
123
+ const parent = (this.parent?.opts() ?? {}) as ListOpts
104
124
  return listInvoices({
105
125
  output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
106
- status: self.status ?? parent.status,
126
+ ...(self.status ?? parent.status ? { status: (self.status ?? parent.status) as string } : {}),
127
+ ...(self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: (self.paymentStatus ?? parent.paymentStatus) as string } : {}),
128
+ ...(self.overdue ?? parent.overdue ? { overdue: true } : {}),
129
+ ...(self.source ?? parent.source ? { source: (self.source ?? parent.source) as string } : {}),
130
+ ...(self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: (self.fiscalStatus ?? parent.fiscalStatus) as string } : {}),
131
+ ...(self.customerId ?? parent.customerId ? { customerId: (self.customerId ?? parent.customerId) as string } : {}),
107
132
  })
108
133
  }),
109
134
  )
@@ -116,13 +141,13 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
116
141
  .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
117
142
  .action(async (opts: { customer: string; currency: string; line: string[] }) => {
118
143
  const lines = opts.line.map(parseLine)
119
- const res = await http.post<{ invoice: InvoiceRow }>('/v1/invoices', {
120
- customerId: opts.customer,
144
+ const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
145
+ customer_id: opts.customer,
121
146
  currency: opts.currency,
122
147
  lines,
123
148
  }).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)]])
149
+ success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`)
150
+ kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
126
151
  }),
127
152
  )
128
153
 
@@ -131,33 +156,33 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
131
156
  .description('Show invoice details (lines, totals, balance)')
132
157
  .option(...outputOption())
133
158
  .action(async (ref: string, opts: { output: string }) => {
134
- const res = await http.get<{ invoice: Record<string, unknown> }>(`/v1/invoices/${ref}`).catch(die)
159
+ const res = await http.get<{ invoice: Record<string, unknown> }>(`/invoices/${ref}`).catch(die)
135
160
  const inv = res.invoice as Record<string, unknown>
136
161
  const cur = String(inv['currency'])
137
162
  printOutput(inv, opts.output, () => {
138
163
  kv([
139
- ['id', String(inv['shortId'])],
164
+ ['id', String(inv['short_id'])],
140
165
  ['number', inv['number'] ? `#${inv['number']}` : '— (draft)'],
141
166
  ['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) : '—'],
167
+ ['customer', String(inv['customer_name'] ?? inv['customer_id'])],
168
+ ['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
169
+ ['due', inv['due_at'] ? fmtDate(inv['due_at'] as number) : '—'],
145
170
  ])
146
- const lines = (inv['lines'] as Array<{ description: string; quantity: number; unitPriceCents: number; amountCents: number }>) ?? []
171
+ const lines = (inv['lines'] as Array<{ description: string; quantity: number; unit_price_cents: number; amount_cents: number }>) ?? []
147
172
  if (lines.length) {
148
173
  console.log(` ${clr.dim}── lines ──${clr.reset}`)
149
174
  table(lines, [
150
175
  { key: 'description', label: 'DESCRIPTION' },
151
176
  { 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) },
177
+ { key: 'unit_price_cents', label: 'UNIT', fmt: (v) => fmtMoney(v as number, cur) },
178
+ { key: 'amount_cents', label: 'AMOUNT', fmt: (v) => fmtMoney(v as number, cur) },
154
179
  ] as ColDef<(typeof lines)[number]>[])
155
180
  }
156
181
  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)],
182
+ ['subtotal', fmtMoney(inv['subtotal_cents'] as number, cur)],
183
+ ['total', fmtMoney(inv['total_cents'] as number, cur)],
184
+ ['paid', fmtMoney(inv['amount_paid_cents'] as number, cur)],
185
+ ['balance', fmtMoney(inv['balance_cents'] as number, cur)],
161
186
  ['full_id', String(inv['id'])],
162
187
  ])
163
188
  }, 'id')
@@ -171,12 +196,12 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
171
196
  .option('--line <spec...>', 'Replace lines: "description|qty|unitPrice" (repeatable)')
172
197
  .action(async (ref: string, opts: { customer?: string; line?: string[] }) => {
173
198
  const body: Record<string, unknown> = {}
174
- if (opts.customer !== undefined) body['customerId'] = opts.customer
199
+ if (opts.customer !== undefined) body['customer_id'] = opts.customer
175
200
  if (opts.line !== undefined) body['lines'] = opts.line.map(parseLine)
176
201
  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)
202
+ const res = await http.patch<{ invoice: InvoiceRow }>(`/invoices/${ref}`, body).catch(die)
178
203
  success('Draft updated.')
179
- kv([['id', res.invoice.shortId], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)]])
204
+ kv([['id', res.invoice.short_id], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
180
205
  }),
181
206
  )
182
207
 
@@ -189,11 +214,11 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
189
214
  if (opts.due) {
190
215
  const ms = Date.parse(opts.due)
191
216
  if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
192
- body['dueAt'] = ms
217
+ body['due_at'] = ms
193
218
  }
194
- const res = await http.post<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}/finalize`, body).catch(die)
219
+ const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
195
220
  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)]])
221
+ 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
222
  }),
198
223
  )
199
224
 
@@ -204,13 +229,13 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
204
229
  .option('--method <method>', 'e.g. bank, cash, card')
205
230
  .option('--ref <reference>', 'External payment reference')
206
231
  .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),
232
+ const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/payments`, {
233
+ amount_cents: toCents(opts.amount),
209
234
  ...(opts.method ? { method: opts.method } : {}),
210
235
  ...(opts.ref ? { reference: opts.ref } : {}),
211
236
  }).catch(die)
212
237
  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)]])
238
+ 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
239
  }),
215
240
  )
216
241
 
@@ -219,29 +244,29 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
219
244
  .description('Void a finalized invoice')
220
245
  .option('--reason <reason>', 'Reason')
221
246
  .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}`)
247
+ const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
248
+ success(`Invoice voided: ${res.invoice.short_id}`)
224
249
  }),
225
250
  )
226
251
 
227
252
  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
253
+ id: string; invoice_number: number; customer_name: string | null; customer_id: string
254
+ kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
230
255
  }
231
256
  cmd.addCommand(
232
257
  new Command('payments').alias('transactions').argument('[ref]', 'invoice id/short_id (omit for all org transactions)')
233
258
  .description('List payments / transactions (the money ledger)')
234
259
  .option(...outputOption())
235
260
  .action(async (ref: string | undefined, opts: { output: string }) => {
236
- const path = ref ? `/v1/invoices/${ref}/payments` : '/v1/transactions'
261
+ const path = ref ? `/invoices/${ref}/payments` : '/transactions'
237
262
  const res = await http.get<{ transactions: TxnRow[] }>(path).catch(die)
238
263
  printOutput(res.transactions, opts.output, (wide) => {
239
264
  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 },
265
+ { key: 'created_at', label: 'DATE', fmt: (v) => fmtDate(v as number) },
266
+ { key: 'invoice_number', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
267
+ { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customer_id },
243
268
  { key: 'kind', label: 'KIND' },
244
- { key: 'amountCents', label: 'AMOUNT', fmt: (v, r) => fmtMoney(v as number, (r as TxnRow).currency) },
269
+ { key: 'amount_cents', label: 'AMOUNT', fmt: (v, r) => fmtMoney(v as number, (r as TxnRow).currency) },
245
270
  { key: 'method', label: 'METHOD', fmt: (v) => (v as string) ?? '' },
246
271
  { key: 'reference', label: 'REF', wide: true, fmt: (v) => (v as string) ?? '' },
247
272
  { key: 'id', label: 'TXN ID', wide: true },
package/src/client.ts CHANGED
@@ -1,5 +1,10 @@
1
+ import { newNamesOnFinalize, newNamesOnLines, newNamesOnPayment, oldNamesOnInvoice, oldNamesOnTransaction } from './compat.js'
1
2
  import type {
2
3
  Invoice,
4
+ ListInvoicesOptions,
5
+ MirrorInvoiceInput,
6
+ MirrorResult,
7
+ FiscalInput,
3
8
  Transaction,
4
9
  CreateInvoiceInput,
5
10
  UpdateInvoiceInput,
@@ -10,10 +15,27 @@ import type {
10
15
  export type {
11
16
  Invoice,
12
17
  InvoiceRow,
18
+ InvoiceDto,
13
19
  InvoiceLine,
20
+ InvoiceLineDto,
21
+ InvoiceDeprecated,
22
+ ExternalRef,
23
+ Fiscal,
24
+ FiscalInput,
25
+ FiscalStatus,
26
+ InvoicePayment,
27
+ InvoiceSource,
28
+ ListInvoicesOptions,
29
+ Metadata,
30
+ MirrorInvoiceInput,
31
+ MirrorResult,
32
+ PaymentStatus,
33
+ InvoiceLineDeprecated,
34
+ TransactionDeprecated,
14
35
  InvoiceLineInput,
15
36
  InvoiceStatus,
16
37
  Transaction,
38
+ TransactionDto,
17
39
  TransactionRow,
18
40
  CreateInvoiceInput,
19
41
  UpdateInvoiceInput,
@@ -23,10 +45,14 @@ export type {
23
45
 
24
46
  export interface InvoiceClientOptions {
25
47
  /** 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. */
48
+ base_url?: string
49
+ /** Bearer token — the caller's token (a service forwards its request's `realm_token`). */
28
50
  token?: string
29
51
  /** Active org id — sent as X-Org-Id (invoices are org-scoped, tenant = org). */
52
+ org_id?: string
53
+ /** @deprecated Read `base_url`. Accepted until the last caller has moved. */
54
+ baseUrl?: string
55
+ /** @deprecated Read `org_id`. Accepted until the last caller has moved. */
30
56
  orgId?: string
31
57
  /** Injectable fetch (tests / non-global environments). */
32
58
  fetch?: typeof fetch
@@ -58,28 +84,36 @@ export interface HttpClient {
58
84
  * service validates + owns the ledger math. Every call carries the org id
59
85
  * (X-Org-Id) — invoices are per-org, and the identity JWT is org-less (ADR-009).
60
86
  */
87
+ /**
88
+ * Paths here are the service's own — `/invoices`, not `/v1/invoices`. A gateway
89
+ * publishes the service at `/v1/<name>` and strips that prefix (ADR-042 §4), so
90
+ * the client says what the service serves and `baseUrl` says where it is.
91
+ */
61
92
  export class InvoiceClient {
62
- private readonly baseUrl: string
93
+ private readonly root: string
63
94
  private readonly fetchImpl: typeof fetch
64
95
  constructor(private readonly opts: InvoiceClientOptions) {
65
- this.baseUrl = opts.baseUrl.replace(/\/$/, '')
96
+ const base = opts.base_url ?? opts.baseUrl // deprecated spelling, read until the last caller has moved
97
+ if (!base) throw new Error('InvoiceClient needs base_url')
98
+ this.root = base.replace(/\/$/, '')
66
99
  this.fetchImpl = opts.fetch ?? globalThis.fetch
67
100
  }
68
101
 
69
102
  withOrg(orgId: string): InvoiceClient {
70
- return new InvoiceClient({ ...this.opts, orgId })
103
+ return new InvoiceClient({ ...this.opts, org_id: orgId, orgId }) // orgId: deprecated spelling, kept in step
71
104
  }
72
105
 
73
106
  private headers(json: boolean, extra: Record<string, string> = {}): Record<string, string> {
74
107
  const h: Record<string, string> = {}
75
108
  if (json) h['Content-Type'] = 'application/json'
76
109
  if (this.opts.token) h['Authorization'] = `Bearer ${this.opts.token}`
77
- if (this.opts.orgId) h['X-Org-Id'] = this.opts.orgId
110
+ const org = this.opts.org_id ?? this.opts.orgId // deprecated spelling, read until the last caller has moved
111
+ if (org) h['X-Org-Id'] = org
78
112
  return { ...h, ...extra }
79
113
  }
80
114
 
81
115
  async api<T>(method: string, path: string, body?: unknown, extra: Record<string, string> = {}): Promise<T> {
82
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
116
+ const res = await this.fetchImpl(`${this.root}${path}`, {
83
117
  method,
84
118
  headers: this.headers(body !== undefined, extra),
85
119
  ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
@@ -109,38 +143,56 @@ export class InvoiceClient {
109
143
 
110
144
  // ── invoices ──────────────────────────────────────────────────────────────
111
145
 
112
- async list(opts: { limit?: number; offset?: number; status?: string } = {}): Promise<Invoice[]> {
146
+ async list(opts: ListInvoicesOptions = {}): Promise<Invoice[]> {
113
147
  const q = new URLSearchParams()
114
148
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
115
149
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
116
150
  if (opts.status) q.set('status', opts.status)
151
+ if (opts.payment_status) q.set('payment_status', [opts.payment_status].flat().join(','))
152
+ if (opts.overdue !== undefined) q.set('overdue', String(opts.overdue))
153
+ if (opts.source) q.set('source', opts.source)
154
+ if (opts.fiscal_status) q.set('fiscal_status', opts.fiscal_status)
155
+ if (opts.customer_id) q.set('customer_id', opts.customer_id)
117
156
  const qs = q.toString()
118
- const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/v1/invoices${qs ? `?${qs}` : ''}`)
119
- return invoices
157
+ const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
158
+ return invoices.map(oldNamesOnInvoice)
120
159
  }
121
160
  async get(ref: string): Promise<Invoice> {
122
- const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/v1/invoices/${ref}`)
123
- return invoice
161
+ const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/invoices/${ref}`)
162
+ return oldNamesOnInvoice(invoice)
124
163
  }
125
164
  async create(input: CreateInvoiceInput): Promise<Invoice> {
126
- const { invoice } = await this.api<{ invoice: Invoice }>('POST', '/v1/invoices', input)
127
- return invoice
165
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', '/invoices', newNamesOnLines(input))
166
+ return oldNamesOnInvoice(invoice)
128
167
  }
129
168
  async update(ref: string, input: UpdateInvoiceInput): Promise<Invoice> {
130
- const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/v1/invoices/${ref}`, input)
131
- return invoice
169
+ const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/invoices/${ref}`, newNamesOnLines(input))
170
+ return oldNamesOnInvoice(invoice)
171
+ }
172
+ /**
173
+ * Keep the provider's document (Stripe's invoice, a hand-entered one) as this invoice: creates it or replaces it by
174
+ * `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
175
+ */
176
+ async mirror(input: MirrorInvoiceInput): Promise<MirrorResult> {
177
+ const r = await this.api<MirrorResult>('PUT', '/invoices/mirror', input)
178
+ return { ...r, invoice: oldNamesOnInvoice(r.invoice) }
179
+ }
180
+ /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
181
+ async setFiscal(ref: string, input: FiscalInput): Promise<Invoice> {
182
+ const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/fiscal`, input)
183
+ return oldNamesOnInvoice(invoice)
132
184
  }
133
185
  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
186
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
187
+ return oldNamesOnInvoice(invoice)
136
188
  }
137
189
  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
190
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/payments`, newNamesOnPayment(input))
191
+ return oldNamesOnInvoice(invoice)
140
192
  }
141
193
  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
194
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/void`, { reason: reason ?? '' })
195
+ return oldNamesOnInvoice(invoice)
144
196
  }
145
197
 
146
198
  // ── transactions (the payment ledger) ───────────────────────────────────────
@@ -151,14 +203,14 @@ export class InvoiceClient {
151
203
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
152
204
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
153
205
  const qs = q.toString()
154
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/v1/transactions${qs ? `?${qs}` : ''}`)
155
- return transactions
206
+ const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/transactions${qs ? `?${qs}` : ''}`)
207
+ return transactions.map(oldNamesOnTransaction)
156
208
  }
157
209
 
158
210
  /** Transactions recorded against one invoice. */
159
211
  async invoiceTransactions(ref: string): Promise<Transaction[]> {
160
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/v1/invoices/${ref}/payments`)
161
- return transactions
212
+ const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/invoices/${ref}/payments`)
213
+ return transactions.map(oldNamesOnTransaction)
162
214
  }
163
215
  }
164
216