@baseworks/invoice 1.1.0 → 1.2.1

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.
package/dist/mcp.js CHANGED
@@ -14,7 +14,7 @@ function invoiceTools() {
14
14
  defineTool({
15
15
  name: "invoice_list",
16
16
  title: "List invoices",
17
- description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. 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: filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
17
+ description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. 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: 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.',
18
18
  input: z.object({
19
19
  status: z.enum(["draft", "finalized", "paid", "void"]).optional().describe("Only invoices in this status."),
20
20
  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."),
@@ -22,6 +22,7 @@ function invoiceTools() {
22
22
  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."),
23
23
  fiscal_status: z.enum(["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"]).optional().describe("Only invoices in this state with a tax system."),
24
24
  customer_id: z.string().optional().describe("Only this customer's invoices: the customer's id."),
25
+ external_number: z.string().optional().describe("Only the invoice with this exact external number (the number another system gave it)."),
25
26
  limit: z.number().int().min(1).max(100).optional().describe("Page size, 1 to 100 (default 25)."),
26
27
  offset: z.number().int().min(0).optional().describe("How many to skip, for the next page.")
27
28
  }),
@@ -36,7 +37,8 @@ function invoiceTools() {
36
37
  ...a.overdue !== void 0 ? { overdue: a.overdue } : {},
37
38
  ...a.source ? { source: a.source } : {},
38
39
  ...a.fiscal_status ? { fiscal_status: a.fiscal_status } : {},
39
- ...a.customer_id ? { customer_id: a.customer_id } : {}
40
+ ...a.customer_id ? { customer_id: a.customer_id } : {},
41
+ ...a.external_number ? { external_number: a.external_number } : {}
40
42
  })
41
43
  })
42
44
  }),
@@ -49,6 +51,15 @@ function invoiceTools() {
49
51
  permission: "invoice.read",
50
52
  run: async (ctx, a) => ({ invoice: await ctx.clients.invoice.get(a.ref) })
51
53
  }),
