@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/src/events.ts CHANGED
@@ -40,6 +40,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
40
40
  // 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
41
41
  source: z.string().optional(),
42
42
  metadata: z.string().optional(), // JSON object, serialized
43
+ external_number: z.string().optional(), // 1.2.0: a number given by another system ('' = none)
43
44
  at: z.number().int(),
44
45
  }),
45
46
  // Draft edited (customer / lines). Only valid while status = draft.
@@ -50,6 +51,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
50
51
  subtotal_cents: z.number().int(),
51
52
  total_cents: z.number().int(),
52
53
  metadata: z.string().optional(), // 1.1.0
54
+ external_number: z.string().optional(), // 1.2.0
53
55
  at: z.number().int(),
54
56
  }),
55
57
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -60,6 +62,11 @@ export const InvoiceEvents = defineAggregate('invoice', {
60
62
  total_cents: z.number().int(),
61
63
  issued_at: z.number().int(),
62
64
  due_at: z.number().int(), // 0 = no due date
65
+ // 1.2.0. `number` is the counter of the series (0 when the number is the external one); `number_text` is the number as
66
+ // printed (`BSF2026000000148`, `7`, or the external number); `series_key` says which counter `number` belongs to.
67
+ number_text: z.string().optional(),
68
+ series_key: z.string().optional(),
69
+ external_number: z.string().optional(),
63
70
  at: z.number().int(),
64
71
  }),
65
72
  // A payment applied to a finalized invoice. `amount_paid_cents` is the new running
@@ -78,6 +85,12 @@ export const InvoiceEvents = defineAggregate('invoice', {
78
85
  reason: z.string(),
79
86
  at: z.number().int(),
80
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
+ }),
81
94
  // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
82
95
  // first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
83
96
  InvoiceMirrored: z.object({
@@ -113,6 +126,29 @@ export const InvoiceEvents = defineAggregate('invoice', {
113
126
  }),
114
127
  })
115
128
 
129
+ /**
130
+ * 1.2.0. An organization's numbering series, and the claims that keep numbers unique. One aggregate, many streams:
131
+ * `numbering-settings` holds the series; one stream per (series key, counter) serializes who takes that number; one per
132
+ * external number serializes who holds it.
133
+ */
134
+ export const NumberingEvents = defineAggregate('numbering', {
135
+ NumberingConfigured: z.object({
136
+ prefix: z.string(), // 3 characters, A-Z 0-9
137
+ digits: z.number().int(),
138
+ yearly: z.boolean(),
139
+ next: z.number().int(), // the counter `next_key` starts from
140
+ next_key: z.string(), // the series key `next` applies to (prefix + year when yearly)
141
+ time_zone: z.string().optional(), // IANA name; absent = UTC. The year in the number and the yearly reset follow it
142
+ at: z.number().int(),
143
+ }),
144
+ NumberingCleared: z.object({ at: z.number().int() }),
145
+ NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
146
+ NumberReleased: z.object({ 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() }),
150
+ })
151
+
116
152
  export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
117
153
  export type FiscalStatus = (typeof FISCAL_STATUSES)[number]
118
154
  export const INVOICE_SOURCES = ['local', 'stripe', 'manual'] 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'
@@ -38,7 +38,7 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
38
38
  description:
39
39
  'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
40
40
  'Each invoice has its totals, the amount paid, the `balance_cents` still owed and a `payment_status` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: ' +
41
- 'filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
41
+ 'filter with `payment_status`, `overdue`, `source`, `fiscal_status`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
42
42
  input: z.object({
43
43
  status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
44
44
  payment_status: z.array(z.enum(['unpaid', 'partially_paid', 'paid', 'not_due'])).min(1).optional().describe('Only invoices in one of these payment states. `unpaid` and `partially_paid` are what is still owed; `not_due` is a draft or void invoice.'),
@@ -46,17 +46,18 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
46
46
  source: z.enum(['local', 'stripe', 'manual']).optional().describe('`local` was made here, `stripe` mirrors a Stripe invoice, `manual` was entered from a document issued elsewhere.'),
47
47
  fiscal_status: z.enum(['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled']).optional().describe('Only invoices in this state with a tax system.'),
48
48
  customer_id: z.string().optional().describe('Only this customer\'s invoices: the customer\'s id.'),
49
+ external_number: z.string().optional().describe('Only the invoice with this exact external number (the number another system gave it).'),
49
50
  limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
50
51
  offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
51
52
  }),
