@baseworks/invoice 1.1.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.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  InvoiceEvents,
3
3
  TransactionEvents
4
- } from "./chunk-335MPCTE.js";
4
+ } from "./chunk-THLNZVGO.js";
5
5
 
6
6
  // src/projections.ts
7
7
  import { defineProjection } from "@baseworks/foldbase";
@@ -21,6 +21,7 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
21
21
  short_id: e.short_id,
22
22
  source: e.source ?? null,
23
23
  metadata: e.metadata ?? null,
24
+ external_number: e.external_number ?? null,
24
25
  created_at: e.at
25
26
  })),
26
27
  InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
@@ -29,7 +30,8 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
29
30
  lines: e.lines,
30
31
  subtotal_cents: e.subtotal_cents,
31
32
  total_cents: e.total_cents,
32
- metadata: e.metadata ?? null
33
+ metadata: e.metadata ?? null,
34
+ external_number: e.external_number ?? null
33
35
  })),
34
36
  InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
35
37
  number: e.number,
@@ -38,7 +40,10 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
38
40
  subtotal_cents: e.subtotal_cents,
39
41
  total_cents: e.total_cents,
40
42
  issued_at: e.issued_at,
41
- due_at: e.due_at
43
+ due_at: e.due_at,
44
+ number_text: e.number_text ?? null,
45
+ series_key: e.series_key ?? null,
46
+ external_number: e.external_number ?? null
42
47
  })),
43
48
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
44
49
  amount_paid_cents: e.amount_paid_cents,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Invoice capability: typed HTTP client, event catalog, projections, and CLI plugin for invoice-service (AR ledger). Contract-first, versioned with the service.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -12,6 +12,8 @@ const DRAFT = {
12
12
  id: '019f6a3e-1111-7c71-beff-496d1be3fd1f',
13
13
  short_id: 'inv9x2',
14
14
  number: null,
15
+ number_text: null,
16
+ external_number: null,
15
17
  status: 'draft',
16
18
  customer_id: 'cst1',
17
19
  customer_name: 'Acme Co',
@@ -26,7 +28,7 @@ const DRAFT = {
26
28
  created_at: 1784200000000,
27
29
  updatedAt: 1784200000000,
28
30
  }
29
- const FINAL = { ...DRAFT, number: 1, status: 'finalized', issued_at: 1784200000000 }
31
+ const FINAL = { ...DRAFT, number: 1, number_text: '1', status: 'finalized', issued_at: 1784200000000 }
30
32
  const PAID = { ...FINAL, status: 'paid', amount_paid_cents: 150000, balance_cents: 0 }
31
33
 
32
34
  describe('dtab invoices (list filters)', () => {
@@ -133,3 +135,37 @@ describe('dtab invoices get / finalize / pay / void', () => {
133
135
  expect(r.stdout).toContain('inv9x2')
134
136
  })
135
137
  })
138
+
139
+ describe('dtab invoices (numbers)', () => {
140
+ it('create and finalize pass --number as the external number; the list filters by --external-number', async () => {
141
+ const cap = mocks.mockPostCapture('/invoices', { invoice: DRAFT })
142
+ await run(['invoices', 'create', '--customer', 'cst1', '--currency', 'USD', '--line', 'x|1|1.00', '--number', 'BSF2026000000148'])
143
+ expect(cap.body).toMatchObject({ external_number: 'BSF2026000000148' })
144
+ const fin = mocks.mockPostCapture('/invoices/inv9x2/finalize', { invoice: { ...FINAL, number: null, number_text: 'PORTAL-1', external_number: 'PORTAL-1' } })
145
+ const r = await run(['invoices', 'finalize', 'inv9x2', '--number', 'PORTAL-1'])
146
+ expect(fin.body).toMatchObject({ external_number: 'PORTAL-1' })
147
+ expect(r.stdout).toContain('PORTAL-1')
148
+ let seen = ''
149
+ server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => { seen = new URL(request.url).search; return HttpResponse.json({ invoices: [{ ...FINAL, number_text: 'BSF2026000000148' }] }) }))
150
+ const list = await run(['invoices', '--external-number', 'BSF2026000000148'])
151
+ expect(Object.fromEntries(new URLSearchParams(seen))).toEqual({ external_number: 'BSF2026000000148' })
152
+ expect(list.stdout).toContain('BSF2026000000148')
153
+ })
154
+
155
+ it('numbering shows the series, sets it, clears it', async () => {
156
+ mocks.mockGet('/settings/numbering', { numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } })
157
+ const shown = await run(['invoices', 'numbering'])
158
+ expect(shown.exitCode).toBe(0)
159
+ expect(shown.stdout).toContain('BSF2026000000149')
160
+ let body: unknown
161
+ server.use(http.put(`${TEST_BASE}/settings/numbering`, async ({ request }) => {
162
+ body = await request.json()
163
+ return HttpResponse.json({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 148, next_text: 'BSF2026000000148', updated_at: 2 } })
164
+ }))
165
+ const set = await run(['invoices', 'numbering', 'set', '--prefix', 'BSF', '--digits', '9', '--yearly', '--next', '148', '--time-zone', 'Europe/Istanbul'])
166
+ expect(set.exitCode).toBe(0)
167
+ expect(body).toEqual({ prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' })
168
+ mocks.mockGet('/settings/numbering', { numbering: null })
169
+ expect((await run(['invoices', 'numbering'])).stdout).toContain('1, 2, 3')
170
+ })
171
+ })
@@ -124,6 +124,25 @@ describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
124
124
  expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
