@baseworks/invoice 1.2.0 → 1.2.2

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/README.md CHANGED
@@ -93,6 +93,17 @@ await invoices.list({ external_number: 'PORTAL-77' }) // exact
93
93
  CLI: `invoices numbering`, `invoices numbering set --prefix BSF --digits 9 --yearly --time-zone Europe/Istanbul --next 148`, `invoices numbering clear`;
94
94
  `invoices create|finalize --number <external>`; `invoices --external-number <n>`; the NO column shows the printed number.
95
95
 
96
+ ### 1.2.1: the number of an invoice already issued
97
+
98
+ ```ts
99
+ // once, on a finalized or paid invoice (the e-Arşiv / GİB portal's number); needs invoice.fiscal_update
100
+ await invoices.setExternalNumber(id, 'GIB2026000000001')
101
+ ```
102
+
103
+ CLI: `invoices set-external-number <ref> <number>`. A draft is `409 use_update`, a void invoice `409 void`, a Stripe mirror
104
+ `409 mirrored`, another number `409 external_number_set`; the same one changes nothing. A wrong number is not corrected:
105
+ void and re-issue. Needs **invoice-service 1.2.1**.
106
+
96
107
  ### Deprecated names
97
108
 
98
109
  Until 0.3.0 the client and the service spoke camelCase. A caller that has not moved (billing-service, stripe-service, apps)
@@ -138,13 +149,14 @@ optional peer.
138
149
  | `invoice_list`, `invoice_get`, `invoice_transactions` | read | `invoice.read` |
139
150
  | `invoice_create`, `invoice_update` (drafts only) | write | `invoice.write` |
140
151
  | `invoice_finalize` (irreversible) | write | `invoice.finalize` |
152
+ | `invoice_set_external_number` (one-time) | write | `invoice.fiscal_update` |
141
153
  | `invoice_numbering` | read | `invoice.read` |
142
154
  | `invoice_configure_numbering` | write | `invoice.configure` |
143
155
  | `invoice_record_payment` | write | `invoice.record_payment` |
144
-
145
- `invoice_create` and `invoice_finalize` take `external_number`; `invoice_list` takes the same filters as the client (`external_number` too); `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension.
146
156
  | `invoice_void` (irreversible) | write | `invoice.void` |
147
157
 
158
+ `invoice_create` and `invoice_finalize` take `external_number`; `invoice_list` takes the same filters as the client (`external_number` too); `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension. `invoice_set_external_number` takes the fiscal permission, as that is fiscal identity.
159
+
148
160
  A tool is a thin wrapper over the same client, so it can never do what the API would refuse, and `permission` is the name
149
161
  the service registered with org-service, used to hide a tool from somebody who may not use it. Money is integer cents; a
150
162
  finalized invoice is never edited.
@@ -69,6 +69,12 @@ var InvoiceEvents = defineAggregate("invoice", {
69
69
  reason: z.string(),
70
70
  at: z.number().int()
71
71
  }),
72
+ // 1.2.1. The number another system gave an invoice that was already issued (the e-Arşiv / GİB portal's), set once.
73
+ // `number`, `number_text` and the series are not touched.
74
+ InvoiceExternalNumberSet: z.object({
75
+ external_number: z.string().min(1),
76
+ at: z.number().int()
77
+ }),
72
78
  // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
73
79
  // first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
74
80
  InvoiceMirrored: z.object({
@@ -128,7 +134,9 @@ var NumberingEvents = defineAggregate("numbering", {
128
134
  NumberingCleared: z.object({ at: z.number().int() }),
129
135
  NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
130
136
  NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
131
- ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() })
137
+ // `invoice_version` (1.2.1): the version of the invoice's stream the claiming write emits at. While the stream is still
138
+ // there, that write is in flight. Absent from claims written before.
139
+ ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), invoice_version: z.number().int().optional(), at: z.number().int() })
132
140
  });
133
141
  var FISCAL_STATUSES = ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
134
142
  var INVOICE_SOURCES = ["local", "stripe", "manual"];
package/dist/cli.d.ts CHANGED
@@ -10,8 +10,8 @@ import { ApiClient } from '@baseworks/cli/client';
10
10
  *