52
53
  access: 'read',
53
54
  permission: 'invoice.read',
54
- run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; limit?: number; offset?: number }) => ({
55
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; external_number?: string; limit?: number; offset?: number }) => ({
55
56
  invoices: await ctx.clients.invoice.list({
56
57
  limit: a.limit ?? 25,
57
58
  ...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}),
58
59
  ...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
59
- ...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}),
60
+ ...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}), ...(a.external_number ? { external_number: a.external_number } : {}),
60
61
  }),
61
62
  }),
62
63
  }),
@@ -73,6 +74,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
73
74
  run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string }) => ({ invoice: await ctx.clients.invoice.get(a.ref) }),
74
75
  }),
75
76
 
77
+ defineTool({
78
+ name: 'invoice_numbering',
79
+ title: 'Show the numbering series',
80
+ description:
81
+ 'Shows how the organization numbers its invoices: `{ prefix, digits, yearly, time_zone, next, next_text }`, or `null` when it has no series and invoices are numbered 1, 2, 3. ' +
82
+ '`next_text` is the number the next invoice finalized now would get (for example BSF2026000000149: the prefix, the issue year, then the counter). ' +
83
+ 'Read it before you finalize or before you tell someone what an invoice\'s number will be. Changing the series is invoice_configure_numbering, which is for administrators. Read only.',
84
+ input: z.object({}),
85
+ access: 'read',
86
+ permission: 'invoice.read',
87
+ run: async (ctx: { clients: InvoiceMcpClients }) => ({ numbering: await ctx.clients.invoice.getNumbering() }),
88
+ }),
89
+
76
90
  defineTool({
77
91
  name: 'invoice_transactions',
78
92
  title: 'List payments',
@@ -100,15 +114,17 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
100
114
  'Creates a DRAFT invoice for a customer and returns it. WRITES. The draft has no number and nothing is owed until it is finalized (invoice_finalize), so it is safe to prepare and then show the user. ' +
101
115
  'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
102
116
  'Lines carry a description, a quantity and a unit price in integer cents; the amounts and totals are computed for you. There is no tax in this version. ' +
117
+ 'Give `external_number` only when another system (an e-Fatura portal, say) has already given this invoice a number: the invoice keeps it and takes none from the organization\'s series. Otherwise leave it out; the number comes when the invoice is finalized. ' +
103
118
  'It is recorded as you, the agent acting for the person who connected you.',
104
119
  input: z.object({
105
120
  customer_id,
106
121
  currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
107
122
  lines: z.array(Line).min(1).describe('At least one line.'),
123
+ external_number: z.string().min(1).max(64).optional().describe('A number another system already gave this invoice (an e-Fatura portal\'s, say), up to 64 characters. Give it only when you have one: the invoice then keeps it as its number and takes none from the organization\'s series. Unique among the organization\'s invoices (`external_number_taken`).'),
108
124
  }),
109
125
  access: 'write',
110
126
  permission: 'invoice.write',
111
- run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[] }) => ({
127
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[]; external_number?: string }) => ({
112
128
  invoice: await ctx.clients.invoice.create(a),
113
129
  }),
114
130
  }),
@@ -137,22 +153,36 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
137
153
  name: 'invoice_finalize',
138
154
  title: 'Finalize an invoice',
139
155
  description:
140
- 'Issues a draft: it gets the next number of the organization, its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
156
+ 'Issues a draft: it gets the next number of the organization\'s series (see invoice_numbering for what that reads like), its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
141
157
  'Ask the user to confirm before you do it. Optionally set `issued_at` and `due_at` (epoch milliseconds; the issue date defaults to now, no due date by default). ' +
