@baseworks/invoice 1.2.3 → 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.3",
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) => {
@@ -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'])
@@ -109,15 +109,15 @@ describe('through a real MCP client', () => {
109
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,13 +125,56 @@ 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' } })
package/src/cli.ts CHANGED
@@ -13,8 +13,9 @@ import type { ApiClient } from '@baseworks/cli/client'
13
13
  *
14
14
  * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
15
15
  * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
16
- * `invoices finalize <ref>` · `invoices set-external-number <ref> <number>` ·
17
- * `invoices pay <ref> --amount 150.00` · `invoices void <ref>`
16
+ * `invoices finalize <ref> [--date YYYY-MM-DD]` · `invoices set-external-number <ref> <number>` ·
17
+ * `invoices clear-external-number <ref>` · `invoices pay <ref> --amount 150.00` · `invoices void <ref>` ·
18
+ * `invoices ls --from 2027-01-01 --to 2027-01-31`
18
19
  */
19
20
  export interface InvoiceCliDeps {
20
21
  http: ApiClient
@@ -33,6 +34,9 @@ type InvoiceRow = {
33
34
  amount_paid_cents: number
34
35
  balance_cents: number
35
36
  created_at?: number
37
+ document_date?: string | null
38
+ due_date?: string | null
39
+ display_number?: string | null
36
40
  number_text?: string | null
37
41
  external_number?: string | null
38
42
  payment_status?: string
@@ -73,6 +77,8 @@ const NUMBER_COL = (v: unknown): string => (v ? (/^\d+$/.test(String(v)) ? `#${v
73
77
  /** The list's filters, on the bare command and on `ls`. */
74
78
  const filterOptions = (c: Command): Command =>
75
79
  c.option('--status <status>', 'Filter: draft | finalized | paid | void')
80
+ .option('--from <date>', 'Invoice date on or after, YYYY-MM-DD')
81
+ .option('--to <date>', 'Invoice date on or before, YYYY-MM-DD')
76
82
  .option('--payment-status <list>', 'unpaid | partially_paid | paid | not_due (comma-separated)')
77
83
  .option('--overdue', 'Owed, with a due date in the past')
78
84
  .option('--source <source>', 'local | stripe | manual')
@@ -84,9 +90,11 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
84
90
  const { http } = deps
85
91
  const cli = deps.cliName ?? 'cli'
86
92
 
87
- type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
93
+ type ListOpts = { output: string; from?: string; to?: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
88
94
  const listInvoices = async (opts: ListOpts) => {
89
95
  const params = new URLSearchParams()
96
+ if (opts.from) params.set('from', opts.from)
97
+ if (opts.to) params.set('to', opts.to)
90
98
  if (opts.status) params.set('status', opts.status)
91
99
  if (opts.paymentStatus) params.set('payment_status', opts.paymentStatus)
92
100
  if (opts.overdue) params.set('overdue', 'true')
@@ -99,7 +107,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
99
107
  printOutput(res.invoices, opts.output, (wide) => {
100
108
  table(res.invoices, [
101
109
  { key: 'short_id', label: 'ID' },
102
- { key: 'number_text', label: 'NO', fmt: NUMBER_COL },
110
+ { key: 'display_number', label: 'NO', fmt: NUMBER_COL },
111
+ { key: 'document_date', label: 'DATE', fmt: (v) => (v as string) ?? '—' },
103
112
  { key: 'status', label: 'STATUS' },
104
113
  { key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
105
114
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
@@ -128,6 +137,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
128
137
  const parent = (this.parent?.opts() ?? {}) as ListOpts
129
138
  return listInvoices({
130
139
  output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
140
+ ...(self.from ?? parent.from ? { from: (self.from ?? parent.from) as string } : {}),
141
+ ...(self.to ?? parent.to ? { to: (self.to ?? parent.to) as string } : {}),
131
142
  ...(self.status ?? parent.status ? { status: (self.status ?? parent.status) as string } : {}),
132
143
  ...(self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: (self.paymentStatus ?? parent.paymentStatus) as string } : {}),
133
144
  ...(self.overdue ?? parent.overdue ? { overdue: true } : {}),
@@ -145,7 +156,7 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
145
156
  .requiredOption('--customer <ref>', 'Customer id, short_id, or external_id')
146
157
  .requiredOption('--currency <cur>', 'ISO-4217 currency (e.g. USD)')
147
158
  .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
148
- .option('--number <external>', 'A number another system gave it (up to 64 characters): the invoice keeps it and takes none from the series')
159
+ .option('--number <external>', 'A number another system gave it (up to 64 characters), kept beside the internal number it gets at finalize')
149
160
  .action(async (opts: { customer: string; currency: string; line: string[]; number?: string }) => {
150
161
  const lines = opts.line.map(parseLine)
151
162
  const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
@@ -170,12 +181,15 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
170
181
  printOutput(inv, opts.output, () => {
171
182
  kv([
172
183
  ['id', String(inv['short_id'])],
173
- ['number', inv['number_text'] ? NUMBER_COL(inv['number_text']) : '— (draft)'],
184
+ ['number', inv['number_text'] ? NUMBER_COL(inv['number_text']) : '—'],
174
185
  ...(inv['external_number'] ? [['external_number', String(inv['external_number'])] as [string, string]] : []),
175
186
  ['status', String(inv['status'])],
176
187
  ['customer', String(inv['customer_name'] ?? inv['customer_id'])],
177
- ['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
178
- ['due', inv['due_at'] ? fmtDate(inv['due_at'] as number) : '—'],
188
+ ['date', String(inv['document_date'] ?? '—')],
189
+ ['due', String(inv['due_date'] ?? '—')],
190
+ ...(inv['paid_date'] ? [['paid on', String(inv['paid_date'])] as [string, string]] : []),
191
+ ...(inv['void_date'] ? [['voided on', String(inv['void_date'])] as [string, string]] : []),
192
+ ...(inv['void_reason'] ? [['void reason', String(inv['void_reason'])] as [string, string]] : []),
179
193
  ])
180
194
  const lines = (inv['lines'] as Array<{ description: string; quantity: number; unit_price_cents: number; amount_cents: number }>) ?? []
181
195
  if (lines.length) {
@@ -217,43 +231,54 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
217
231
  cmd.addCommand(
218
232
  new Command('finalize').argument('<ref>')
219
233
  .description('Finalize a draft — assigns a number, freezes it (immutable)')
234
+ .option('--date <date>', 'Invoice date YYYY-MM-DD (default today, UTC)')
220
235
  .option('--due <date>', 'Due date YYYY-MM-DD')
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 }) => {
236
+ .option('--number <external>', 'A number another system gave it, kept beside the internal number')
237
+ .action(async (ref: string, opts: { date?: string; due?: string; number?: string }) => {
223
238
  const body: Record<string, unknown> = {}
224
239
  if (opts.number) body['external_number'] = opts.number
225
- if (opts.due) {
226
- const ms = Date.parse(opts.due)
227
- if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
228
- body['due_at'] = ms
229
- }
240
+ if (opts.date) body['document_date'] = opts.date
241
+ if (opts.due) body['due_date'] = opts.due
230
242
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
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)]])
243
+ success(`Invoice finalized: ${NUMBER_COL(res.invoice.display_number)}`)
244
+ kv([['id', res.invoice.short_id], ['number', NUMBER_COL(res.invoice.number_text)], ['date', res.invoice.document_date ?? '—'], ...(res.invoice.external_number ? [['external_number', res.invoice.external_number] as [string, string]] : []), ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
233
245
  }),
234
246
  )
235
247
 
236
248
  cmd.addCommand(
237
249
  new Command('set-external-number').argument('<ref>', 'id or short_id').argument('<number>', 'the number the other system gave it (up to 64 characters)')
238
- .description('Record the portal number of an already finalized or paid invoice, ONCE (needs `invoice.fiscal_update`). A wrong one is not corrected: void and re-issue.')
239
- .action(async (ref: string, number: string) => {
240
- const res = await http.api<{ invoice: InvoiceRow }>('PUT', `/invoices/${ref}/external-number`, { external_number: number }).catch(die)
250
+ .option('--from-invoice <invoice>', 'MOVE the number from this VOID invoice (id or short_id) to <ref>, in one operation')
251
+ .description('Set or change the portal number of a finalized, paid or void invoice (needs `invoice.fiscal_update`)')
252
+ .action(async (ref: string, number: string, opts: { fromInvoice?: string }) => {
253
+ const res = await http.api<{ invoice: InvoiceRow }>('PUT', `/invoices/${ref}/external-number`, { external_number: number, ...(opts.fromInvoice ? { from_invoice_id: opts.fromInvoice } : {}) }).catch(die)
241
254
  success(`External number set: ${res.invoice.external_number}`)
242
255
  kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['number', NUMBER_COL(res.invoice.number_text)], ['external_number', res.invoice.external_number ?? '']])
243
256
  }),
244
257
  )
245
258
 
259
+ cmd.addCommand(
260
+ new Command('clear-external-number').argument('<ref>', 'id or short_id')
261
+ .description('Take the portal number off a finalized, paid or void invoice, freeing it (needs `invoice.fiscal_update`)')
262
+ .action(async (ref: string) => {
263
+ const res = await http.del<{ invoice: InvoiceRow }>(`/invoices/${ref}/external-number`).catch(die)
264
+ success('External number cleared.')
265
+ kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['number', NUMBER_COL(res.invoice.number_text)]])
266
+ }),
267
+ )
268
+
246
269
  cmd.addCommand(
247
270
  new Command('pay').argument('<ref>')
248
271
  .description('Record a payment against a finalized invoice')
249
272
  .requiredOption('--amount <amount>', 'Amount, e.g. 150.00')
250
273
  .option('--method <method>', 'e.g. bank, cash, card')
251
274
  .option('--ref <reference>', 'External payment reference')
252
- .action(async (ref: string, opts: { amount: string; method?: string; ref?: string }) => {
275
+ .option('--date <date>', 'The day of the payment, YYYY-MM-DD (default today, UTC)')
276
+ .action(async (ref: string, opts: { amount: string; method?: string; ref?: string; date?: string }) => {
253
277
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/payments`, {
254
278
  amount_cents: toCents(opts.amount),
255
279
  ...(opts.method ? { method: opts.method } : {}),
256
280
  ...(opts.ref ? { reference: opts.ref } : {}),
281
+ ...(opts.date ? { document_date: opts.date } : {}),
257
282
  }).catch(die)
258
283
  success(`Payment recorded. Invoice is now ${res.invoice.status}.`)
259
284
  kv([['id', res.invoice.short_id], ['paid', fmtMoney(res.invoice.amount_paid_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
@@ -264,15 +289,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
264
289
  new Command('void').argument('<ref>')
265
290
  .description('Void a finalized invoice')
266
291
  .option('--reason <reason>', 'Reason')
267
- .action(async (ref: string, opts: { reason?: string }) => {
268
- const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
292
+ .option('--date <date>', 'The day it is voided, YYYY-MM-DD (default today, UTC)')
293
+ .action(async (ref: string, opts: { reason?: string; date?: string }) => {
294
+ const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '', ...(opts.date ? { void_date: opts.date } : {}) }).catch(die)
269
295
  success(`Invoice voided: ${res.invoice.short_id}`)
270
296
  }),
271
297
  )
272
298
 
273
- const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; time_zone: string; next: number; next_text: string } | null) =>
299
+ const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; next: number; next_text: string } | null) =>
274
300
  n
275
- ? 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}`]])
301
+ ? kv([['prefix', n.prefix], ['digits', String(n.digits)], ['yearly', n.yearly ? 'yes (the counter restarts each year)' : 'no'], ['next', `${n.next} → ${n.next_text}`]])
276
302
  : console.log('No series: invoices are numbered 1, 2, 3.')
277
303
  cmd.addCommand(
278
304
  new Command('numbering')
@@ -284,15 +310,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
284
310
  })
285
311
  .addCommand(
286
312
  new Command('set')
287
- .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`.')
313
+ .description('Set the series: PREFIX (3 uppercase letters or digits) + the year of the invoice date + a counter of --digits. Never renumbers a finalized invoice. Needs `invoice.configure`.')
288
314
  .requiredOption('--prefix <prefix>', '3 uppercase letters or digits, e.g. BSF')
289
315
  .requiredOption('--digits <n>', 'Counter width, 1 to 12 (9 for e-Fatura)')
290
316
  .option('--yearly', 'The counter restarts each calendar year')
291
- .option('--time-zone <zone>', 'IANA name, e.g. Europe/Istanbul: the year follows the issue date there (kept when omitted; UTC if never set)')
317
+ .option('--time-zone <zone>', 'Deprecated: accepted and ignored')
292
318
  .option('--next <n>', 'Continue from this counter (this year\'s, when yearly); it can only go forward')
293
- .action(async (opts: { prefix: string; digits: string; yearly?: boolean; timeZone?: string; next?: string }) => {
319
+ .option('--year <year>', 'Which year\'s series --next applies to (yearly only; default the current year, UTC)')
320
+ .action(async (opts: { prefix: string; digits: string; yearly?: boolean; next?: string; year?: string }) => {
294
321
  const res = await http.api<{ numbering: Parameters<typeof showNumbering>[0] }>('PUT', '/settings/numbering', {
295
- prefix: opts.prefix, digits: Number(opts.digits), yearly: !!opts.yearly, ...(opts.next ? { next: Number(opts.next) } : {}), ...(opts.timeZone ? { time_zone: opts.timeZone } : {}),
322
+ prefix: opts.prefix, digits: Number(opts.digits), yearly: !!opts.yearly, ...(opts.next ? { next: Number(opts.next) } : {}), ...(opts.year ? { year: Number(opts.year) } : {}),
296
323
  }).catch(die)
297
324
  success('Numbering series set.')
298
325
  showNumbering(res.numbering)
@@ -310,18 +337,27 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
310
337
 
311
338
  type TxnRow = {
312
339
  id: string; invoice_number: number; customer_name: string | null; customer_id: string
313
- kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
340
+ kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; document_date?: string; created_at?: number
314
341
  }
315
342
  cmd.addCommand(
316
343
  new Command('payments').alias('transactions').argument('[ref]', 'invoice id/short_id (omit for all org transactions)')
317
344
  .description('List payments / transactions (the money ledger)')
345
+ .option('--from <date>', 'Paid on or after, YYYY-MM-DD')
346
+ .option('--to <date>', 'Paid on or before, YYYY-MM-DD')
318
347
  .option(...outputOption())
319
- .action(async (ref: string | undefined, opts: { output: string }) => {
320
- const path = ref ? `/invoices/${ref}/payments` : '/transactions'
348
+ .action(async function (this: Command, ref: string | undefined, opts: { output: string; from?: string; to?: string }) {
349
+ // `--from` / `--to` are the list's options too: commander gives them to whichever command declares them first
350
+ const parent = (this.parent?.opts() ?? {}) as { from?: string; to?: string }
351
+ const params = new URLSearchParams()
352
+ const from = opts.from ?? parent.from
353
+ const to = opts.to ?? parent.to
354
+ if (from) params.set('from', from)
355
+ if (to) params.set('to', to)
356
+ const path = `${ref ? `/invoices/${ref}/payments` : '/transactions'}${params.size ? `?${params}` : ''}`
321
357
  const res = await http.get<{ transactions: TxnRow[] }>(path).catch(die)
322
358
  printOutput(res.transactions, opts.output, (wide) => {
323
359
  table(res.transactions, [
324
- { key: 'created_at', label: 'DATE', fmt: (v) => fmtDate(v as number) },
360
+ { key: 'document_date', label: 'DATE', fmt: (v) => (v as string) ?? '—' },
325
361
  { key: 'invoice_number', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
326
362
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customer_id },
327
363
  { key: 'kind', label: 'KIND' },