@baseworks/invoice 1.2.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  InvoiceEvents,
3
3
  TransactionEvents
4
- } from "./chunk-JS6GUXCC.js";
4
+ } from "./chunk-3MXVPVAV.js";
5
5
 
6
6
  // src/projections.ts
7
7
  import { defineProjection } from "@baseworks/foldbase";
@@ -39,22 +39,32 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
39
39
  lines: e.lines,
40
40
  subtotal_cents: e.subtotal_cents,
41
41
  total_cents: e.total_cents,
42
- issued_at: e.issued_at,
43
- due_at: e.due_at,
42
+ document_date: e.document_date ?? null,
43
+ due_date: e.due_date ?? null,
44
+ issued_at: e.issued_at ?? null,
45
+ // events before 2.0; NULL for newer ones
46
+ due_at: e.due_at ?? null,
44
47
  number_text: e.number_text ?? null,
45
48
  series_key: e.series_key ?? null,
46
49
  external_number: e.external_number ?? null
47
50
  })),
48
51
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
49
52
  amount_paid_cents: e.amount_paid_cents,
50
- status: e.status
53
+ status: e.status,
54
+ paid_date: e.paid_date ?? null
51
55
  })),
52
- InvoiceVoided: on.InvoiceVoided.upsert(() => ({
53
- status: "void"
56
+ InvoiceVoided: on.InvoiceVoided.upsert((e) => ({
57
+ status: "void",
58
+ void_date: e.void_date ?? null,
59
+ void_reason: e.reason,
60
+ voided_at: e.at
54
61
  })),
55
62
  InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
56
63
  external_number: e.external_number
57
64
  })),
65
+ InvoiceExternalNumberCleared: on.InvoiceExternalNumberCleared.upsert(() => ({
66
+ external_number: ""
67
+ })),
58
68
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
59
69
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
60
70
  source: e.source,
@@ -70,10 +80,14 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
70
80
  tax_cents: e.tax_cents,
71
81
  total_cents: e.total_cents,
72
82
  amount_paid_cents: e.amount_paid_cents,
73
- issued_at: e.issued_at,
74
- due_at: e.due_at,
75
- paid_at: e.paid_at,
76
- voided_at: e.voided_at,
83
+ document_date: e.document_date ?? null,
84
+ due_date: e.due_date ?? null,
85
+ paid_date: e.paid_date ?? null,
86
+ void_date: e.void_date ?? null,
87
+ issued_at: e.issued_at ?? null,
88
+ due_at: e.due_at ?? null,
89
+ paid_at: e.paid_at ?? null,
90
+ voided_at: e.voided_at ?? null,
77
91
  provider_updated_at: e.provider_updated_at,
78
92
  metadata: e.metadata,
79
93
  short_id: e.short_id,
@@ -99,6 +113,7 @@ var readTransactions = defineProjection("transactions", TransactionEvents, (on)
99
113
  method: e.method,
100
114
  reference: e.reference,
101
115
  payment_id: e.payment_id ?? null,
116
+ document_date: e.document_date ?? null,
102
117
  created_at: e.at
103
118
  }))
104
119
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "1.2.2",
3
+ "version": "2.0.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": {
@@ -20,6 +20,7 @@
20
20
  ],