11
11
  * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
12
12
  * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
13
- * `invoices finalize <ref>` · `invoices pay <ref> --amount 150.00` ·
14
- * `invoices void <ref>`
13
+ * `invoices finalize <ref>` · `invoices set-external-number <ref> <number>` ·
14
+ * `invoices pay <ref> --amount 150.00` · `invoices void <ref>`
15
15
  */
16
16
  interface InvoiceCliDeps {
17
17
  http: ApiClient;
package/dist/cli.js CHANGED
@@ -145,6 +145,13 @@ function buildInvoiceCommand(deps) {
145
145
  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)]]);
146
146
  })
147
147
  );
148
+ cmd.addCommand(
149
+ new Command("set-external-number").argument("<ref>", "id or short_id").argument("<number>", "the number the other system gave it (up to 64 characters)").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.").action(async (ref, number) => {
150
+ const res = await http.api("PUT", `/invoices/${ref}/external-number`, { external_number: number }).catch(die);
151
+ success(`External number set: ${res.invoice.external_number}`);
152
+ kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["number", NUMBER_COL(res.invoice.number_text)], ["external_number", res.invoice.external_number ?? ""]]);
153
+ })
154
+ );
148
155
  cmd.addCommand(
149
156
  new Command("pay").argument("<ref>").description("Record a payment against a finalized invoice").requiredOption("--amount <amount>", "Amount, e.g. 150.00").option("--method <method>", "e.g. bank, cash, card").option("--ref <reference>", "External payment reference").action(async (ref, opts) => {
150
157
  const res = await http.post(`/invoices/${ref}/payments`, {
package/dist/client.d.ts CHANGED
@@ -388,6 +388,12 @@ declare class InvoiceClient {
388
388
  clearNumbering(): Promise<void>;
389
389
  /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
390
390
  setFiscal(ref: string, input: FiscalInput): Promise<Invoice>;
391
+ /**
392
+ * Record the number another system gave an invoice that is already finalized or paid (the e-Arşiv / GİB portal's).
393
+ * Once: the same number again changes nothing, another one is `409 external_number_set`. Needs `invoice.fiscal_update`.
394
+ * A draft is `409 use_update`.
395
+ */
396
+ setExternalNumber(ref: string, external_number: string): Promise<Invoice>;
391
397
  finalize(ref: string, input?: FinalizeInvoiceInput): Promise<Invoice>;
392
398
  recordPayment(ref: string, input: RecordPaymentInput): Promise<Invoice>;
393
399
  void(ref: string, reason?: string): Promise<Invoice>;
package/dist/client.js CHANGED
@@ -166,6 +166,15 @@ var InvoiceClient = class _InvoiceClient {
166
166
  const { invoice } = await this.api("PUT", `/invoices/${ref}/fiscal`, input);
167
167
  return oldNamesOnInvoice(invoice);
168
168
  }
169
+ /**
170
+ * Record the number another system gave an invoice that is already finalized or paid (the e-Arşiv / GİB portal's).
171
+ * Once: the same number again changes nothing, another one is `409 external_number_set`. Needs `invoice.fiscal_update`.
172
+ * A draft is `409 use_update`.
173
+ */
174
+ async setExternalNumber(ref, external_number) {
175
+ const { invoice } = await this.api("PUT", `/invoices/${ref}/external-number`, { external_number });
176
+ return oldNamesOnInvoice(invoice);
177
+ }
169
178
  async finalize(ref, input = {}) {
170
179
  const { invoice } = await this.api("POST", `/invoices/${ref}/finalize`, newNamesOnFinalize(input));
171
180
  return oldNamesOnInvoice(invoice);
package/dist/events.d.ts CHANGED
@@ -39,25 +39,25 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
39
39
  at: z.ZodNumber;
40
40
  }, "strip", z.ZodTypeAny, {
41
41
  at: number;
42
- lines: string;
43
- short_id: string;
44
42
  customer_id: string;
45
43
  customer_name: string;
46
44
  currency: string;
45
+ lines: string;
47
46
  subtotal_cents: number;
48
47
  total_cents: number;
48
+ short_id: string;
49
49
  source?: string | undefined;
50
50
  metadata?: string | undefined;
51
51
  external_number?: string | undefined;
52
52
  }, {
53
53
  at: number;
54
- lines: string;
55
- short_id: string;
56
54
  customer_id: string;
57
55
  customer_name: string;
58
56
  currency: string;
57
+ lines: string;
59
58
  subtotal_cents: number;
60
59
  total_cents: number;
60
+ short_id: string;
61
61
  source?: string | undefined;
62
62
  metadata?: string | undefined;
63
63
  external_number?: string | undefined;
@@ -73,18 +73,18 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
73
73
  at: z.ZodNumber;
74
74
  }, "strip", z.ZodTypeAny, {
75
75
  at: number;
76
- lines: string;
77
76
  customer_id: string;
78
77
  customer_name: string;
78
+ lines: string;
79
79
  subtotal_cents: number;
80
80
  total_cents: number;
81
81
  metadata?: string | undefined;
82
82
  external_number?: string | undefined;
83
83
  }, {
84
84
  at: number;
85
- lines: string;
86
85
  customer_id: string;
87
86
  customer_name: string;
87
+ lines: string;
88
88
  subtotal_cents: number;
89
89
  total_cents: number;
90
90
  metadata?: string | undefined;
@@ -109,8 +109,8 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
109
109
  total_cents: number;
110
110
  issued_at: number;
111
111
  due_at: number;
112
- number_text?: string | undefined;
113
112
  external_number?: string | undefined;
113
+ number_text?: string | undefined;
114
114
  series_key?: string | undefined;
115
115
  }, {
116
116
  number: number;
@@ -120,8 +120,8 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
120
120
  total_cents: number;
121
121
  issued_at: number;
122
122
  due_at: number;
123
- number_text?: string | undefined;
124
123
  external_number?: string | undefined;
124
+ number_text?: string | undefined;
125
125
  series_key?: string | undefined;
126
126
  }>;
127
127
  PaymentRecorded: z.ZodObject<{
@@ -133,19 +133,19 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
133
133
  payment_id: z.ZodOptional<z.ZodString>;
134
134
  at: z.ZodNumber;
135
135
  }, "strip", z.ZodTypeAny, {
136
- method: string;
137
136
  at: number;
138
- status: "paid" | "draft" | "finalized" | "void";
139
- amount_paid_cents: number;
137
+ status: "draft" | "finalized" | "paid" | "void";
140
138
  amount_cents: number;
139
+ amount_paid_cents: number;
140
+ method: string;
141
141
  reference: string;
142
142
  payment_id?: string | undefined;
143
143
  }, {
144
- method: string;
145
144
  at: number;
146
- status: "paid" | "draft" | "finalized" | "void";
147
- amount_paid_cents: number;
145
+ status: "draft" | "finalized" | "paid" | "void";
148
146
  amount_cents: number;
147
+ amount_paid_cents: number;
148
+ method: string;
149
149
  reference: string;
150
150
  payment_id?: string | undefined;
151
151
  }>;
@@ -159,6 +159,16 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
159
159
  at: number;
160
160
  reason: string;
161
161
  }>;
162
+ InvoiceExternalNumberSet: z.ZodObject<{
163
+ external_number: z.ZodString;
164
+ at: z.ZodNumber;
165
+ }, "strip", z.ZodTypeAny, {
166
+ at: number;
167
+ external_number: string;
168
+ }, {
169
+ at: number;
170
+ external_number: string;
171
+ }>;
162
172
  InvoiceMirrored: z.ZodObject<{
163
173
  source: z.ZodString;
164
174
  mirror_key: z.ZodString;
@@ -183,48 +193,48 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
183
193
  at: z.ZodNumber;
184
194
  }, "strip", z.ZodTypeAny, {
185
195
  at: number;
186
- lines: string;
187
- short_id: string;
188
- status: "paid" | "draft" | "finalized" | "void";
196
+ status: "draft" | "finalized" | "paid" | "void";
189
197
  customer_id: string;
190
198
  customer_name: string;
191
199
  currency: string;
200
+ lines: string;
192
201
  subtotal_cents: number;
193
202
  total_cents: number;
194
- amount_paid_cents: number;
203
+ short_id: string;
204
+ source: string;
205
+ metadata: string;
195
206
  issued_at: number;
196
207
  due_at: number;
197
- created_at: number;
198
- source: string;
208
+ amount_paid_cents: number;
209
+ mirror_key: string;
199
210
  external_refs: string;
200
- metadata: string;
201
211
  tax_cents: number;
202
- mirror_key: string;
203
212
  paid_at: number;
204
213
  voided_at: number;
205
214
  provider_updated_at: number;
215
+ created_at: number;
206
216
  }, {
207
217
  at: number;
208
- lines: string;
209
- short_id: string;
210
- status: "paid" | "draft" | "finalized" | "void";
218
+ status: "draft" | "finalized" | "paid" | "void";
211
219
  customer_id: string;
212
220
  customer_name: string;
213
221
  currency: string;
222
+ lines: string;
214
223
  subtotal_cents: number;
215
224
  total_cents: number;
216
- amount_paid_cents: number;
225
+ short_id: string;
226
+ source: string;
227
+ metadata: string;
217
228
  issued_at: number;
218
229
  due_at: number;
219
- created_at: number;
220
- source: string;
230
+ amount_paid_cents: number;
231
+ mirror_key: string;
221
232
  external_refs: string;
222
- metadata: string;
223
233
  tax_cents: number;
224
- mirror_key: string;
225
234
  paid_at: number;
226
235
  voided_at: number;
227
236
  provider_updated_at: number;
237
+ created_at: number;
228
238
  }>;
229
239
  InvoiceFiscalChanged: z.ZodObject<{
230
240
  status: z.ZodString;
@@ -234,14 +244,14 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
234
244
  at: z.ZodNumber;
235
245
  }, "strip", z.ZodTypeAny, {
236
246
  at: number;
237
- status: string;
238
247
  message: string;
248
+ status: string;
239
249
  system: string;
240
250
  external_id: string;
241
251
  }, {
242
252
  at: number;
243
- status: string;
244
253
  message: string;
254
+ status: string;
245
255
  system: string;
246
256
  external_id: string;
247
257
  }>;
@@ -294,13 +304,13 @@ declare const NumberingEvents: _baseworks_foldbase.EventCatalog<{
294
304
  }, "strip", z.ZodTypeAny, {
295
305
  number: number;
296
306
  at: number;
297
- invoice_id: string;
298
307
  series_key: string;
308
+ invoice_id: string;
299
309
  }, {
300
310
  number: number;
301
311
  at: number;
302
- invoice_id: string;
303
312
  series_key: string;
313
+ invoice_id: string;
304
314
  }>;
305
315
  NumberReleased: z.ZodObject<{
306
316
  invoice_id: z.ZodString;
@@ -315,15 +325,18 @@ declare const NumberingEvents: _baseworks_foldbase.EventCatalog<{
315
325
  ExternalNumberClaimed: z.ZodObject<{
316
326
  external_number: z.ZodString;
317
327
  invoice_id: z.ZodString;
328
+ invoice_version: z.ZodOptional<z.ZodNumber>;
318
329
  at: z.ZodNumber;
319
330
  }, "strip", z.ZodTypeAny, {
320
331
  at: number;
321
332
  external_number: string;
322
333
  invoice_id: string;
334
+ invoice_version?: number | undefined;
323
335
  }, {
324
336
  at: number;
325
337
  external_number: string;
326
338
  invoice_id: string;
339
+ invoice_version?: number | undefined;
327
340
  }>;
328
341
  }> & {
329
342
  newId(): string;
@@ -355,27 +368,27 @@ declare const TransactionEvents: _baseworks_foldbase.EventCatalog<{
355
368
  payment_id: z.ZodOptional<z.ZodString>;
356
369
  at: z.ZodNumber;
357
370
  }, "strip", z.ZodTypeAny, {
358
- method: string;
359
371
  at: number;
360
372
  customer_id: string;
361
373
  customer_name: string;
362
374
  currency: string;
363
375
  amount_cents: number;
376
+ method: string;
377
+ reference: string;
364
378
  invoice_id: string;
365
379
  invoice_number: number;
366
- reference: string;
367
380
  kind: "payment" | "refund" | "adjustment";
368
381
  payment_id?: string | undefined;
369
382
  }, {
370
- method: string;
371
383
  at: number;
372
384
  customer_id: string;
373
385
  customer_name: string;
374
386
  currency: string;
375
387
  amount_cents: number;
388
+ method: string;
389
+ reference: string;
376
390
  invoice_id: string;
377
391
  invoice_number: number;
378
- reference: string;
379
392
  kind: "payment" | "refund" | "adjustment";
380
393
  payment_id?: string | undefined;
381
394
  }>;
package/dist/events.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  NumberingEvents,
7
7
  TransactionEvents,
8
8
  TransactionKind
9
- } from "./chunk-THLNZVGO.js";
9
+ } from "./chunk-JS6GUXCC.js";
10
10
  export {
11
11
  FISCAL_STATUSES,
12
12
  INVOICE_SOURCES,
package/dist/mcp.js CHANGED
@@ -125,6 +125,15 @@ function invoiceTools() {
125
125
  return { invoice: await ctx.clients.invoice.finalize(ref, input) };
126
126
  }
127
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
+ }),
128
137
  defineTool({
129
138
  name: "invoice_record_payment",
130
139
  title: "Record a payment",
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  InvoiceEvents,
3
3
  TransactionEvents
4
- } from "./chunk-THLNZVGO.js";
4
+ } from "./chunk-JS6GUXCC.js";
5
5
 
6
6
  // src/projections.ts
7
7
  import { defineProjection } from "@baseworks/foldbase";
@@ -52,6 +52,9 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
52
52
  InvoiceVoided: on.InvoiceVoided.upsert(() => ({
53
53
  status: "void"
54
54
  })),
55
+ InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
56
+ external_number: e.external_number
57
+ })),
55
58
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
56
59
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
57
60
  source: e.source,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
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": {
@@ -22,7 +22,7 @@
22
22
  "@baseworks/cli": "^0.2.0",
23
23
  "commander": "^15.0.0",
24
24
  "zod": "^3.25.76",
25
- "@baseworks/mcp": "^0.1.2",
25
+ "@baseworks/mcp": "^0.3.0",
26
26
  "@baseworks/foldbase": "0.2.0"
27
27
  },
