@baseworks/invoice 1.0.0 → 1.2.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.
@@ -93,6 +93,63 @@ describe('what goes out', () => {
93
93
  })
94
94
  })
95
95
 
96
+ describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
97
+ const sent: Array<{ method: string; url: string; body: unknown }> = []
98
+ const g = (async (url: string, init?: RequestInit) => {
99
+ sent.push({ method: init?.method ?? 'GET', url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined })
100
+ if (String(url).includes('/mirror')) return new Response(JSON.stringify({ invoice: INVOICE, created: true }))
101
+ if (init?.method === 'POST') return new Response(JSON.stringify({ invoice: INVOICE }))
102
+ if (String(url).includes('/fiscal')) return new Response(JSON.stringify({ invoice: { ...INVOICE, fiscal: { status: 'queued' } } }))
103
+ return new Response(JSON.stringify({ invoices: [INVOICE] }))
104
+ }) as unknown as typeof fetch
105
+ const c = () => new InvoiceClient({ base_url: 'http://i.test/api', fetch: g })
106
+
107
+ it('list sends every filter, several payment statuses comma-separated', async () => {
108
+ sent.length = 0
109
+ await c().list({ status: 'finalized', payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1', limit: 5 })
110
+ const q = new URL(sent[0]!.url).searchParams
111
+ expect(Object.fromEntries(q)).toEqual({ limit: '5', status: 'finalized', payment_status: 'unpaid,partially_paid', overdue: 'true', source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' })
112
+ sent.length = 0
113
+ await c().list({ payment_status: 'paid', overdue: false })
114
+ expect(Object.fromEntries(new URL(sent[0]!.url).searchParams)).toEqual({ payment_status: 'paid', overdue: 'false' })
115
+ })
116
+ it('mirror PUTs the whole document; setFiscal PUTs the state; both read the old names too', async () => {
117
+ sent.length = 0
118
+ const doc = { source: 'stripe' as const, external_ref: { system: 'stripe', id: 'in_1' }, customer_id: 'c1', currency: 'USD', lines: [], subtotal_cents: 0, tax_cents: 0, total_cents: 0, status: 'finalized' as const, issued_at: 1, provider_updated_at: 2 }
119
+ const r = await c().mirror(doc)
120
+ expect(sent[0]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/mirror', body: doc })
121
+ expect(r.created).toBe(true)
122
+ expect(r.invoice.totalCents).toBe(1000)
123
+ const inv = await c().setFiscal('i1', { status: 'queued', system: 'gib' })
124
+ expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
125
+ expect(inv.fiscal?.status).toBe('queued')
126
+ })
127
+ it('numbering: get, set and clear; list filters by external_number', async () => {
128
+ sent.length = 0
129
+ const h = (async (url: string, init?: RequestInit) => {
130
+ sent.push({ method: init?.method ?? 'GET', url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined })
131
+ if (init?.method === 'DELETE') return new Response(JSON.stringify({ numbering: null }))
132
+ return new Response(JSON.stringify({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 148, next_text: 'BSF2026000000148', updated_at: 1 }, invoices: [] }))
133
+ }) as unknown as typeof fetch
134
+ const cl = new InvoiceClient({ base_url: 'http://i.test/api', fetch: h })
135
+ expect((await cl.getNumbering())?.next_text).toBe('BSF2026000000148')
136
+ await cl.setNumbering({ prefix: 'BSF', digits: 9, yearly: true, next: 148 })
137
+ await cl.clearNumbering()
138
+ await cl.list({ external_number: 'X-1' })
139
+ expect(sent.map((s) => [s.method, s.url.replace('http://i.test/api', ''), s.body])).toEqual([
140
+ ['GET', '/settings/numbering', undefined],
141
+ ['PUT', '/settings/numbering', { prefix: 'BSF', digits: 9, yearly: true, next: 148 }],
142
+ ['DELETE', '/settings/numbering', undefined],
143
+ ['GET', '/invoices?external_number=X-1', undefined],
144
+ ])
145
+ })
146
+ it('recordPayment sends payment_id', async () => {
147
+ sent.length = 0
148
+ await c().recordPayment('i1', { amount_cents: 5, payment_id: 'pay_1' })
149
+ expect(sent[0]!.body).toEqual({ amount_cents: 5, payment_id: 'pay_1' })
150
+ })
151
+ })
152
+
96
153
  describe('the source is snake_case', () => {
97
154
  it('compat.ts is the only place the old names live', async () => {
98
155
  const { readdirSync, readFileSync } = await import('node:fs')
@@ -100,7 +157,8 @@ describe('the source is snake_case', () => {
100
157
  const { fileURLToPath } = await import('node:url')
101
158
  const src = resolve(dirname(fileURLToPath(import.meta.url)), '..')
102
159
  const OLD = /\.(customerId|customerName|shortId|subtotalCents|totalCents|amountPaidCents|balanceCents|issuedAt|dueAt|createdAt|updatedAt|unitPriceCents|amountCents|productId|invoiceId|invoiceNumber|userId|orgId|baseUrl)\b/
103
- for (const f of readdirSync(src).filter((x) => x.endsWith('.ts') && !['compat.ts', 'graphql.ts'].includes(x))) {
160
+ // cli.ts is left out: `opts.customerId` is the name commander gives `--customer-id`
161
+ for (const f of readdirSync(src).filter((x) => x.endsWith('.ts') && !['compat.ts', 'graphql.ts', 'cli.ts'].includes(x))) {
104
162
  const hits = readFileSync(join(src, f), 'utf8').split('\n').map((l, i) => [i + 1, l] as const).filter(([, l]) => OLD.test(l) && !/deprecated|Deprecated/i.test(l))
105
163
  expect(hits, f).toEqual([])
106
164
  }
@@ -15,6 +15,8 @@ const fake = {
15
15
  finalize: async (ref: string, a: unknown) => { calls.push(['finalize', ref, a]); return { id: ref, status: 'finalized' } },
16
16
  recordPayment: async (ref: string, a: unknown) => { calls.push(['recordPayment', ref, a]); return { id: ref, status: 'paid' } },
17
17
  void: async (ref: string, reason?: string) => { calls.push(['void', ref, reason]); return { id: ref, status: 'void' } },
18
+ getNumbering: async () => { calls.push(['getNumbering']); return { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } },
19
+ setNumbering: async (a: unknown) => { calls.push(['setNumbering', a]); return { ...(a as object), next: 1, next_text: 'x', updated_at: 2 } },
18
20
  transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
19
21
  invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
20
22
  }
@@ -37,11 +39,12 @@ describe('the tool set', () => {
37
39
  it('is invoice_<verb>, composes with itself once, and says read or write with the permission the service registered', () => {
38
40
  const tools = invoiceTools()
39
41
  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'],
42
+ ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_numbering', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
41
43
  ['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'],
44
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
45
+ ['invoice_configure_numbering', 'write', 'invoice.configure'], ['invoice_void', 'write', 'invoice.void'],
43
46
  ])
44
- expect(composeTools(tools)).toHaveLength(8)
47
+ expect(composeTools(tools)).toHaveLength(10)
45
48
  expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
46
49
  })
47
50
  it('permission names are the ones invoice-service registers', async () => {
@@ -65,14 +68,60 @@ describe('the tool set', () => {
65
68
  })
66
69
 
67
70
  describe('through a real MCP client', () => {
68
- it('lists the eight tools; reads are hinted read-only, writes are not', async () => {
71
+ it('lists the ten tools; reads are hinted read-only, writes are not', async () => {
69
72
  const t = (await (await session()).listTools()).tools
70
- expect(t).toHaveLength(8)
73
+ expect(t).toHaveLength(10)
71
74
  expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
72
75
  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
76
  expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
74
77
  })
75
78
 
79
+ it('list: the filters reach the client; payment_status is a list', async () => {
80
+ const c = await session()
81
+ await c.callTool({ name: 'invoice_list', arguments: { payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' } })
82
+ expect(calls).toEqual([['list', { limit: 25, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
83
+ for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
84
+ })
85
+
86
+ it('numbering: read with invoice.read, set only with invoice.configure; the shape is checked before the call', async () => {
87
+ const c = await session()
88
+ expect(out(await c.callTool({ name: 'invoice_numbering', arguments: {} }))).toEqual({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } })
89
+ await c.callTool({ name: 'invoice_configure_numbering', arguments: { prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' } })
90
+ expect(calls).toEqual([['getNumbering'], ['setNumbering', { prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' }]])
91
+ calls.length = 0
92
+ for (const bad of [{ prefix: 'bsf', digits: 9, yearly: true }, { prefix: 'BS', digits: 9, yearly: true }, { prefix: 'BSF', digits: 13, yearly: true }, { prefix: 'BSF', digits: 9 }, { prefix: 'BSF', digits: 9, yearly: true, next: 0 }]) {
93
+ expect(await refused(c, 'invoice_configure_numbering', bad), JSON.stringify(bad)).toBeTruthy()
94
+ }
95
+ expect(calls).toEqual([])
96
+ const reader = await session({ permissions: async () => ['invoice.read', 'invoice.write'] })
97
+ const names = (await reader.listTools()).tools.map((x) => x.name)
98
+ expect(names).toContain('invoice_numbering')
99
+ expect(names).not.toContain('invoice_configure_numbering')
100
+ })
101
+
102
+ it('external_number: on create, on finalize and as a list filter; descriptions say when to use which', async () => {
103
+ const c = await session()
104
+ const args = { customer_id: 'c1', currency: 'TRY', lines: [{ description: 'x', quantity: 1, unit_price_cents: 100 }], external_number: 'BSF2026000000148' }
105
+ await c.callTool({ name: 'invoice_create', arguments: args })
106
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', external_number: 'PORTAL-1' } })
107
+ await c.callTool({ name: 'invoice_list', arguments: { external_number: 'PORTAL-1' } })
108
+ expect(calls).toEqual([['create', args], ['finalize', 'i1', { external_number: 'PORTAL-1' }], ['list', { limit: 25, external_number: 'PORTAL-1' }]])
109
+ expect(await refused(c, 'invoice_create', { ...args, external_number: 'x'.repeat(65) })).toBeTruthy()
110
+ const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
111
+ expect(d['invoice_create']).toMatch(/takes none from the organization's series/)
112
+ expect(d['invoice_finalize']).toMatch(/series does not advance/)
113
+ expect(d['invoice_numbering']).toMatch(/next_text/)
114
+ expect(d['invoice_configure_numbering']).toMatch(/administrator/)
115
+ expect(d['invoice_configure_numbering']).toMatch(/never renumbers/)
116
+ expect(d['invoice_configure_numbering']).toMatch(/invoice_numbering/)
117
+ })
118
+
119
+ it('record_payment: payment_id is passed on', async () => {
120
+ const c = await session()
121
+ await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
122
+ expect(calls).toEqual([['recordPayment', 'i1', { amount_cents: 5, payment_id: 'pay_1' }]])
123
+ })
124
+
76
125
  it('list: a status and a page; defaults to 25', async () => {
77
126
  const c = await session()
78
127
  expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
@@ -145,6 +194,6 @@ describe('through a real MCP client', () => {
145
194
 
146
195
  it('a permission reader hides what the person may not do', async () => {
147
196
  const c = await session({ permissions: async () => ['invoice.read', 'invoice.write'] })
148
- expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_transactions', 'invoice_create', 'invoice_update'])
197
+ expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_numbering', 'invoice_transactions', 'invoice_create', 'invoice_update'])
149
198
  })
150
199
  })
package/src/cli.ts CHANGED
@@ -33,6 +33,11 @@ type InvoiceRow = {
33
33
  amount_paid_cents: number
34
34
  balance_cents: number
35
35
  created_at?: number
36
+ number_text?: string | null
37
+ external_number?: string | null
38
+ payment_status?: string
39
+ source?: string
40
+ fiscal?: { status: string } | null
36
41
  }
37
42
 
38
43
  const die = (e: unknown): never => fatal(e instanceof Error ? e.message : String(e))
@@ -62,23 +67,45 @@ function parseLine(spec: string): { description: string; quantity: number; unit_
62
67
  return { description, quantity, unit_price_cents: toCents(parts[2]!.trim(), '--line unitPrice') }
63
68
  }
64
69
 
65
- const NUMBER_COL = (v: unknown): string => (v ? `#${v}` : '—')
70
+ /** A plain counter reads `#7`; a series number or an external number reads as it is. */
71
+ const NUMBER_COL = (v: unknown): string => (v ? (/^\d+$/.test(String(v)) ? `#${v}` : String(v)) : '—')
72
+
73
+ /** The list's filters, on the bare command and on `ls`. */
74
+ const filterOptions = (c: Command): Command =>
75
+ c.option('--status <status>', 'Filter: draft | finalized | paid | void')
76
+ .option('--payment-status <list>', 'unpaid | partially_paid | paid | not_due (comma-separated)')
77
+ .option('--overdue', 'Owed, with a due date in the past')
78
+ .option('--source <source>', 'local | stripe | manual')
79
+ .option('--fiscal-status <status>', 'not_submitted | queued | submitted | accepted | rejected | cancelled')
80
+ .option('--customer-id <id>', 'Only this customer (its id)')
81
+ .option('--external-number <number>', 'Only the invoice with this external number (exact)')
66
82
 
67
83
  export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
68
84
  const { http } = deps
69
85
  const cli = deps.cliName ?? 'cli'
70
86
 
71
- const listInvoices = async (opts: { output: string; status?: string }) => {
72
- const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : ''
87
+ type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
88
+ const listInvoices = async (opts: ListOpts) => {
89
+ const params = new URLSearchParams()
90
+ if (opts.status) params.set('status', opts.status)
91
+ if (opts.paymentStatus) params.set('payment_status', opts.paymentStatus)
92
+ if (opts.overdue) params.set('overdue', 'true')
93
+ if (opts.source) params.set('source', opts.source)
94
+ if (opts.fiscalStatus) params.set('fiscal_status', opts.fiscalStatus)
95
+ if (opts.customerId) params.set('customer_id', opts.customerId)
96
+ if (opts.externalNumber) params.set('external_number', opts.externalNumber)
97
+ const q = params.toString() ? `?${params}` : ''
73
98
  const res = await http.get<{ invoices: InvoiceRow[] }>(`/invoices${q}`).catch(die)
74
99
  printOutput(res.invoices, opts.output, (wide) => {
75
100
  table(res.invoices, [
76
101
  { key: 'short_id', label: 'ID' },
77
- { key: 'number', label: 'NO', fmt: NUMBER_COL },
102
+ { key: 'number_text', label: 'NO', fmt: NUMBER_COL },
78
103
  { key: 'status', label: 'STATUS' },
104
+ { key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
79
105
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
80
106
  { key: 'total_cents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
81
107
  { key: 'balance_cents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
108
+ { key: 'source', label: 'SOURCE', wide: true, fmt: (v) => (v as string) ?? 'local' },
82
109
  { key: 'created_at', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
83
110
  { key: 'id', label: 'FULL ID', wide: true },
84
111
  ] as ColDef<InvoiceRow>[], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` })
@@ -86,24 +113,28 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
86
113
  }, 'id')
87
114
  }
88
115
 
89
- const cmd = new Command('invoices')
116
+ const cmd: Command = new Command('invoices')
90
117
  .aliases(['inv', 'invoice'])
91
118
  .description('Manage invoices (org-scoped — run `use <org>` first)')
92
119
  .option(...outputOption())
93
- .option('--status <status>', 'Filter: draft | finalized | paid | void')
94
- .action(listInvoices)
120
+ filterOptions(cmd).action(listInvoices)
95
121
 
96
122
  cmd.addCommand(
97
- new Command('ls')
123
+ filterOptions(new Command('ls')
98
124
  .description('List invoices (alias of the bare command)')
99
- .option(...outputOption())
100
- .option('--status <status>', 'Filter by status')
125
+ .option(...outputOption()))
101
126
  .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 }
127
+ const self = this.opts() as ListOpts
128
+ const parent = (this.parent?.opts() ?? {}) as ListOpts
104
129
  return listInvoices({
105
130
  output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
106
- status: self.status ?? parent.status,
131
+ ...(self.status ?? parent.status ? { status: (self.status ?? parent.status) as string } : {}),
132
+ ...(self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: (self.paymentStatus ?? parent.paymentStatus) as string } : {}),
133
+ ...(self.overdue ?? parent.overdue ? { overdue: true } : {}),
134
+ ...(self.source ?? parent.source ? { source: (self.source ?? parent.source) as string } : {}),
135
+ ...(self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: (self.fiscalStatus ?? parent.fiscalStatus) as string } : {}),
136
+ ...(self.customerId ?? parent.customerId ? { customerId: (self.customerId ?? parent.customerId) as string } : {}),
137
+ ...(self.externalNumber ?? parent.externalNumber ? { externalNumber: (self.externalNumber ?? parent.externalNumber) as string } : {}),
107
138
  })
108
139
  }),
109
140
  )
@@ -114,12 +145,14 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
114
145
  .requiredOption('--customer <ref>', 'Customer id, short_id, or external_id')
115
146
  .requiredOption('--currency <cur>', 'ISO-4217 currency (e.g. USD)')
116
147
  .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
117
- .action(async (opts: { customer: string; currency: string; line: string[] }) => {
148
+ .option('--number <external>', 'A number another system gave it (up to 64 characters): the invoice keeps it and takes none from the series')
149
+ .action(async (opts: { customer: string; currency: string; line: string[]; number?: string }) => {
118
150
  const lines = opts.line.map(parseLine)
119
151
  const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
120
152
  customer_id: opts.customer,
121
153
  currency: opts.currency,
122
154
  lines,
155
+ ...(opts.number ? { external_number: opts.number } : {}),
123
156
  }).catch(die)
124
157
  success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`)
125
158
  kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
@@ -137,7 +170,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
137
170
  printOutput(inv, opts.output, () => {
138
171
  kv([
139
172
  ['id', String(inv['short_id'])],
140
- ['number', inv['number'] ? `#${inv['number']}` : '— (draft)'],
173
+ ['number', inv['number_text'] ? NUMBER_COL(inv['number_text']) : '— (draft)'],
174
+ ...(inv['external_number'] ? [['external_number', String(inv['external_number'])] as [string, string]] : []),
141
175
  ['status', String(inv['status'])],
142
176
  ['customer', String(inv['customer_name'] ?? inv['customer_id'])],
143
177
  ['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
@@ -184,16 +218,18 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
184
218
  new Command('finalize').argument('<ref>')
185
219
  .description('Finalize a draft — assigns a number, freezes it (immutable)')
186
220
  .option('--due <date>', 'Due date YYYY-MM-DD')
187
- .action(async (ref: string, opts: { due?: string }) => {
221
+ .option('--number <external>', 'A number another system gave it: it becomes the invoice\'s number and the series does not advance')
222
+ .action(async (ref: string, opts: { due?: string; number?: string }) => {
188
223
  const body: Record<string, unknown> = {}
224
+ if (opts.number) body['external_number'] = opts.number
189
225
  if (opts.due) {
190
226
  const ms = Date.parse(opts.due)
191
227
  if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
192
228
  body['due_at'] = ms
193
229
  }
194
230
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
195
- success(`Invoice finalized: #${res.invoice.number}`)
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)]])
231
+ success(`Invoice finalized: ${NUMBER_COL(res.invoice.number_text)}`)
232
+ kv([['id', res.invoice.short_id], ['number', NUMBER_COL(res.invoice.number_text)], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
197
233
  }),
198
234
  )
199
235
 
@@ -224,6 +260,44 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
224
260
  }),
225
261
  )
226
262
 
263
+ const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; time_zone: string; next: number; next_text: string } | null) =>
264
+ n
265
+ ? kv([['prefix', n.prefix], ['digits', String(n.digits)], ['yearly', n.yearly ? 'yes (the counter restarts each year)' : 'no'], ['time_zone', n.time_zone], ['next', `${n.next} → ${n.next_text}`]])
266
+ : console.log('No series: invoices are numbered 1, 2, 3.')
267
+ cmd.addCommand(
268
+ new Command('numbering')
269
+ .description('Show the organization\'s numbering series (needs `invoice.read`)')
270
+ .option(...outputOption())
271
+ .action(async (opts: { output: string }) => {
272
+ const res = await http.get<{ numbering: Parameters<typeof showNumbering>[0] }>('/settings/numbering').catch(die)
273
+ printOutput(res.numbering ?? {}, opts.output, () => showNumbering(res.numbering), 'prefix')
274
+ })
275
+ .addCommand(
276
+ new Command('set')
277
+ .description('Set the series: PREFIX (3 uppercase letters or digits) + the issue year + a counter of --digits. Never renumbers a finalized invoice. Needs `invoice.configure`.')
278
+ .requiredOption('--prefix <prefix>', '3 uppercase letters or digits, e.g. BSF')
279
+ .requiredOption('--digits <n>', 'Counter width, 1 to 12 (9 for e-Fatura)')
280
+ .option('--yearly', 'The counter restarts each calendar year')
281
+ .option('--time-zone <zone>', 'IANA name, e.g. Europe/Istanbul: the year follows the issue date there (kept when omitted; UTC if never set)')
282
+ .option('--next <n>', 'Continue from this counter (this year\'s, when yearly); it can only go forward')
283
+ .action(async (opts: { prefix: string; digits: string; yearly?: boolean; timeZone?: string; next?: string }) => {
284
+ const res = await http.api<{ numbering: Parameters<typeof showNumbering>[0] }>('PUT', '/settings/numbering', {
285
+ prefix: opts.prefix, digits: Number(opts.digits), yearly: !!opts.yearly, ...(opts.next ? { next: Number(opts.next) } : {}), ...(opts.timeZone ? { time_zone: opts.timeZone } : {}),
286
+ }).catch(die)
287
+ success('Numbering series set.')
288
+ showNumbering(res.numbering)
289
+ }),
290
+ )
291
+ .addCommand(
292
+ new Command('clear')
293
+ .description('Back to plain 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`.')
294
+ .action(async () => {
295
+ await http.del('/settings/numbering').catch(die)
296
+ success('No series: invoices are numbered 1, 2, 3.')
297
+ }),
298
+ ),
299
+ )
300
+
227
301
  type TxnRow = {
228
302
  id: string; invoice_number: number; customer_name: string | null; customer_id: string
229
303
  kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
package/src/client.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { newNamesOnFinalize, newNamesOnLines, newNamesOnPayment, oldNamesOnInvoice, oldNamesOnTransaction } from './compat.js'
2
2
  import type {
3
3
  Invoice,
4
+ ListInvoicesOptions,
5
+ MirrorInvoiceInput,
6
+ MirrorResult,
7
+ FiscalInput,
8
+ Numbering,
9
+ NumberingInput,
4
10
  Transaction,
5
11
  CreateInvoiceInput,
6
12
  UpdateInvoiceInput,
@@ -15,6 +21,19 @@ export type {
15
21
  InvoiceLine,
16
22
  InvoiceLineDto,
17
23
  InvoiceDeprecated,
24
+ ExternalRef,
25
+ Fiscal,
26
+ FiscalInput,
27
+ FiscalStatus,
28
+ InvoicePayment,
29
+ InvoiceSource,
30
+ ListInvoicesOptions,
31
+ Metadata,
32
+ MirrorInvoiceInput,
33
+ MirrorResult,
34
+ Numbering,
35
+ NumberingInput,
36
+ PaymentStatus,
18
37
  InvoiceLineDeprecated,
19
38
  TransactionDeprecated,
20
39
  InvoiceLineInput,
@@ -128,11 +147,17 @@ export class InvoiceClient {
128
147
 
129
148
  // ── invoices ──────────────────────────────────────────────────────────────
130
149
 
131
- async list(opts: { limit?: number; offset?: number; status?: string } = {}): Promise<Invoice[]> {
150
+ async list(opts: ListInvoicesOptions = {}): Promise<Invoice[]> {
132
151
  const q = new URLSearchParams()
133
152
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
134
153
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
135
154
  if (opts.status) q.set('status', opts.status)
155
+ if (opts.payment_status) q.set('payment_status', [opts.payment_status].flat().join(','))
156
+ if (opts.overdue !== undefined) q.set('overdue', String(opts.overdue))
157
+ if (opts.source) q.set('source', opts.source)
158
+ if (opts.fiscal_status) q.set('fiscal_status', opts.fiscal_status)
159
+ if (opts.customer_id) q.set('customer_id', opts.customer_id)
160
+ if (opts.external_number) q.set('external_number', opts.external_number)
136
161
  const qs = q.toString()
137
162
  const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
138
163
  return invoices.map(oldNamesOnInvoice)
@@ -149,6 +174,31 @@ export class InvoiceClient {
149
174
  const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/invoices/${ref}`, newNamesOnLines(input))
150
175
  return oldNamesOnInvoice(invoice)
151
176
  }
177
+ /**
178
+ * Keep the provider's document (Stripe's invoice, a hand-entered one) as this invoice: creates it or replaces it by
179
+ * `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
180
+ */
181
+ async mirror(input: MirrorInvoiceInput): Promise<MirrorResult> {
182
+ const r = await this.api<MirrorResult>('PUT', '/invoices/mirror', input)
183
+ return { ...r, invoice: oldNamesOnInvoice(r.invoice) }
184
+ }
185
+ /** The organization's numbering series; `null` while it has none (invoices are numbered 1, 2, 3). */
186
+ async getNumbering(): Promise<Numbering | null> {
187
+ return (await this.api<{ numbering: Numbering | null }>('GET', '/settings/numbering')).numbering
188
+ }
189
+ /** Set the series (`BSF` + issue year + a counter of `digits`). Needs `invoice.configure`. Never renumbers a finalized invoice. */
190
+ async setNumbering(input: NumberingInput): Promise<Numbering> {
191
+ return (await this.api<{ numbering: Numbering }>('PUT', '/settings/numbering', input)).numbering
192
+ }
193
+ /** Back to 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`. */
194
+ async clearNumbering(): Promise<void> {
195
+ await this.api('DELETE', '/settings/numbering')
196
+ }
197
+ /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
198
+ async setFiscal(ref: string, input: FiscalInput): Promise<Invoice> {
199
+ const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/fiscal`, input)
200
+ return oldNamesOnInvoice(invoice)
201
+ }
152
202
  async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
153
203
  const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
154
204
  return oldNamesOnInvoice(invoice)
package/src/events.ts CHANGED
@@ -37,6 +37,10 @@ export const InvoiceEvents = defineAggregate('invoice', {
37
37
  subtotal_cents: z.number().int(),
38
38
  total_cents: z.number().int(),
39
39
  short_id: z.string().min(1),
40
+ // 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
41
+ source: z.string().optional(),
42
+ metadata: z.string().optional(), // JSON object, serialized
43
+ external_number: z.string().optional(), // 1.2.0: a number given by another system ('' = none)
40
44
  at: z.number().int(),
41
45
  }),
42
46
  // Draft edited (customer / lines). Only valid while status = draft.
@@ -46,6 +50,8 @@ export const InvoiceEvents = defineAggregate('invoice', {
46
50
  lines: z.string(),
47
51
  subtotal_cents: z.number().int(),
48
52
  total_cents: z.number().int(),
53
+ metadata: z.string().optional(), // 1.1.0
54
+ external_number: z.string().optional(), // 1.2.0
49
55
  at: z.number().int(),
50
56
  }),
51
57
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -56,6 +62,11 @@ export const InvoiceEvents = defineAggregate('invoice', {
56
62
  total_cents: z.number().int(),
57
63
  issued_at: z.number().int(),
58
64
  due_at: z.number().int(), // 0 = no due date
65
+ // 1.2.0. `number` is the counter of the series (0 when the number is the external one); `number_text` is the number as
66
+ // printed (`BSF2026000000148`, `7`, or the external number); `series_key` says which counter `number` belongs to.
67
+ number_text: z.string().optional(),
68
+ series_key: z.string().optional(),
69
+ external_number: z.string().optional(),
59
70
  at: z.number().int(),
60
71
  }),
61
72
  // A payment applied to a finalized invoice. `amount_paid_cents` is the new running
@@ -67,14 +78,74 @@ export const InvoiceEvents = defineAggregate('invoice', {
67
78
  status: InvoiceStatus,
68
79
  method: z.string(),
69
80
  reference: z.string(),
81
+ payment_id: z.string().optional(), // 1.1.0: the pay record this settles; the idempotency key when present
70
82
  at: z.number().int(),
71
83
  }),
72
84
  InvoiceVoided: z.object({
73
85
  reason: z.string(),
74
86
  at: z.number().int(),
75
87
  }),
88
+ // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
89
+ // first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
90
+ InvoiceMirrored: z.object({
91
+ source: z.string(), // 'stripe' | 'manual'
92
+ mirror_key: z.string().min(1), // `${system}:${external_id}`
93
+ external_refs: z.string(), // JSON array, serialized
94
+ customer_id: z.string().min(1),
95
+ customer_name: z.string(),
96
+ currency: z.string().length(3),
97
+ lines: z.string(),
98
+ subtotal_cents: z.number().int(),
99
+ tax_cents: z.number().int(),
100
+ total_cents: z.number().int(),
101
+ amount_paid_cents: z.number().int(), // from the payment entries, not from the provider
102
+ status: InvoiceStatus,
103
+ issued_at: z.number().int(),
104
+ due_at: z.number().int(), // 0 = none
105
+ paid_at: z.number().int(), // 0 = none
106
+ voided_at: z.number().int(), // 0 = none
107
+ provider_updated_at: z.number().int(),
108
+ metadata: z.string(),
109
+ short_id: z.string().min(1),
110
+ created_at: z.number().int(),
111
+ at: z.number().int(),
112
+ }),
113
+ // 1.1.0. Where the invoice stands with a tax system. Only changed through `invoice.fiscal_update`.
114
+ InvoiceFiscalChanged: z.object({
115
+ status: z.string(), // FISCAL_STATUSES
116
+ system: z.string(),
117
+ external_id: z.string(),
118
+ message: z.string(),
119
+ at: z.number().int(),
120
+ }),
121
+ })
122
+
123
+ /**
124
+ * 1.2.0. An organization's numbering series, and the claims that keep numbers unique. One aggregate, many streams:
125
+ * `numbering-settings` holds the series; one stream per (series key, counter) serializes who takes that number; one per
126
+ * external number serializes who holds it.
127
+ */
128
+ export const NumberingEvents = defineAggregate('numbering', {
129
+ NumberingConfigured: z.object({
130
+ prefix: z.string(), // 3 characters, A-Z 0-9
131
+ digits: z.number().int(),
132
+ yearly: z.boolean(),
133
+ next: z.number().int(), // the counter `next_key` starts from
134
+ next_key: z.string(), // the series key `next` applies to (prefix + year when yearly)
135
+ time_zone: z.string().optional(), // IANA name; absent = UTC. The year in the number and the yearly reset follow it
136
+ at: z.number().int(),
137
+ }),
138
+ NumberingCleared: z.object({ at: z.number().int() }),
139
+ NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
140
+ NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
141
+ ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() }),
76
142
  })
77
143
 
144
+ export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
145
+ export type FiscalStatus = (typeof FISCAL_STATUSES)[number]
146
+ export const INVOICE_SOURCES = ['local', 'stripe', 'manual'] as const
147
+ export type InvoiceSource = (typeof INVOICE_SOURCES)[number]
148
+
78
149
  /**
79
150
  * The transaction ledger — one stream (and one read-model row) PER money movement,
80
151
  * unlike the invoice's cached `amount_paid`. A payment emits BOTH `PaymentRecorded`
@@ -96,6 +167,7 @@ export const TransactionEvents = defineAggregate('transaction', {
96
167
  currency: z.string().length(3),
97
168
  method: z.string(),
98
169
  reference: z.string(),
170
+ payment_id: z.string().optional(), // 1.1.0
99
171
  at: z.number().int(),
100
172
  }),
101
173
  })