125
125
  expect(inv.fiscal?.status).toBe('queued')
126
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
+ })
127
146
  it('recordPayment sends payment_id', async () => {
128
147
  sent.length = 0
129
148
  await c().recordPayment('i1', { amount_cents: 5, payment_id: 'pay_1' })
@@ -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,9 +68,9 @@ 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'])
@@ -80,6 +83,39 @@ describe('through a real MCP client', () => {
80
83
  for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
81
84
  })
82
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
+
83
119
  it('record_payment: payment_id is passed on', async () => {
84
120
  const c = await session()
85
121
  await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
@@ -158,6 +194,6 @@ describe('through a real MCP client', () => {
158
194
 
159
195
  it('a permission reader hides what the person may not do', async () => {
160
196
  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'])
197
+ expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_numbering', 'invoice_transactions', 'invoice_create', 'invoice_update'])
162
198
  })
163
199
  })
package/src/cli.ts CHANGED
@@ -33,6 +33,8 @@ 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
36
38
  payment_status?: string
37
39
  source?: string
38
40
  fiscal?: { status: string } | null
@@ -65,7 +67,8 @@ function parseLine(spec: string): { description: string; quantity: number; unit_
65
67
  return { description, quantity, unit_price_cents: toCents(parts[2]!.trim(), '--line unitPrice') }
66
68
  }
67
69
 
68
- 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)) : '—')
69
72
 
70
73
  /** The list's filters, on the bare command and on `ls`. */
71
74
  const filterOptions = (c: Command): Command =>
@@ -75,12 +78,13 @@ const filterOptions = (c: Command): Command =>
75
78
  .option('--source <source>', 'local | stripe | manual')
76
79
  .option('--fiscal-status <status>', 'not_submitted | queued | submitted | accepted | rejected | cancelled')
77
80
  .option('--customer-id <id>', 'Only this customer (its id)')
81
+ .option('--external-number <number>', 'Only the invoice with this external number (exact)')
78
82
 
79
83
  export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
80
84
  const { http } = deps
81
85
  const cli = deps.cliName ?? 'cli'
82
86
 
83
- type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string }
87
+ type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
84
88
  const listInvoices = async (opts: ListOpts) => {
85
89
  const params = new URLSearchParams()
86
90
  if (opts.status) params.set('status', opts.status)
@@ -89,12 +93,13 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
89
93
  if (opts.source) params.set('source', opts.source)
90
94
  if (opts.fiscalStatus) params.set('fiscal_status', opts.fiscalStatus)
91
95
  if (opts.customerId) params.set('customer_id', opts.customerId)
96
+ if (opts.externalNumber) params.set('external_number', opts.externalNumber)
92
97
  const q = params.toString() ? `?${params}` : ''
93
98
  const res = await http.get<{ invoices: InvoiceRow[] }>(`/invoices${q}`).catch(die)
94
99
  printOutput(res.invoices, opts.output, (wide) => {
95
100
  table(res.invoices, [
96
101
  { key: 'short_id', label: 'ID' },
97
- { key: 'number', label: 'NO', fmt: NUMBER_COL },
102
+ { key: 'number_text', label: 'NO', fmt: NUMBER_COL },
98
103
  { key: 'status', label: 'STATUS' },
99
104
  { key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
100
105
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
@@ -129,6 +134,7 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
129
134
  ...(self.source ?? parent.source ? { source: (self.source ?? parent.source) as string } : {}),
130
135
  ...(self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: (self.fiscalStatus ?? parent.fiscalStatus) as string } : {}),
131
136
  ...(self.customerId ?? parent.customerId ? { customerId: (self.customerId ?? parent.customerId) as string } : {}),
137
+ ...(self.externalNumber ?? parent.externalNumber ? { externalNumber: (self.externalNumber ?? parent.externalNumber) as string } : {}),
132
138
  })
133
139
  }),
134
140
  )