54
+ defineTool({
55
+ name: "invoice_numbering",
56
+ title: "Show the numbering series",
57
+ description: "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. `next_text` is the number the next invoice finalized now would get (for example BSF2026000000149: the prefix, the issue year, then the counter). 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.",
58
+ input: z.object({}),
59
+ access: "read",
60
+ permission: "invoice.read",
61
+ run: async (ctx) => ({ numbering: await ctx.clients.invoice.getNumbering() })
62
+ }),
52
63
  defineTool({
53
64
  name: "invoice_transactions",
54
65
  title: "List payments",
@@ -67,11 +78,12 @@ function invoiceTools() {
67
78
  defineTool({
68
79
  name: "invoice_create",
69
80
  title: "Draft an invoice",
70
- description: "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. The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. 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. It is recorded as you, the agent acting for the person who connected you.",
81
+ description: "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. The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. 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. 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. It is recorded as you, the agent acting for the person who connected you.",
71
82
  input: z.object({
72
83
  customer_id,
73
84
  currency: z.string().length(3).describe("ISO 4217 code, e.g. EUR, USD, TRY."),
74
- lines: z.array(Line).min(1).describe("At least one line.")
85
+ lines: z.array(Line).min(1).describe("At least one line."),
86
+ 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`).")
75
87
  }),
76
88
  access: "write",
77
89
  permission: "invoice.write",
@@ -99,11 +111,12 @@ function invoiceTools() {
99
111
  defineTool({
100
112
  name: "invoice_finalize",
101
113
  title: "Finalize an invoice",
102
- description: "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). 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). Only a draft can be finalized: otherwise `not_draft`.",
114
+ description: "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). 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). 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`.",
103
115
  input: z.object({
104
116
  ref: REF,
105
117
  issued_at: z.number().int().optional().describe("Epoch milliseconds; default now."),
106
- due_at: z.number().int().optional().describe("Epoch milliseconds; omit for no due date.")
118
+ due_at: z.number().int().optional().describe("Epoch milliseconds; omit for no due date."),
119
+ 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.")
107
120
  }),
108
121
  access: "write",
109
122
  permission: "invoice.finalize",
@@ -112,6 +125,15 @@ function invoiceTools() {
112
125
  return { invoice: await ctx.clients.invoice.finalize(ref, input) };
113
126
  }
114
127
  }),
128
+ defineTool({
129
+ name: "invoice_set_external_number",
130
+ title: "Set the portal number of an issued invoice",
131
+ description: "Records the number another system (the e-Ar\u015Fiv / G\u0130B portal, say) gave an invoice that is ALREADY finalized or paid, and returns the invoice. WRITES, and it is one-time: once set it cannot be changed or removed here (a wrong number is corrected only by voiding the invoice and issuing it again). It needs the fiscal permission (`invoice.fiscal_update`). Ask the user to confirm the number first. The same number again changes nothing; a different one is `external_number_set`; a number another invoice holds is `external_number_taken`. The invoice's own `number` and `number_text` stay as issued. A draft is `use_update` (give `external_number` on invoice_finalize instead), a void invoice `void`, a Stripe mirror `mirrored`.",
132
+ input: z.object({ ref: REF, external_number: z.string().min(1).max(64).describe("The number exactly as the other system printed it, up to 64 characters, no leading or trailing spaces.") }),
133
+ access: "write",
134
+ permission: "invoice.fiscal_update",
135
+ run: async (ctx, a) => ({ invoice: await ctx.clients.invoice.setExternalNumber(a.ref, a.external_number) })
136
+ }),
115
137
  defineTool({
116
138
  name: "invoice_record_payment",
117
139
  title: "Record a payment",
@@ -130,6 +152,21 @@ function invoiceTools() {
130
152
  return { invoice: await ctx.clients.invoice.recordPayment(ref, input) };
131
153
  }
132
154
  }),
155
+ defineTool({
156
+ name: "invoice_configure_numbering",
157
+ title: "Set the numbering series",
158
+ description: "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). 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). 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.",
159
+ input: z.object({
160
+ prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe("Exactly 3 uppercase letters or digits."),
161
+ digits: z.number().int().min(1).max(12).describe("Counter width: 9 for e-Fatura."),
162
+ yearly: z.boolean().describe("true: the counter restarts each calendar year (of the issue date)."),
163
+ 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)."),
164
+ 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.")
165
+ }),
166
+ access: "write",
167
+ permission: "invoice.configure",
168
+ run: async (ctx, a) => ({ numbering: await ctx.clients.invoice.setNumbering(a) })
169
+ }),
133
170
  defineTool({
134
171
  name: "invoice_void",
135
172
  title: "Void an invoice",
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  InvoiceEvents,
3
3
  TransactionEvents
4
- } from "./chunk-335MPCTE.js";
4
+ } from "./chunk-JS6GUXCC.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,
@@ -47,6 +52,9 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
47
52
  InvoiceVoided: on.InvoiceVoided.upsert(() => ({
48
53
  status: "void"
49
54
  })),
55
+ InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
56
+ external_number: e.external_number
57
+ })),
50
58
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
51
59
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
52
60
  source: e.source,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
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,52 @@ 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('set-external-number puts the number on an issued invoice, through either name of the group', async () => {
156
+ let body: unknown
157
+ server.use(http.put(`${TEST_BASE}/invoices/inv9x2/external-number`, async ({ request }) => {
158
+ body = await request.json()
159
+ return HttpResponse.json({ invoice: { ...FINAL, external_number: 'GIB2026000000001' } })
160
+ }))
161
+ for (const group of ['invoices', 'invoice']) {
162
+ body = undefined
163
+ const r = await run([group, 'set-external-number', 'inv9x2', 'GIB2026000000001'])
164
+ expect(r.exitCode).toBe(0)
165
+ expect(body).toEqual({ external_number: 'GIB2026000000001' })
166
+ expect(r.stdout).toContain('GIB2026000000001')
167
+ }
168
+ })
169
+
170
+ it('numbering shows the series, sets it, clears it', async () => {
171
+ mocks.mockGet('/settings/numbering', { numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } })
172
+ const shown = await run(['invoices', 'numbering'])
173
+ expect(shown.exitCode).toBe(0)
174
+ expect(shown.stdout).toContain('BSF2026000000149')
175
+ let body: unknown
176
+ server.use(http.put(`${TEST_BASE}/settings/numbering`, async ({ request }) => {
177
+ body = await request.json()
178
+ return HttpResponse.json({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 148, next_text: 'BSF2026000000148', updated_at: 2 } })
179
+ }))
180
+ const set = await run(['invoices', 'numbering', 'set', '--prefix', 'BSF', '--digits', '9', '--yearly', '--next', '148', '--time-zone', 'Europe/Istanbul'])
181
+ expect(set.exitCode).toBe(0)
182
+ expect(body).toEqual({ prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' })
183
+ mocks.mockGet('/settings/numbering', { numbering: null })
184
+ expect((await run(['invoices', 'numbering'])).stdout).toContain('1, 2, 3')
185
+ })
186
+ })
@@ -104,6 +104,14 @@ describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
104
104
  }) as unknown as typeof fetch