142
- 'Only a draft can be finalized: otherwise `not_draft`.',
158
+ 'If another system already numbered it, give `external_number`: that becomes the invoice\'s number and the series does not advance. Only a draft can be finalized: otherwise `not_draft`.',
143
159
  input: z.object({
144
160
  ref: REF,
145
161
  issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
146
162
  due_at: z.number().int().optional().describe('Epoch milliseconds; omit for no due date.'),
163
+ external_number: z.string().min(1).max(64).optional().describe('A number another system already gave this invoice. Then it IS the invoice\'s number and the organization\'s series does not advance. Leave it out to take the next number of the series (a configured one such as BSF2026000000149, else 1, 2, 3). Refused with `external_number_set` if the invoice already has a different one.'),
147
164
  }),
148
165
  access: 'write',
149
166
  permission: 'invoice.finalize',
150
- async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number }) {
167
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number; external_number?: string }) {
151
168
  const { ref, ...input } = a
152
169
  return { invoice: await ctx.clients.invoice.finalize(ref, input) }
153
170
  },
154
171
  }),
155
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
+
156
186
  defineTool({
157
187
  name: 'invoice_record_payment',
158
188
  title: 'Record a payment',
@@ -176,6 +206,25 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
176
206
  },
177
207
  }),
178
208
 
209
+ defineTool({
210
+ name: 'invoice_configure_numbering',
211
+ title: 'Set the numbering series',
212
+ description:
213
+ '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). ' +
214
+ '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). ' +
215
+ '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.',
216
+ input: z.object({
217
+ prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe('Exactly 3 uppercase letters or digits.'),
218
+ digits: z.number().int().min(1).max(12).describe('Counter width: 9 for e-Fatura.'),
219
+ yearly: z.boolean().describe('true: the counter restarts each calendar year (of the issue date).'),
220
+ 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).'),
221
+ 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.'),
222
+ }),
223
+ access: 'write',
224
+ permission: 'invoice.configure',
225
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { prefix: string; digits: number; yearly: boolean; time_zone?: string; next?: number }) => ({ numbering: await ctx.clients.invoice.setNumbering(a) }),
226
+ }),
227
+
179
228
  defineTool({
180
229
  name: 'invoice_void',
181
230
  title: 'Void an invoice',
@@ -25,6 +25,7 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
25
25
  short_id: e.short_id,
26
26
  source: e.source ?? null,
27
27
  metadata: e.metadata ?? null,
28
+ external_number: e.external_number ?? null,
28
29
  created_at: e.at,
29
30
  })),
30
31
  InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
@@ -34,6 +35,7 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
34
35
  subtotal_cents: e.subtotal_cents,
35
36
  total_cents: e.total_cents,
36
37
  metadata: e.metadata ?? null,
38
+ external_number: e.external_number ?? null,
37
39
  })),
38
40
  InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
39
41
  number: e.number,
@@ -43,6 +45,9 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
43
45
  total_cents: e.total_cents,
44
46
  issued_at: e.issued_at,
45
47
  due_at: e.due_at,
48
+ number_text: e.number_text ?? null,
49
+ series_key: e.series_key ?? null,
50
+ external_number: e.external_number ?? null,
46
51
  })),
47
52
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
48
53
  amount_paid_cents: e.amount_paid_cents,
@@ -51,6 +56,9 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
51
56
  InvoiceVoided: on.InvoiceVoided.upsert(() => ({
52
57
  status: 'void',
53
58
  })),
59
+ InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
60
+ external_number: e.external_number,
61
+ })),
54
62
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
55
63
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
56
64
  source: e.source,
package/src/types.ts CHANGED
@@ -33,6 +33,10 @@ export interface InvoiceRow {
33
33
  fiscal_external_id: string | null
34
34
  fiscal_message: string | null
35
35
  fiscal_updated_at: number | null
36
+ // 1.2.0
37
+ number_text: string | null
38
+ series_key: string | null
39
+ external_number: string | null
36
40
  }