@@ -139,12 +145,14 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
139
145
  .requiredOption('--customer <ref>', 'Customer id, short_id, or external_id')
140
146
  .requiredOption('--currency <cur>', 'ISO-4217 currency (e.g. USD)')
141
147
  .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
142
- .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 }) => {
143
150
  const lines = opts.line.map(parseLine)
144
151
  const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
145
152
  customer_id: opts.customer,
146
153
  currency: opts.currency,
147
154
  lines,
155
+ ...(opts.number ? { external_number: opts.number } : {}),
148
156
  }).catch(die)
149
157
  success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`)
150
158
  kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)]])
@@ -162,7 +170,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
162
170
  printOutput(inv, opts.output, () => {
163
171
  kv([
164
172
  ['id', String(inv['short_id'])],
165
- ['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]] : []),
166
175
  ['status', String(inv['status'])],
167
176
  ['customer', String(inv['customer_name'] ?? inv['customer_id'])],
168
177
  ['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
@@ -209,16 +218,18 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
209
218
  new Command('finalize').argument('<ref>')
210
219
  .description('Finalize a draft — assigns a number, freezes it (immutable)')
211
220
  .option('--due <date>', 'Due date YYYY-MM-DD')
212
- .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 }) => {
213
223
  const body: Record<string, unknown> = {}
224
+ if (opts.number) body['external_number'] = opts.number
214
225
  if (opts.due) {
215
226
  const ms = Date.parse(opts.due)
216
227
  if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
217
228
  body['due_at'] = ms
218
229
  }
219
230
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
220
- success(`Invoice finalized: #${res.invoice.number}`)
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)]])
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)]])
222
233
  }),
223
234
  )
224
235
 
@@ -249,6 +260,44 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
249
260
  }),
250
261
  )