28
28
  "devDependencies": {
@@ -152,6 +152,21 @@ describe('dtab invoices (numbers)', () => {
152
152
  expect(list.stdout).toContain('BSF2026000000148')
153
153
  })
154
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
+
155
170
  it('numbering shows the series, sets it, clears it', async () => {
156
171
  mocks.mockGet('/settings/numbering', { numbering: { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } })
157
172
  const shown = await run(['invoices', 'numbering'])
@@ -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 })
@@ -16,6 +16,7 @@ const fake = {
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
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 } },
19
20
  setNumbering: async (a: unknown) => { calls.push(['setNumbering', a]); return { ...(a as object), next: 1, next_text: 'x', updated_at: 2 } },
20
21
  transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
21
22
  invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
@@ -41,10 +42,10 @@ describe('the tool set', () => {
41
42
  expect(tools.map((t) => [t.name, t.access, t.permission])).toEqual([
42
43
  ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_numbering', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
43
44
  ['invoice_create', 'write', 'invoice.write'], ['invoice_update', 'write', 'invoice.write'],
44
- ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
45
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_set_external_number', 'write', 'invoice.fiscal_update'], ['invoice_record_payment', 'write', 'invoice.record_payment'],
45
46
  ['invoice_configure_numbering', 'write', 'invoice.configure'], ['invoice_void', 'write', 'invoice.void'],
46
47
  ])
47
- expect(composeTools(tools)).toHaveLength(10)
48
+ expect(composeTools(tools)).toHaveLength(11)
48
49
  expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
49
50
  })