105
105
  const c = () => new InvoiceClient({ base_url: 'http://i.test/api', fetch: g })
106
106
 
107
+ it('setExternalNumber PUTs the number and reads the invoice', async () => {
108
+ const seen: Array<{ method?: string; url: string; body: unknown }> = []
109
+ const f = (async (url: string, init?: RequestInit) => { seen.push({ method: init?.method, url: String(url), body: JSON.parse(String(init?.body)) }); return new Response(JSON.stringify({ invoice: { ...INVOICE, external_number: 'GIB-1' } })) }) as unknown as typeof fetch
110
+ const inv = await new InvoiceClient({ base_url: 'http://i.test/api', fetch: f }).setExternalNumber('i1', 'GIB-1')
111
+ expect(seen).toEqual([{ method: 'PUT', url: 'http://i.test/api/invoices/i1/external-number', body: { external_number: 'GIB-1' } }])
112
+ expect(inv.external_number).toBe('GIB-1')
113
+ })
114
+
107
115
  it('list sends every filter, several payment statuses comma-separated', async () => {
108
116
  sent.length = 0
109
117
  await c().list({ status: 'finalized', payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1', limit: 5 })
@@ -124,6 +132,25 @@ describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
124
132
  expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
125
133
  expect(inv.fiscal?.status).toBe('queued')
126
134
  })
135
+ it('numbering: get, set and clear; list filters by external_number', async () => {
136
+ sent.length = 0
137
+ const h = (async (url: string, init?: RequestInit) => {
138
+ sent.push({ method: init?.method ?? 'GET', url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined })
139
+ if (init?.method === 'DELETE') return new Response(JSON.stringify({ numbering: null }))
140
+ return new Response(JSON.stringify({ numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 148, next_text: 'BSF2026000000148', updated_at: 1 }, invoices: [] }))
141
+ }) as unknown as typeof fetch
142
+ const cl = new InvoiceClient({ base_url: 'http://i.test/api', fetch: h })
143
+ expect((await cl.getNumbering())?.next_text).toBe('BSF2026000000148')
144
+ await cl.setNumbering({ prefix: 'BSF', digits: 9, yearly: true, next: 148 })
145
+ await cl.clearNumbering()
146
+ await cl.list({ external_number: 'X-1' })
147
+ expect(sent.map((s) => [s.method, s.url.replace('http://i.test/api', ''), s.body])).toEqual([
148
+ ['GET', '/settings/numbering', undefined],
149
+ ['PUT', '/settings/numbering', { prefix: 'BSF', digits: 9, yearly: true, next: 148 }],
150
+ ['DELETE', '/settings/numbering', undefined],
151
+ ['GET', '/invoices?external_number=X-1', undefined],
152
+ ])
153
+ })
127
154
  it('recordPayment sends payment_id', async () => {
128
155
  sent.length = 0
129
156
  await c().recordPayment('i1', { amount_cents: 5, payment_id: 'pay_1' })
@@ -15,6 +15,9 @@ 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
+ setExternalNumber: async (ref: string, external_number: string) => { calls.push(['setExternalNumber', ref, external_number]); return { id: ref, external_number } },
20
+ setNumbering: async (a: unknown) => { calls.push(['setNumbering', a]); return { ...(a as object), next: 1, next_text: 'x', updated_at: 2 } },
18
21
  transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
19
22
  invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
20
23
  }
@@ -37,11 +40,12 @@ describe('the tool set', () => {
37
40
  it('is invoice_<verb>, composes with itself once, and says read or write with the permission the service registered', () => {
38
41
  const tools = invoiceTools()
39
42
  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'],
43
+ ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_numbering', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
41
44
  ['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'],
45
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_set_external_number', 'write', 'invoice.fiscal_update'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
46
+ ['invoice_configure_numbering', 'write', 'invoice.configure'], ['invoice_void', 'write', 'invoice.void'],
43
47
  ])
44
- expect(composeTools(tools)).toHaveLength(8)
48
+ expect(composeTools(tools)).toHaveLength(11)
45
49
  expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
46
50
  })
47
51
  it('permission names are the ones invoice-service registers', async () => {
@@ -65,11 +69,11 @@ describe('the tool set', () => {
65
69
  })
66
70
 
67
71
  describe('through a real MCP client', () => {
68
- it('lists the eight tools; reads are hinted read-only, writes are not', async () => {
72
+ it('lists the eleven tools; reads are hinted read-only, writes are not', async () => {
69
73
  const t = (await (await session()).listTools()).tools
70
- expect(t).toHaveLength(8)
74
+ expect(t).toHaveLength(11)
71
75
  expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
72
- for (const n of ['invoice_create', 'invoice_finalize', 'invoice_record_payment', 'invoice_void']) expect(t.find((x) => x.name === n)!.annotations, n).toMatchObject({ readOnlyHint: false })
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 })
73
77
  expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
74
78
  })
75
79
 
@@ -80,6 +84,54 @@ describe('through a real MCP client', () => {
80
84
  for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
81
85
  })
82
86
 
87
+ it('numbering: read with invoice.read, set only with invoice.configure; the shape is checked before the call', async () => {
88
+ const c = await session()
89
+ 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 } })
90
+ await c.callTool({ name: 'invoice_configure_numbering', arguments: { prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' } })
91
+ expect(calls).toEqual([['getNumbering'], ['setNumbering', { prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' }]])
92
+ calls.length = 0
93
+ 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 }]) {
94
+ expect(await refused(c, 'invoice_configure_numbering', bad), JSON.stringify(bad)).toBeTruthy()
95
+ }
96
+ expect(calls).toEqual([])
97
+ const reader = await session({ permissions: async () => ['invoice.read', 'invoice.write'] })
98
+ const names = (await reader.listTools()).tools.map((x) => x.name)
99
+ expect(names).toContain('invoice_numbering')
100
+ expect(names).not.toContain('invoice_configure_numbering')
101
+ })
102
+
103
+ it('external_number: on create, on finalize and as a list filter; descriptions say when to use which', async () => {
104
+ const c = await session()
105
+ const args = { customer_id: 'c1', currency: 'TRY', lines: [{ description: 'x', quantity: 1, unit_price_cents: 100 }], external_number: 'BSF2026000000148' }
106
+ await c.callTool({ name: 'invoice_create', arguments: args })
107
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', external_number: 'PORTAL-1' } })
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' }]])
110
+ expect(await refused(c, 'invoice_create', { ...args, external_number: 'x'.repeat(65) })).toBeTruthy()
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/)
114
+ expect(d['invoice_numbering']).toMatch(/next_text/)
115
+ expect(d['invoice_configure_numbering']).toMatch(/administrator/)
116
+ expect(d['invoice_configure_numbering']).toMatch(/never renumbers/)
117
+ expect(d['invoice_configure_numbering']).toMatch(/invoice_numbering/)
118
+ })
119
+
120
+ it('set_external_number: a write behind the fiscal permission, described as one-time', async () => {
121
+ const c = await session()
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
+ expect(calls).toEqual([['setExternalNumber', 'i1', 'GIB-1']])
124
+ calls.length = 0
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
+ expect(calls).toEqual([])
127
+ const d = invoiceTools().find((t) => t.name === 'invoice_set_external_number')!.description
128
+ expect(d).toMatch(/one-time/)
129
+ expect(d).toMatch(/fiscal permission/)
130
+ expect(d).toMatch(/WRITES/)
131
+ const writer = await session({ permissions: async () => ['invoice.read', 'invoice.write', 'invoice.finalize'] })
132
+ expect((await writer.listTools()).tools.map((x) => x.name)).not.toContain('invoice_set_external_number')
133
+ })
134
+
83
135
  it('record_payment: payment_id is passed on', async () => {
84
136
  const c = await session()
85
137
  await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
@@ -158,6 +210,6 @@ describe('through a real MCP client', () => {
158
210
 
159
211
  it('a permission reader hides what the person may not do', async () => {
160
212
  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'])
213
+ expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_numbering', 'invoice_transactions', 'invoice_create', 'invoice_update'])
162
214
  })
163
215
  })
package/src/cli.ts CHANGED
@@ -13,8 +13,8 @@ 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 pay <ref> --amount 150.00` ·
17
- * `invoices void <ref>`
16
+ * `invoices finalize <ref>` · `invoices set-external-number <ref> <number>` ·
17
+ * `invoices pay <ref> --amount 150.00` · `invoices void <ref>`
18
18
  */
19
19
  export interface InvoiceCliDeps {
20
20
  http: ApiClient
@@ -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,28 @@ 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)]])
233
+ }),
234
+ )
235
+
236
+ cmd.addCommand(
237
+ 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)
241
+ success(`External number set: ${res.invoice.external_number}`)
242
+ kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['number', NUMBER_COL(res.invoice.number_text)], ['external_number', res.invoice.external_number ?? '']])
222
243
  }),
223
244
  )
224
245
 
@@ -249,6 +270,44 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
249
270
  }),
250
271
  )
251
272
 
273
+ const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; time_zone: string; next: number; next_text: string } | null) =>
274
+ 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}`]])
276
+ : console.log('No series: invoices are numbered 1, 2, 3.')
277
+ cmd.addCommand(
278
+ new Command('numbering')
279
+ .description('Show the organization\'s numbering series (needs `invoice.read`)')
280
+ .option(...outputOption())
281
+ .action(async (opts: { output: string }) => {
282
+ const res = await http.get<{ numbering: Parameters<typeof showNumbering>[0] }>('/settings/numbering').catch(die)
283
+ printOutput(res.numbering ?? {}, opts.output, () => showNumbering(res.numbering), 'prefix')
284
+ })
285
+ .addCommand(
286
+ 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`.')
288
+ .requiredOption('--prefix <prefix>', '3 uppercase letters or digits, e.g. BSF')
289
+ .requiredOption('--digits <n>', 'Counter width, 1 to 12 (9 for e-Fatura)')
290
+ .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)')
292
+ .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 }) => {
294
+ 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 } : {}),
296
+ }).catch(die)
297
+ success('Numbering series set.')
298
+ showNumbering(res.numbering)
299
+ }),
300
+ )
301
+ .addCommand(
302
+ new Command('clear')
303
+ .description('Back to plain 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`.')
304
+ .action(async () => {
305
+ await http.del('/settings/numbering').catch(die)
306
+ success('No series: invoices are numbered 1, 2, 3.')
307
+ }),
308
+ ),
309
+ )
310
+
252
311
  type TxnRow = {
253
312
  id: string; invoice_number: number; customer_name: string | null; customer_id: string
254
313
  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,11 +182,32 @@ 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)
183
200
  return oldNamesOnInvoice(invoice)
184
201
  }
202
+ /**
203
+ * Record the number another system gave an invoice that is already finalized or paid (the e-Arşiv / GİB portal's).
204
+ * Once: the same number again changes nothing, another one is `409 external_number_set`. Needs `invoice.fiscal_update`.
205
+ * A draft is `409 use_update`.
206
+ */
207
+ async setExternalNumber(ref: string, external_number: string): Promise<Invoice> {
208
+ const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/external-number`, { external_number })
209
+ return oldNamesOnInvoice(invoice)
210
+ }
185
211
  async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
186
212
  const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
187
213
  return oldNamesOnInvoice(invoice)