251
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
+
252
301
  type TxnRow = {
253
302
  id: string; invoice_number: number; customer_name: string | null; customer_id: string
254
303
  kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
package/src/client.ts CHANGED
@@ -5,6 +5,8 @@ import type {
5
5
  MirrorInvoiceInput,
6
6
  MirrorResult,
7
7
  FiscalInput,
8
+ Numbering,
9
+ NumberingInput,
8
10
  Transaction,
9
11
  CreateInvoiceInput,
10
12
  UpdateInvoiceInput,
@@ -29,6 +31,8 @@ export type {
29
31
  Metadata,
30
32
  MirrorInvoiceInput,
31
33
  MirrorResult,
34
+ Numbering,
35
+ NumberingInput,
32
36
  PaymentStatus,
33
37
  InvoiceLineDeprecated,
34
38
  TransactionDeprecated,
@@ -153,6 +157,7 @@ export class InvoiceClient {
153
157
  if (opts.source) q.set('source', opts.source)
154
158
  if (opts.fiscal_status) q.set('fiscal_status', opts.fiscal_status)
155
159
  if (opts.customer_id) q.set('customer_id', opts.customer_id)
160
+ if (opts.external_number) q.set('external_number', opts.external_number)
156
161
  const qs = q.toString()
157
162
  const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
158
163
  return invoices.map(oldNamesOnInvoice)
@@ -177,6 +182,18 @@ export class InvoiceClient {
177
182
  const r = await this.api<MirrorResult>('PUT', '/invoices/mirror', input)
178
183
  return { ...r, invoice: oldNamesOnInvoice(r.invoice) }
179
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
+ }
180
197
  /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
181
198
  async setFiscal(ref: string, input: FiscalInput): Promise<Invoice> {
182
199
  const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/fiscal`, input)
package/src/events.ts CHANGED
@@ -40,6 +40,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
40
40
  // 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
41
41
  source: z.string().optional(),
42
42
  metadata: z.string().optional(), // JSON object, serialized
43
+ external_number: z.string().optional(), // 1.2.0: a number given by another system ('' = none)
43
44
  at: z.number().int(),
44
45
  }),
45
46
  // Draft edited (customer / lines). Only valid while status = draft.
@@ -50,6 +51,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
50
51
  subtotal_cents: z.number().int(),
51
52
  total_cents: z.number().int(),
52
53
  metadata: z.string().optional(), // 1.1.0
54
+ external_number: z.string().optional(), // 1.2.0
53
55
  at: z.number().int(),
54
56
  }),
55
57
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -60,6 +62,11 @@ export const InvoiceEvents = defineAggregate('invoice', {
60
62
  total_cents: z.number().int(),
61
63
  issued_at: z.number().int(),
62
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(),
63
70
  at: z.number().int(),
64
71
  }),
65
72
  // A payment applied to a finalized invoice. `amount_paid_cents` is the new running
@@ -113,6 +120,27 @@ export const InvoiceEvents = defineAggregate('invoice', {
113
120
  }),
114
121
  })
115
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() }),
142
+ })
143
+
116
144
  export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
117
145
  export type FiscalStatus = (typeof FISCAL_STATUSES)[number]
118
146
  export const INVOICE_SOURCES = ['local', 'stripe', 'manual'] as const
package/src/mcp.ts CHANGED
@@ -38,7 +38,7 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
38
38
  description:
39
39
  'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
40
40
  'Each invoice has its totals, the amount paid, the `balance_cents` still owed and a `payment_status` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: ' +
41
- 'filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
41
+ 'filter with `payment_status`, `overdue`, `source`, `fiscal_status`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
42
42
  input: z.object({
43
43
  status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
44
44
  payment_status: z.array(z.enum(['unpaid', 'partially_paid', 'paid', 'not_due'])).min(1).optional().describe('Only invoices in one of these payment states. `unpaid` and `partially_paid` are what is still owed; `not_due` is a draft or void invoice.'),
@@ -46,17 +46,18 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
46
46
  source: z.enum(['local', 'stripe', 'manual']).optional().describe('`local` was made here, `stripe` mirrors a Stripe invoice, `manual` was entered from a document issued elsewhere.'),
47
47
  fiscal_status: z.enum(['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled']).optional().describe('Only invoices in this state with a tax system.'),
48
48
  customer_id: z.string().optional().describe('Only this customer\'s invoices: the customer\'s id.'),
49
+ external_number: z.string().optional().describe('Only the invoice with this exact external number (the number another system gave it).'),
49
50
  limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
50
51
  offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
51
52
  }),
52
53
  access: 'read',
53
54
  permission: 'invoice.read',
54
- run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; limit?: number; offset?: number }) => ({
55
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; external_number?: string; limit?: number; offset?: number }) => ({
55
56
  invoices: await ctx.clients.invoice.list({
56
57
  limit: a.limit ?? 25,
57
58
  ...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}),
58
59
  ...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
59
- ...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}),
60
+ ...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}), ...(a.external_number ? { external_number: a.external_number } : {}),
60
61
  }),
61
62
  }),
62
63
  }),
@@ -73,6 +74,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
73
74
  run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string }) => ({ invoice: await ctx.clients.invoice.get(a.ref) }),
74
75
  }),
75
76
 
77
+ defineTool({
78
+ name: 'invoice_numbering',
79
+ title: 'Show the numbering series',
80
+ description:
81
+ 'Shows how the organization numbers its invoices: `{ prefix, digits, yearly, time_zone, next, next_text }`, or `null` when it has no series and invoices are numbered 1, 2, 3. ' +
82
+ '`next_text` is the number the next invoice finalized now would get (for example BSF2026000000149: the prefix, the issue year, then the counter). ' +
83
+ 'Read it before you finalize or before you tell someone what an invoice\'s number will be. Changing the series is invoice_configure_numbering, which is for administrators. Read only.',
84
+ input: z.object({}),
85
+ access: 'read',
86
+ permission: 'invoice.read',
87
+ run: async (ctx: { clients: InvoiceMcpClients }) => ({ numbering: await ctx.clients.invoice.getNumbering() }),
88
+ }),
89
+
76
90
  defineTool({
77
91
  name: 'invoice_transactions',
78
92
  title: 'List payments',
@@ -100,15 +114,17 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
100
114
  'Creates a DRAFT invoice for a customer and returns it. WRITES. The draft has no number and nothing is owed until it is finalized (invoice_finalize), so it is safe to prepare and then show the user. ' +
101
115
  'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
102
116
  'Lines carry a description, a quantity and a unit price in integer cents; the amounts and totals are computed for you. There is no tax in this version. ' +
117
+ 'Give `external_number` only when another system (an e-Fatura portal, say) has already given this invoice a number: the invoice keeps it and takes none from the organization\'s series. Otherwise leave it out; the number comes when the invoice is finalized. ' +
103
118
  'It is recorded as you, the agent acting for the person who connected you.',
104
119
  input: z.object({
105
120
  customer_id,
106
121
  currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
107
122
  lines: z.array(Line).min(1).describe('At least one line.'),
123
+ external_number: z.string().min(1).max(64).optional().describe('A number another system already gave this invoice (an e-Fatura portal\'s, say), up to 64 characters. Give it only when you have one: the invoice then keeps it as its number and takes none from the organization\'s series. Unique among the organization\'s invoices (`external_number_taken`).'),
108
124
  }),
109
125
  access: 'write',
110
126
  permission: 'invoice.write',
111
- run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[] }) => ({
127
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[]; external_number?: string }) => ({
112
128
  invoice: await ctx.clients.invoice.create(a),
113
129
  }),
114
130
  }),
@@ -137,17 +153,18 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
137
153
  name: 'invoice_finalize',
138
154
  title: 'Finalize an invoice',
139
155
  description:
140
- 'Issues a draft: it gets the next number of the organization, its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
156
+ 'Issues a draft: it gets the next number of the organization\'s series (see invoice_numbering for what that reads like), its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
141
157
  'Ask the user to confirm before you do it. Optionally set `issued_at` and `due_at` (epoch milliseconds; the issue date defaults to now, no due date by default). ' +
142
- 'Only a draft can be finalized: otherwise `not_draft`.',
158
+ 'If another system already numbered it, give `external_number`: that becomes the invoice\'s number and the series does not advance. Only a draft can be finalized: otherwise `not_draft`.',
143
159
  input: z.object({
144
160
  ref: REF,
145
161
  issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
146
162
  due_at: z.number().int().optional().describe('Epoch milliseconds; omit for no due date.'),
163
+ external_number: z.string().min(1).max(64).optional().describe('A number another system already gave this invoice. Then it IS the invoice\'s number and the organization\'s series does not advance. Leave it out to take the next number of the series (a configured one such as BSF2026000000149, else 1, 2, 3). Refused with `external_number_set` if the invoice already has a different one.'),
147
164
  }),
148
165
  access: 'write',
149
166
  permission: 'invoice.finalize',
150
- async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number }) {
167
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number; external_number?: string }) {
151
168
  const { ref, ...input } = a
152
169
  return { invoice: await ctx.clients.invoice.finalize(ref, input) }
153
170
  },
@@ -176,6 +193,25 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
176
193
  },
177
194
  }),
178
195
 
196
+ defineTool({
197
+ name: 'invoice_configure_numbering',
198
+ title: 'Set the numbering series',
199
+ description:
200
+ 'Sets how the organization numbers its invoices from now on: a `prefix` of 3 uppercase letters or digits, then the issue year, then a counter zero-padded to `digits` (prefix BSF, 9 digits: BSF2026000000148). ' +
201
+ 'WRITES, and it is for an administrator (permission `invoice.configure`). It never renumbers a finalized invoice. `yearly: true` restarts the counter each calendar year; the year (in the number and for the restart) is that of the issue date in `time_zone`, so set the organization\'s zone (e.g. Europe/Istanbul) or numbers issued around New Year land in the wrong year (UTC when never set); `next` continues an existing series from that counter and can only go forward (`next_behind` otherwise). ' +
202
+ 'Ask the person to confirm the prefix, the width and the next number before you change it: these are legal numbers. Use invoice_numbering to read the current series; to give one invoice a number from another system use `external_number` on invoice_create or invoice_finalize instead.',
203
+ input: z.object({
204
+ prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe('Exactly 3 uppercase letters or digits.'),
205
+ digits: z.number().int().min(1).max(12).describe('Counter width: 9 for e-Fatura.'),
206
+ yearly: z.boolean().describe('true: the counter restarts each calendar year (of the issue date).'),
207
+ time_zone: z.string().min(1).max(64).optional().describe('IANA time zone name, e.g. Europe/Istanbul. Omit to keep the current one (UTC if never set).'),
208
+ next: z.number().int().min(1).optional().describe('The counter to continue from (this year\'s, when yearly). Omit to continue where the series is.'),
209
+ }),
210
+ access: 'write',
211
+ permission: 'invoice.configure',
212
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { prefix: string; digits: number; yearly: boolean; time_zone?: string; next?: number }) => ({ numbering: await ctx.clients.invoice.setNumbering(a) }),
213
+ }),
214
+
179
215
  defineTool({
180
216
  name: 'invoice_void',
181
217
  title: 'Void an invoice',
@@ -25,6 +25,7 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
25
25
  short_id: e.short_id,
26
26
  source: e.source ?? null,
27
27
  metadata: e.metadata ?? null,
28
+ external_number: e.external_number ?? null,
28
29
  created_at: e.at,
29
30
  })),
30
31
  InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
@@ -34,6 +35,7 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
34
35
  subtotal_cents: e.subtotal_cents,
35
36
  total_cents: e.total_cents,
36
37
  metadata: e.metadata ?? null,
38
+ external_number: e.external_number ?? null,
37
39
  })),
38
40
  InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
39
41
  number: e.number,
@@ -43,6 +45,9 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
43
45
  total_cents: e.total_cents,
44
46
  issued_at: e.issued_at,
45
47
  due_at: e.due_at,
48
+ number_text: e.number_text ?? null,
49
+ series_key: e.series_key ?? null,
50
+ external_number: e.external_number ?? null,
46
51
  })),
47
52
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
48
53
  amount_paid_cents: e.amount_paid_cents,