37
41
 
38
42
  // ── REST DTOs (snake_case, as every service in the realm speaks: ADR-0003) ───
@@ -125,6 +129,13 @@ export interface InvoiceDto {
125
129
  tax_cents: number
126
130
  payment_status: PaymentStatus
127
131
  fiscal: Fiscal | null
132
+ /**
133
+ * The number as printed: `BSF2026000000148` in a series, `7` without one, the external number when the invoice has one.
134
+ * `null` while a draft. `number` is the series' counter (`null` when the number is the external one).
135
+ */
136
+ number_text: string | null
137
+ /** A number given by another system (an e-Fatura portal, say), up to 64 characters. Unique among non-void invoices. */
138
+ external_number: string | null
128
139
  /** Only `GET /invoices/:ref` includes the payments. */
129
140
  payments?: InvoicePayment[]
130
141
  }
@@ -174,6 +185,8 @@ export interface CreateInvoiceInput {
174
185
  currency: string
175
186
  lines: InvoiceLineInput[]
176
187
  metadata?: Metadata
188
+ /** A number from another system; the invoice keeps it and takes none from the series at finalize. */
189
+ external_number?: string
177
190
  /** @deprecated Send `customer_id`. */
178
191
  customerId?: string
179
192
  }
@@ -183,6 +196,8 @@ export interface UpdateInvoiceInput {
183
196
  lines?: InvoiceLineInput[]
184
197
  /** Replaces the invoice's metadata. */
185
198
  metadata?: Metadata
199
+ /** Sets (or, with null, clears) the external number of a draft. */
200
+ external_number?: string | null
186
201
  /** @deprecated Send `customer_id`. */
187
202
  customerId?: string
188
203
  }
@@ -192,6 +207,8 @@ export interface FinalizeInvoiceInput {
192
207
  issued_at?: number
193
208
  /** Epoch millis; 0/omitted = no due date. */
194
209
  due_at?: number
210
+ /** The number another system gave it. Then it is the invoice's number and the series does not advance. */
211
+ external_number?: string
195
212
  /** @deprecated Send `issued_at`. */
196
213
  issuedAt?: number
197
214
  /** @deprecated Send `due_at`. */
@@ -219,6 +236,8 @@ export interface ListInvoicesOptions {
219
236
  source?: InvoiceSource
220
237
  fiscal_status?: FiscalStatus
221
238
  customer_id?: string
239
+ /** Exact. */
240
+ external_number?: string
222
241
  }
223
242
 
224
243
  /** The provider's whole document, for `PUT /invoices/mirror`. */
@@ -249,6 +268,33 @@ export interface MirrorResult {
249
268
  stale?: boolean
250
269
  }
251
270
 
271
+ /** An organization's numbering series. `number_text` is `${prefix}${issue year}${counter, zero-padded to digits}`. */
272
+ export interface Numbering {
273
+ prefix: string
274
+ digits: number
275
+ yearly: boolean
276
+ /** IANA name (`Europe/Istanbul`); `UTC` when none is set. The year in the number and the yearly reset follow the issue date in it. */
277
+ time_zone: string
278
+ /** The counter the next invoice finalized now would get. */
279
+ next: number
280
+ /** What that number would read, for the current year. */
281
+ next_text: string
282
+ updated_at: number
283
+ }
284
+
285
+ export interface NumberingInput {
286
+ /** 3 uppercase letters or digits. */
287
+ prefix: string
288
+ /** 1 to 12; 9 for e-Fatura. */
289
+ digits: number
290
+ /** true: the counter restarts each calendar year (of the issue date). */
291
+ yearly: boolean
292
+ /** IANA name. Omitted: stays as it was (UTC if never set). */
293
+ time_zone?: string
294
+ /** The counter to continue from (this year's, when yearly). Omitted: the series continues where it is. It can only go forward. */
295
+ next?: number
296
+ }
297
+
252
298
  export interface FiscalInput {
253
299
  status: FiscalStatus
254
300
  system?: string