50
51
  it('permission names are the ones invoice-service registers', async () => {
@@ -68,11 +69,11 @@ describe('the tool set', () => {
68
69
  })
69
70
 
70
71
  describe('through a real MCP client', () => {
71
- it('lists the ten 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 () => {
72
73
  const t = (await (await session()).listTools()).tools
73
- expect(t).toHaveLength(10)
74
+ expect(t).toHaveLength(11)
74
75
  expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
75
- for (const n of ['invoice_create', 'invoice_finalize', 'invoice_record_payment', 'invoice_void']) expect(t.find((x) => x.name === n)!.annotations, n).toMatchObject({ readOnlyHint: false })
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 })
76
77
  expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
77
78
  })
78
79
 
@@ -116,6 +117,21 @@ describe('through a real MCP client', () => {
116
117
  expect(d['invoice_configure_numbering']).toMatch(/invoice_numbering/)
117
118
  })
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
+
119
135
  it('record_payment: payment_id is passed on', async () => {
120
136
  const c = await session()
121
137
  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,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
@@ -233,6 +233,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
233
233
  }),
234
234
  )
235
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 ?? '']])
243
+ }),
244
+ )
245
+
236
246
  cmd.addCommand(
237
247
  new Command('pay').argument('<ref>')
238
248
  .description('Record a payment against a finalized invoice')
package/src/client.ts CHANGED
@@ -199,6 +199,15 @@ export class InvoiceClient {
199
199
  const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/fiscal`, input)
200
200
  return oldNamesOnInvoice(invoice)
201
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
+ }
202
211
  async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
203
212
  const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
204
213
  return oldNamesOnInvoice(invoice)
package/src/events.ts CHANGED
@@ -85,6 +85,12 @@ export const InvoiceEvents = defineAggregate('invoice', {
85
85
  reason: z.string(),
86
86
  at: z.number().int(),
87
87
  }),
88
+ // 1.2.1. The number another system gave an invoice that was already issued (the e-Arşiv / GİB portal's), set once.
89
+ // `number`, `number_text` and the series are not touched.
90
+ InvoiceExternalNumberSet: z.object({
91
+ external_number: z.string().min(1),
92
+ at: z.number().int(),
93
+ }),
88
94
  // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
89
95
  // first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
90
96
  InvoiceMirrored: z.object({
@@ -138,7 +144,9 @@ export const NumberingEvents = defineAggregate('numbering', {
138
144
  NumberingCleared: z.object({ at: z.number().int() }),
139
145
  NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
140
146
  NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
141
- ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() }),
147
+ // `invoice_version` (1.2.1): the version of the invoice's stream the claiming write emits at. While the stream is still
148
+ // there, that write is in flight. Absent from claims written before.
149
+ ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), invoice_version: z.number().int().optional(), at: z.number().int() }),
142
150
  })
143
151
 
144
152
  export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
package/src/mcp.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * // ctx.clients.invoice is an InvoiceClient built from the realm token
10
10
  *
11
11
  * Money is integer cents everywhere. A finalized invoice is a legal record: there is no tool that
12
- * edits one, and recording a payment and voiding are separate permissions so an organization can
12
+ * edits one (invoice_set_external_number only adds a missing portal number, once), and recording a payment and voiding are separate permissions so an organization can
13
13
  * give a model drafts and not the books.
14
14
  */
15
15
  import { z } from 'zod'
@@ -170,6 +170,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
170
170
  },
171
171
  }),
172
172
 
173
+ defineTool({
174
+ name: 'invoice_set_external_number',
175
+ title: 'Set the portal number of an issued invoice',
176
+ description:
177
+ 'Records the number another system (the e-Arşiv / GİB 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). ' +
178
+ '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`. ' +
179
+ '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`.',
180
+ 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.') }),
181
+ access: 'write',
182
+ permission: 'invoice.fiscal_update',
183
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; external_number: string }) => ({ invoice: await ctx.clients.invoice.setExternalNumber(a.ref, a.external_number) }),
184
+ }),
185
+
173
186
  defineTool({
174
187
  name: 'invoice_record_payment',
175
188
  title: 'Record a payment',
@@ -56,6 +56,9 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
56
56
  InvoiceVoided: on.InvoiceVoided.upsert(() => ({
57
57
  status: 'void',
58
58
  })),
59
+ InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
60
+ external_number: e.external_number,
61
+ })),
59
62
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
60
63
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
61
64
  source: e.source,