21
21
  "dependencies": {
22
22
  "@baseworks/cli": "^0.2.0",
23
+ "@baseworks/core": "^0.6.0",
23
24
  "commander": "^15.0.0",
24
25
  "zod": "^3.25.76",
25
26
  "@baseworks/mcp": "^0.3.0",
@@ -23,12 +23,12 @@ const DRAFT = {
23
23
  total_cents: 150000,
24
24
  amount_paid_cents: 0,
25
25
  balance_cents: 150000,
26
- issued_at: null,
27
- due_at: null,
26
+ document_date: null,
27
+ due_date: null,
28
28
  created_at: 1784200000000,
29
29
  updatedAt: 1784200000000,
30
30
  }
31
- const FINAL = { ...DRAFT, number: 1, number_text: '1', status: 'finalized', issued_at: 1784200000000 }
31
+ const FINAL = { ...DRAFT, number: 1, number_text: '1', display_number: '1', status: 'finalized', document_date: '2026-07-16' }
32
32
  const PAID = { ...FINAL, status: 'paid', amount_paid_cents: 150000, balance_cents: 0 }
33
33
 
34
34
  describe('dtab invoices (list filters)', () => {
@@ -141,12 +141,12 @@ describe('dtab invoices (numbers)', () => {
141
141
  const cap = mocks.mockPostCapture('/invoices', { invoice: DRAFT })
142
142
  await run(['invoices', 'create', '--customer', 'cst1', '--currency', 'USD', '--line', 'x|1|1.00', '--number', 'BSF2026000000148'])
143
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' } })
144
+ const fin = mocks.mockPostCapture('/invoices/inv9x2/finalize', { invoice: { ...FINAL, external_number: 'PORTAL-1', display_number: 'PORTAL-1' } })
145
145
  const r = await run(['invoices', 'finalize', 'inv9x2', '--number', 'PORTAL-1'])
146
146
  expect(fin.body).toMatchObject({ external_number: 'PORTAL-1' })
147
147
  expect(r.stdout).toContain('PORTAL-1')
148
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' }] }) }))
149
+ server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => { seen = new URL(request.url).search; return HttpResponse.json({ invoices: [{ ...FINAL, display_number: 'BSF2026000000148' }] }) }))
150
150
  const list = await run(['invoices', '--external-number', 'BSF2026000000148'])
151
151
  expect(Object.fromEntries(new URLSearchParams(seen))).toEqual({ external_number: 'BSF2026000000148' })
152
152
  expect(list.stdout).toContain('BSF2026000000148')
@@ -167,6 +167,43 @@ describe('dtab invoices (numbers)', () => {
167
167
  }
168
168
  })
169
169
 
170
+ it('dates: finalize, pay, void and the list windows send days as they are; clear-external-number deletes', async () => {
171
+ const sent: Array<[string, string, unknown]> = []
172
+ const record = async (request: Request) => {
173
+ const url = new URL(request.url)
174
+ sent.push([request.method, url.pathname + url.search, request.method === 'POST' ? await request.json() : undefined])
175
+ return HttpResponse.json({ invoice: FINAL, invoices: [], transactions: [] })
176
+ }
177
+ server.use(
178
+ http.post(`${TEST_BASE}/invoices/:ref/:verb`, ({ request }) => record(request)),
179
+ http.get(`${TEST_BASE}/invoices`, ({ request }) => record(request)),
180
+ http.get(`${TEST_BASE}/transactions`, ({ request }) => record(request)),
181
+ http.delete(`${TEST_BASE}/invoices/:ref/external-number`, ({ request }) => record(request)),
182
+ )
183
+ await run(['invoices', 'finalize', 'i1', '--date', '2027-01-05', '--due', '2027-02-05'])
184
+ await run(['invoices', 'pay', 'i1', '--amount', '1.00', '--date', '2027-01-06'])
185
+ await run(['invoices', 'void', 'i1', '--date', '2027-01-07'])
186
+ await run(['invoices', '--from', '2027-01-01', '--to', '2027-01-31'])
187
+ await run(['invoices', 'ls', '--from', '2027-01-01'])
188
+ await run(['invoices', 'payments', '--from', '2027-01-01', '--to', '2027-01-31'])
189
+ await run(['invoices', 'clear-external-number', 'i1'])
190
+ server.use(http.put(`${TEST_BASE}/invoices/:ref/external-number`, async ({ request }) => { sent.push(['PUT', new URL(request.url).pathname, await request.json()]); return HttpResponse.json({ invoice: FINAL }) }))
191
+ await run(['invoices', 'set-external-number', 'i2', 'N-1', '--from-invoice', 'i1'])
192
+ server.use(http.put(`${TEST_BASE}/settings/numbering`, async ({ request }) => { sent.push(['PUT', new URL(request.url).pathname, await request.json()]); return HttpResponse.json({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 500, next_text: 'x', updated_at: 1 } }) }))
193
+ await run(['invoices', 'numbering', 'set', '--prefix', 'BSF', '--digits', '9', '--yearly', '--next', '500', '--year', '2025'])
194
+ expect(sent).toEqual([
195
+ ['POST', '/invoices/i1/finalize', { document_date: '2027-01-05', due_date: '2027-02-05' }],
196
+ ['POST', '/invoices/i1/payments', { amount_cents: 100, document_date: '2027-01-06' }],
197
+ ['POST', '/invoices/i1/void', { reason: '', void_date: '2027-01-07' }],
198
+ ['GET', '/invoices?from=2027-01-01&to=2027-01-31', undefined],
199
+ ['GET', '/invoices?from=2027-01-01', undefined],
200
+ ['GET', '/transactions?from=2027-01-01&to=2027-01-31', undefined],
201
+ ['DELETE', '/invoices/i1/external-number', undefined],
202
+ ['PUT', '/invoices/i2/external-number', { external_number: 'N-1', from_invoice_id: 'i1' }],
203
+ ['PUT', '/settings/numbering', { prefix: 'BSF', digits: 9, yearly: true, next: 500, year: 2025 }],
204
+ ])
205
+ })
206
+
170
207
  it('numbering shows the series, sets it, clears it', async () => {
171
208
  mocks.mockGet('/settings/numbering', { numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } })
172
209
  const shown = await run(['invoices', 'numbering'])
@@ -179,7 +216,7 @@ describe('dtab invoices (numbers)', () => {
179
216
  }))
180
217
  const set = await run(['invoices', 'numbering', 'set', '--prefix', 'BSF', '--digits', '9', '--yearly', '--next', '148', '--time-zone', 'Europe/Istanbul'])
181
218
  expect(set.exitCode).toBe(0)
182
- expect(body).toEqual({ prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' })
219
+ expect(body).toEqual({ prefix: 'BSF', digits: 9, yearly: true, next: 148 }) // --time-zone is ignored since 2.0
183
220
  mocks.mockGet('/settings/numbering', { numbering: null })
184
221
  expect((await run(['invoices', 'numbering'])).stdout).toContain('1, 2, 3')
185
222
  })
@@ -10,7 +10,7 @@ const seen: Array<{ method: string; url: string; org: string | null; auth: strin
10
10
  const INVOICE = {
11
11
  id: 'i1', short_id: 'sh1', number: 7, status: 'finalized', customer_id: 'c1', customer_name: 'Acme', currency: 'EUR',
12
12
  lines: [{ description: 'x', quantity: 2, unit_price_cents: 500, amount_cents: 1000, product_id: null }],
13
- subtotal_cents: 1000, total_cents: 1000, amount_paid_cents: 250, balance_cents: 750, issued_at: 5, due_at: null, created_at: 1, updated_at: 2,
13
+ subtotal_cents: 1000, total_cents: 1000, amount_paid_cents: 250, balance_cents: 750, document_date: '2027-01-05', due_date: null, created_at: 1, updated_at: 2,
14
14
  }
15
15
  const TXN = { id: 't1', invoice_id: 'i1', invoice_number: 7, customer_id: 'c1', customer_name: 'Acme', kind: 'payment', amount_cents: 250, currency: 'EUR', method: null, reference: 'R', created_at: 3 }
16
16
  const f = (async (url: string, init?: RequestInit) => {
@@ -51,7 +51,8 @@ describe('what comes back', () => {
51
51
  expect(inv.shortId).toBe('sh1')
52
52
  expect(inv.customerName).toBe('Acme')
53
53
  expect(inv.balanceCents).toBe(750)
54
- expect(inv.dueAt).toBeNull()
54
+ expect(inv).not.toHaveProperty('dueAt')
55
+ expect([inv.document_date, inv.due_date]).toEqual(['2027-01-05', null])
55
56
  expect(inv.lines[0]!.unitPriceCents).toBe(500)
56
57
  expect(inv.lines[0]!.unit_price_cents).toBe(500)
57
58
  expect((await c.list())[0]!.createdAt).toBe(1)
@@ -132,6 +133,39 @@ describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
132
133
  expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
133
134
  expect(inv.fiscal?.status).toBe('queued')
134
135
  })
136
+ it('2.0: dates go as days, lists take from and to, the external number can be cleared', async () => {
137
+ const sent: Array<[string, string, unknown]> = []
138
+ const fetcher = (async (url: string, init?: RequestInit) => {
139
+ sent.push([init?.method ?? 'GET', url.replace('http://i.test/api', ''), init?.body ? JSON.parse(String(init.body)) : undefined])
140
+ return new Response(JSON.stringify({ invoice: { lines: [] }, invoices: [], transactions: [] }))
141
+ }) as unknown as typeof fetch
142
+ const client = createInvoiceClient({ base_url: 'http://i.test/api', fetch: fetcher })
143
+ await client.finalize('i1', { document_date: '2027-01-05', due_date: '2027-02-05' })
144
+ await client.recordPayment('i1', { amount_cents: 1, document_date: '2027-01-06' })
145
+ await client.void('i1', 'twice', { void_date: '2027-01-07' })
146
+ await client.void('i1')
147
+ await client.list({ from: '2027-01-01', to: '2027-01-31' })
148
+ await client.transactions({ from: '2027-01-01' })
149
+ await client.invoiceTransactionsPage('i1', { to: '2027-01-31' })
150
+ await client.clearExternalNumber('i1')
151
+ await client.setExternalNumber('i2', 'N-1', { from_invoice_id: 'i1' })
152
+ await client.setExternalNumber('i2', 'N-2')
153
+ await client.setNumbering({ prefix: 'BSF', digits: 9, yearly: true, next: 500, year: 2025 })
154
+ expect(sent).toEqual([
155
+ ['POST', '/invoices/i1/finalize', { document_date: '2027-01-05', due_date: '2027-02-05' }],
156
+ ['POST', '/invoices/i1/payments', { amount_cents: 1, document_date: '2027-01-06' }],
157
+ ['POST', '/invoices/i1/void', { reason: 'twice', void_date: '2027-01-07' }],
158
+ ['POST', '/invoices/i1/void', { reason: '' }],
159
+ ['GET', '/invoices?from=2027-01-01&to=2027-01-31', undefined],
160
+ ['GET', '/transactions?from=2027-01-01', undefined],
161
+ ['GET', '/invoices/i1/payments?to=2027-01-31', undefined],
162
+ ['DELETE', '/invoices/i1/external-number', undefined],
163
+ ['PUT', '/invoices/i2/external-number', { external_number: 'N-1', from_invoice_id: 'i1' }],
164
+ ['PUT', '/invoices/i2/external-number', { external_number: 'N-2' }],
165
+ ['PUT', '/settings/numbering', { prefix: 'BSF', digits: 9, yearly: true, next: 500, year: 2025 }],
166
+ ])
167
+ })
168
+
135
169
  it('numbering: get, set and clear; list filters by external_number', async () => {
136
170
  sent.length = 0
137
171
  const h = (async (url: string, init?: RequestInit) => {
@@ -8,7 +8,7 @@ import { invoiceTools } from '../mcp.js'
8
8
 
9
9
  const calls: Array<[string, ...unknown[]]> = []
10
10
  const fake = {
11
- list: async (o: unknown) => { calls.push(['list', o]); return [{ id: 'i1' }] },
11
+ listPage: async (o: unknown) => { calls.push(['listPage', o]); return { invoices: [{ id: 'i1' }], next_offset: null } },
12
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
13
  create: async (a: unknown) => { calls.push(['create', a]); return { id: 'new', ...(a as object) } },
14
14
  update: async (ref: string, a: unknown) => { calls.push(['update', ref, a]); return { id: ref } },
@@ -18,8 +18,8 @@ const fake = {
18
18
  getNumbering: async () => { calls.push(['getNumbering']); return { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } },
19
19
  setExternalNumber: async (ref: string, external_number: string) => { calls.push(['setExternalNumber', ref, external_number]); return { id: ref, external_number } },
20
20
  setNumbering: async (a: unknown) => { calls.push(['setNumbering', a]); return { ...(a as object), next: 1, next_text: 'x', updated_at: 2 } },
21
- transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
22
- invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
21
+ transactionsPage: async (o: unknown) => { calls.push(['transactionsPage', o]); return { transactions: [{ id: 't1' }], next_offset: null } },
22
+ invoiceTransactionsPage: async (ref: string, o: unknown) => { calls.push(['invoiceTransactionsPage', ref, o]); return { transactions: [{ id: 't2' }], next_offset: null } },
23
23
  }
24
24
 
25
25
  async function session(over: Partial<Parameters<typeof runStdio>[0]> = {}) {
@@ -42,10 +42,10 @@ describe('the tool set', () => {
42
42
  expect(tools.map((t) => [t.name, t.access, t.permission])).toEqual([
43
43
  ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_numbering', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
44
44
  ['invoice_create', 'write', 'invoice.write'], ['invoice_update', 'write', 'invoice.write'],
45
- ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_set_external_number', 'write', 'invoice.fiscal_update'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
45
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_set_external_number', 'write', 'invoice.fiscal_update'], ['invoice_clear_external_number', 'write', 'invoice.fiscal_update'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
46
46
  ['invoice_configure_numbering', 'write', 'invoice.configure'], ['invoice_void', 'write', 'invoice.void'],
47
47
  ])
48
- expect(composeTools(tools)).toHaveLength(11)
48
+ expect(composeTools(tools)).toHaveLength(12)
49
49
  expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
50
50
  })
51
51
  it('permission names are the ones invoice-service registers', async () => {
@@ -69,9 +69,9 @@ describe('the tool set', () => {
69
69
  })
70
70
 
71
71
  describe('through a real MCP client', () => {
72
- it('lists the eleven tools; reads are hinted read-only, writes are not', async () => {
72
+ it('lists the twelve tools; reads are hinted read-only, writes are not', async () => {
73
73
  const t = (await (await session()).listTools()).tools
74
- expect(t).toHaveLength(11)
74
+ expect(t).toHaveLength(12)
75
75
  expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
76
76
  for (const n of ['invoice_create', 'invoice_finalize', 'invoice_set_external_number', 'invoice_record_payment', 'invoice_void']) expect(t.find((x) => x.name === n)!.annotations, n).toMatchObject({ readOnlyHint: false })
77
77
  expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
@@ -80,7 +80,7 @@ describe('through a real MCP client', () => {
80
80
  it('list: the filters reach the client; payment_status is a list', async () => {
81
81
  const c = await session()
82
82
  await c.callTool({ name: 'invoice_list', arguments: { payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' } })
83
- expect(calls).toEqual([['list', { limit: 25, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
83
+ expect(calls).toEqual([['listPage', { limit: 100, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
84
84
  for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
85
85
  })
86
86
 
@@ -106,18 +106,18 @@ describe('through a real MCP client', () => {
106
106
  await c.callTool({ name: 'invoice_create', arguments: args })
107
107
  await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', external_number: 'PORTAL-1' } })
108
108
  await c.callTool({ name: 'invoice_list', arguments: { external_number: 'PORTAL-1' } })
109
- expect(calls).toEqual([['create', args], ['finalize', 'i1', { external_number: 'PORTAL-1' }], ['list', { limit: 25, external_number: 'PORTAL-1' }]])
109
+ expect(calls).toEqual([['create', args], ['finalize', 'i1', { external_number: 'PORTAL-1' }], ['listPage', { limit: 100, external_number: 'PORTAL-1' }]])
110
110
  expect(await refused(c, 'invoice_create', { ...args, external_number: 'x'.repeat(65) })).toBeTruthy()
111
111
  const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
112
- expect(d['invoice_create']).toMatch(/takes none from the organization's series/)
113
- expect(d['invoice_finalize']).toMatch(/series does not advance/)
112
+ expect(d['invoice_create']).toMatch(/beside the internal number/)
113
+ expect(d['invoice_finalize']).toMatch(/kept beside the internal number/)
114
114
  expect(d['invoice_numbering']).toMatch(/next_text/)
115
115
  expect(d['invoice_configure_numbering']).toMatch(/administrator/)
116
116
  expect(d['invoice_configure_numbering']).toMatch(/never renumbers/)
117
117
  expect(d['invoice_configure_numbering']).toMatch(/invoice_numbering/)
118
118
  })
119
119
 
120
- it('set_external_number: a write behind the fiscal permission, described as one-time', async () => {
120
+ it('set_external_number: a write behind the fiscal permission, described as changeable', async () => {
121
121
  const c = await session()
122
122
  expect(out(await c.callTool({ name: 'invoice_set_external_number', arguments: { ref: 'i1', external_number: 'GIB-1' } }))).toEqual({ invoice: { id: 'i1', external_number: 'GIB-1' } })
123
123
  expect(calls).toEqual([['setExternalNumber', 'i1', 'GIB-1']])
@@ -125,28 +125,71 @@ describe('through a real MCP client', () => {
125
125
  for (const bad of [{ ref: 'i1' }, { ref: 'i1', external_number: '' }, { ref: 'i1', external_number: 'x'.repeat(65) }]) expect(await refused(c, 'invoice_set_external_number', bad), JSON.stringify(bad)).toBeTruthy()
126
126
  expect(calls).toEqual([])
127
127
  const d = invoiceTools().find((t) => t.name === 'invoice_set_external_number')!.description
128
- expect(d).toMatch(/one-time/)
128
+ expect(d).toMatch(/CHANGES/)
129
129
  expect(d).toMatch(/fiscal permission/)
130
130
  expect(d).toMatch(/WRITES/)
131
131
  const writer = await session({ permissions: async () => ['invoice.read', 'invoice.write', 'invoice.finalize'] })
132
132
  expect((await writer.listTools()).tools.map((x) => x.name)).not.toContain('invoice_set_external_number')
133
133
  })
134
134
 
135
+ it('2.0: dates are checked days, the deprecated ms names still go through, and clear takes only a ref', async () => {
136
+ const seen: unknown[][] = []
137
+ const record = (name: string) => async (...a: unknown[]) => { seen.push([name, ...a]); return { lines: [] } }
138
+ const c = await session({ clients: () => ({ invoice: { finalize: record('finalize'), void: record('void'), recordPayment: record('pay'), clearExternalNumber: record('clear'), listPage: async (o: unknown) => { seen.push(['list', o]); return { invoices: [] } } } }) } as never)
139
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', document_date: '2026-01-05', due_date: '2030-01-01' } })
140
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', issued_at: 5, due_at: 9 } })
141
+ await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 1, document_date: '2026-01-06' } })
142
+ await c.callTool({ name: 'invoice_void', arguments: { ref: 'i1', void_date: '2026-01-07' } })
143
+ await c.callTool({ name: 'invoice_list', arguments: { from: '2026-01-01', to: '2026-01-31' } })
144
+ await c.callTool({ name: 'invoice_clear_external_number', arguments: { ref: 'i1' } })
145
+ expect(seen).toEqual([
146
+ ['finalize', 'i1', { document_date: '2026-01-05', due_date: '2030-01-01' }],
147
+ ['finalize', 'i1', { issued_at: 5, due_at: 9 }],
148
+ ['pay', 'i1', { amount_cents: 1, document_date: '2026-01-06' }],
149
+ ['void', 'i1', undefined, { void_date: '2026-01-07' }],
150
+ ['list', { limit: 100, from: '2026-01-01', to: '2026-01-31' }],
151
+ ['clear', 'i1'],
152
+ ])
153
+ seen.length = 0
154
+ for (const [name, bad] of [['invoice_finalize', { ref: 'i1', document_date: '2999-01-01' }], ['invoice_finalize', { ref: 'i1', due_date: 'soon' }], ['invoice_record_payment', { ref: 'i1', amount_cents: 1, document_date: '2026-02-30' }], ['invoice_clear_external_number', { ref: 'i1', external_number: 'x' }]] as const) {
155
+ expect(await refused(c, name, bad), JSON.stringify(bad)).toBeTruthy()
156
+ }
157
+ expect(seen).toEqual([])
158
+ })
159
+
160
+ it('2.0 review: move and year are passed on; the date tools say what an omitted day means', async () => {
161
+ const seen: unknown[][] = []
162
+ const c = await session({ clients: () => ({ invoice: {
163
+ setExternalNumber: async (...a: unknown[]) => { seen.push(['set', ...a]); return { lines: [] } },
164
+ setNumbering: async (...a: unknown[]) => { seen.push(['numbering', ...a]); return {} },
165
+ } }) } as never)
166
+ await c.callTool({ name: 'invoice_set_external_number', arguments: { ref: 'i2', external_number: 'N-1', from_invoice_id: 'i1' } })
167
+ await c.callTool({ name: 'invoice_set_external_number', arguments: { ref: 'i2', external_number: 'N-2' } })
168
+ await c.callTool({ name: 'invoice_configure_numbering', arguments: { prefix: 'BSF', digits: 9, yearly: true, next: 500, year: 2025 } })
169
+ expect(seen).toEqual([['set', 'i2', 'N-1', { from_invoice_id: 'i1' }], ['set', 'i2', 'N-2', {}], ['numbering', { prefix: 'BSF', digits: 9, yearly: true, next: 500, year: 2025 }]])
170
+ expect(await refused(c, 'invoice_configure_numbering', { prefix: 'BSF', digits: 9, yearly: true, year: 0 })).toBeTruthy()
171
+ const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
172
+ for (const n of ['invoice_finalize', 'invoice_record_payment', 'invoice_void']) {
173
+ expect(d[n], n).toMatch(/send the day the user means: omitted, it is today in UTC, which is yesterday in Türkiye between 00:00 and 03:00/)
174
+ }
175
+ expect(d['invoice_set_external_number']).toMatch(/from_invoice_id/)
176
+ })
177
+
135
178
  it('record_payment: payment_id is passed on', async () => {
136
179
  const c = await session()
137
180
  await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
138
181
  expect(calls).toEqual([['recordPayment', 'i1', { amount_cents: 5, payment_id: 'pay_1' }]])
139
182
  })
140
183
 
141
- it('list: a status and a page; defaults to 25', async () => {
184
+ it('list: a status and a page; defaults to 100', async () => {
142
185
  const c = await session()
143
- expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
144
- expect(calls).toEqual([['list', { limit: 5, offset: 10, status: 'finalized' }]])
186
+ expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }], next: null })
187
+ expect(calls).toEqual([['listPage', { limit: 5, offset: 10, status: 'finalized' }]])
145
188
  calls.length = 0
146
189
  await c.callTool({ name: 'invoice_list', arguments: {} })
147
- expect(calls).toEqual([['list', { limit: 25 }]])
190
+ expect(calls).toEqual([['listPage', { limit: 100 }]])
148
191
  calls.length = 0
149
- for (const args of [{ limit: 0 }, { limit: 101 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
192
+ for (const args of [{ limit: 0 }, { limit: 501 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
150
193
  expect(calls).toEqual([])
151
194
  })
152
195
 
@@ -160,9 +203,9 @@ describe('through a real MCP client', () => {
160
203
 
161
204
  it('transactions: one invoice\'s, or the organization\'s', async () => {
162
205
  const c = await session()
163
- expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }] })
164
- expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }] })
165
- expect(calls).toEqual([['invoiceTransactions', 'i1'], ['transactions', { limit: 3 }]])
206
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }], next: null })
207
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }], next: null })
208
+ expect(calls).toEqual([['invoiceTransactionsPage', 'i1', { limit: 100 }], ['transactionsPage', { limit: 3 }]])
166
209
  })
167
210
 
168
211
  it('create: lines in snake_case reach the client; what the API would refuse is refused here', async () => {
@@ -213,3 +256,64 @@ describe('through a real MCP client', () => {
213
256
  expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_numbering', 'invoice_transactions', 'invoice_create', 'invoice_update'])
214
257
  })
215
258
  })
259
+
260
+ describe.each([
261
+ ['invoice_list', 'listPage', 'invoices', { status: 'finalized' }],
262
+ ['invoice_transactions', 'transactionsPage', 'transactions', {}],
263
+ ['invoice_transactions', 'invoiceTransactionsPage', 'transactions', { ref: 'i1' }],
264
+ ] as const)('%s is paged (%s)', (tool, method, key, filters) => {
265
+ const rows = Array.from({ length: 7 }, (_, i) => ({ id: `r${i}` }))
266
+ /** The service's paging over `rows`; the query is the last argument. */
267
+ const paged = { ...fake, [method]: async (...args: unknown[]) => {
268
+ const q = args[args.length - 1] as { limit: number; offset?: number }
269
+ calls.push([method, q])
270
+ const from = q.offset ?? 0
271
+ return { [key]: rows.slice(from, from + q.limit), next_offset: from + q.limit < rows.length ? from + q.limit : null }
272
+ } }
273
+ const open = () => session({ clients: () => ({ invoice: paged }) } as never)
274
+ const sent = () => calls.map((x) => x[1] as { limit: number; offset?: number })
275
+
276
+ it('asks for the first page of 100 by default', async () => {
277
+ const c = await open()
278
+ const page = out(await c.callTool({ name: tool, arguments: filters }))
279
+ expect(page[key].map((r: { id: string }) => r.id)).toEqual(rows.map((r) => r.id))
280
+ expect(page.next).toBeNull()
281
+ expect(sent()).toHaveLength(1)
282
+ expect(sent()[0]!.limit).toBe(100)
283
+ expect(sent()[0]!.offset ?? 0).toBe(0)
284
+ })
285
+ it('walks to the end with `next` as the cursor', async () => {
286
+ const c = await open()
287
+ const seen: string[] = []
288
+ let cursor: string | null = null
289
+ do {
290
+ const page: Record<string, unknown> = out(await c.callTool({ name: tool, arguments: { ...filters, limit: 3, ...(cursor ? { cursor } : {}) } }))
291
+ seen.push(...(page[key] as Array<{ id: string }>).map((r) => r.id))
292
+ cursor = page['next'] as string | null
293
+ } while (cursor)
294
+ expect(seen).toEqual(rows.map((r) => r.id))
295
+ expect(sent().map((q) => q.offset ?? 0)).toEqual([0, 3, 6])
296
+ })
297
+ it('takes 500, refuses 501 and a cursor it did not give', async () => {
298
+ const c = await open()
299
+ await c.callTool({ name: tool, arguments: { ...filters, limit: 500 } })
300
+ expect(sent()[0]!.limit).toBe(500)
301
+ calls.length = 0
302
+ expect(await refused(c, tool, { ...filters, limit: 501 })).toBeTruthy()
303
+ expect(out(await c.callTool({ name: tool, arguments: { ...filters, cursor: '100' } }))).toMatchObject({ error: 'invalid_cursor', status: 400 })
304
+ expect(calls).toEqual([])
305
+ })
306
+ it('still takes the deprecated `offset`, and refuses it together with `cursor`', async () => {
307
+ const c = await open()
308
+ const page = out(await c.callTool({ name: tool, arguments: { ...filters, offset: 2, limit: 3 } }))
309
+ expect(page[key].map((r: { id: string }) => r.id)).toEqual(['r2', 'r3', 'r4'])
310
+ calls.length = 0
311
+ const both = out(await c.callTool({ name: tool, arguments: { ...filters, offset: 0, cursor: page.next } }))
312
+ expect(both).toMatchObject({ error: 'bad_request', status: 400 })
313
+ expect(calls).toEqual([])
314
+ })
315
+ it('says how to page', () => {
316
+ const d = invoiceTools().find((t) => t.name === tool)!.description
317
+ for (const w of ['default 100', 'max 500', 'cursor: next']) expect(d, w).toContain(w)
318
+ })
319
+ })