@baseworks/invoice 1.2.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp.ts CHANGED
@@ -9,11 +9,12 @@
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 (invoice_set_external_number only adds a missing portal number, once), and recording a payment and voiding are separate permissions so an organization can
12
+ * edits one (invoice_set_external_number and invoice_clear_external_number only write the portal number), 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'
16
- import { defineTool, type McpTool } from '@baseworks/mcp'
16
+ import { defineTool, encodeCursor, pageArgs, withPaging, type McpTool } from '@baseworks/mcp'
17
+ import { documentDate, documentDateRange, parseDocumentDate } from '@baseworks/core'
17
18
  import type { FiscalStatus, InvoiceClient, InvoiceSource, PaymentStatus } from './client.js'
18
19
 
19
20
  /** What `ctx.clients` must hold for these tools. */
@@ -28,18 +29,36 @@ const Line = z.object({
28
29
  product_id: z.string().optional().describe('The id of a catalog product, if the line is one.'),
29
30
  })
30
31
 
32
+ const isDay = (v: string) => { try { parseDocumentDate(v); return true } catch { return false } }
33
+ /** The day an invoice is due: may be in the future, so not the `document_date` field. The service checks the calendar. */
34
+ const due_date = z.string().refine(isDay, { message: 'not a calendar day YYYY-MM-DD' }).optional().describe('The due date, a calendar day YYYY-MM-DD; omit for none.')
35
+
31
36
  const customer_id = z.string().min(1).describe('The customer: its id, short id or external id in the customer directory (see customers_list). It must exist.')
32
37
 
38
+ const PAGED = 'Paged: at most `limit` (default 100, max 500); when `next` is not null there is more: call again with the same filters and `cursor: next`.'
39
+ /** `offset` is the input from before paging by cursor, kept for one release. */
40
+ const Offset = z.number().int().min(0).optional().describe('Deprecated: use `cursor`. How many to skip; not together with `cursor`.')
41
+ function pageOf(a: { limit?: number | undefined; cursor?: string | undefined; offset?: number | undefined }): { limit: number; offset: number } {
42
+ if (a.offset === undefined) return pageArgs(a)
43
+ if (a.cursor !== undefined) {
44
+ throw Object.assign(new Error('give `cursor` or `offset`, not both: `offset` is deprecated, pass the `next` of the previous page as `cursor`'), { code: 'bad_request', status: 400 })
45
+ }
46
+ return { limit: pageArgs({ limit: a.limit }).limit, offset: a.offset }
47
+ }
48
+ const nextOf = (next_offset: number | null | undefined) => (next_offset == null ? null : encodeCursor(next_offset))
49
+
33
50
  export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
34
51
  return [
35
52
  defineTool({
36
53
  name: 'invoice_list',
37
54
  title: 'List invoices',
38
55
  description:
39
- 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
56
+ 'Lists the organization\'s invoices, newest `document_date` first (drafts, which have none yet, before them). Narrow with `from` / `to` (invoice dates, both included; drafts are then left out), with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
40
57
  '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`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
42
- input: z.object({
58
+ '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, next }`. ' +
59
+ `${PAGED} Read only.`,
60
+ input: z.object(withPaging(z, {
61
+ ...documentDateRange(z),
43
62
  status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
44
63
  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.'),
45
64
  overdue: z.boolean().optional().describe('true: only what is owed and past its due date.'),
@@ -47,26 +66,28 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
47
66
  fiscal_status: z.enum(['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled']).optional().describe('Only invoices in this state with a tax system.'),
48
67
  customer_id: z.string().optional().describe('Only this customer\'s invoices: the customer\'s id.'),
49
68
  external_number: z.string().optional().describe('Only the invoice with this exact external number (the number another system gave it).'),
50
- limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
51
- offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
52
- }),
69
+ offset: Offset,
70
+ })),
53
71
  access: 'read',
54
72
  permission: 'invoice.read',
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 }) => ({
56
- invoices: await ctx.clients.invoice.list({
57
- limit: a.limit ?? 25,
58
- ...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}),
73
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { from?: string; to?: string; status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; external_number?: string; limit?: number; cursor?: string; offset?: number }) => {
74
+ const page = pageOf(a)
75
+ const res = await ctx.clients.invoice.listPage({
76
+ limit: page.limit,
77
+ ...(a.from !== undefined ? { from: a.from } : {}), ...(a.to !== undefined ? { to: a.to } : {}),
78
+ ...(page.offset ? { offset: page.offset } : {}), ...(a.status ? { status: a.status } : {}),
59
79
  ...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
60
80
  ...(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 } : {}),
61
- }),
62
- }),
81
+ })
82
+ return { invoices: res.invoices, next: nextOf(res.next_offset) }
83
+ },
63
84
  }),
64
85
 
65
86
  defineTool({
66
87
  name: 'invoice_get',
67
88
  title: 'Get one invoice',
68
89
  description:
69
- 'Returns one invoice in full: status, number (null while a draft), the customer (id and the name as it was when the invoice was drafted), every line, subtotal, tax, total, amount paid, balance, payment status, issue and due dates, where it came from (`source`, `external_refs`) and every payment recorded on it. ' +
90
+ 'Returns one invoice in full: status, the internal number (`number`, `number_text`; null while a draft), `external_number` and `display_number` (the external one if there is one, else the internal), the customer (id and the name as it was when the invoice was drafted), every line, subtotal, tax, total, amount paid, balance, payment status, `document_date` (the invoice date), `due_date`, `paid_date`, `void_date` and `void_reason`, where it came from (`source`, `external_refs`) and every payment recorded on it. ' +
70
91
  '`ref` is the invoice\'s id or short id. Fails with `not_found` if there is no such invoice. Read only.',
71
92
  input: z.object({ ref: REF }),
72
93
  access: 'read',
@@ -78,8 +99,8 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
78
99
  name: 'invoice_numbering',
79
100
  title: 'Show the numbering series',
80
101
  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). ' +
102
+ 'Shows how the organization numbers its invoices: `{ prefix, digits, yearly, next, next_text }`, or `null` when it has no series and invoices are numbered 1, 2, 3. ' +
103
+ '`next_text` is the number the next invoice finalized now would get (for example BSF2026000000149: the prefix, the year of the invoice date, then the counter). ' +
83
104
  '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
105
  input: z.object({}),
85
106
  access: 'read',
@@ -91,20 +112,22 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
91
112
  name: 'invoice_transactions',
92
113
  title: 'List payments',
93
114
  description:
94
- 'The money ledger: one entry per payment recorded, newest first. Give `ref` for one invoice\'s payments, or leave it out for every payment of the organization. ' +
95
- 'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.',
96
- input: z.object({
115
+ 'The money ledger: one entry per payment recorded, newest `document_date` (day of the payment) first. Narrow with `from` / `to`. Give `ref` for one invoice\'s payments, or leave it out for every payment of the organization. ' +
116
+ 'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. ' +
117
+ `${PAGED} Read only.`,
118
+ input: z.object(withPaging(z, {
97
119
  ref: REF.optional().describe('An invoice id or short id; leave out for the whole organization.'),
98
- limit: z.number().int().min(1).max(100).optional().describe('Page size when listing the whole organization, 1 to 100 (default 25).'),
99
- offset: z.number().int().min(0).optional(),
100
- }),
120
+ ...documentDateRange(z),
121
+ offset: Offset,
122
+ })),
101
123
  access: 'read',
102
124
  permission: 'invoice.read',
103
- run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; offset?: number }) => ({
104
- transactions: a.ref
105
- ? await ctx.clients.invoice.invoiceTransactions(a.ref)
106
- : await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...(a.offset ? { offset: a.offset } : {}) }),
107
- }),
125
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; from?: string; to?: string; limit?: number; cursor?: string; offset?: number }) => {
126
+ const page = pageOf(a)
127
+ const q = { limit: page.limit, ...(page.offset ? { offset: page.offset } : {}), ...(a.from !== undefined ? { from: a.from } : {}), ...(a.to !== undefined ? { to: a.to } : {}) }
128
+ const res = a.ref ? await ctx.clients.invoice.invoiceTransactionsPage(a.ref, q) : await ctx.clients.invoice.transactionsPage(q)
129
+ return { transactions: res.transactions, next: nextOf(res.next_offset) }
130
+ },
108
131
  }),
109
132
 
110
133
  defineTool({
@@ -114,13 +137,13 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
114
137
  '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. ' +
115
138
  'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
116
139
  '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. ' +
140
+ 'Give `external_number` only when another system (an e-Fatura portal, say) has already given this invoice a number: the invoice keeps it beside the internal number it gets when finalized. Otherwise leave it out. ' +
118
141
  'It is recorded as you, the agent acting for the person who connected you.',
119
142
  input: z.object({
120
143
  customer_id,
121
144
  currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
122
145
  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`).'),
146
+ 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: it is kept beside the internal number the invoice gets at finalize. Unique among the organization\'s invoices (`external_number_taken`).'),
124
147
  }),
125
148
  access: 'write',
126
149
  permission: 'invoice.write',
@@ -153,18 +176,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
153
176
  name: 'invoice_finalize',
154
177
  title: 'Finalize an invoice',
155
178
  description:
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). ' +
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). ' +
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`.',
179
+ 'Issues a draft: it gets the next internal number of the organization\'s series (see invoice_numbering for what that reads like), always; its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
180
+ 'Ask the user to confirm before you do it. `document_date` is the invoice date: send the day the user means: omitted, it is today in UTC, which is yesterday in Türkiye between 00:00 and 03:00. It is never in the future and decides the year and series of the number: a date before the latest numbered invoice of that series is refused (`date_before_series`, naming it). `due_date` is optional and not before `document_date`. ' +
181
+ 'If another system already numbered it, give `external_number`: it is kept beside the internal number and shown as the `display_number`. Only a draft can be finalized: otherwise `not_draft`.',
159
182
  input: z.object({
160
183
  ref: REF,
161
- issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
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.'),
184
+ document_date: documentDate(z),
185
+ due_date,
186
+ external_number: z.string().min(1).max(64).optional().describe('A number another system already gave this invoice. Refused with `external_number_set` if the draft already has a different one.'),
187
+ issued_at: z.number().int().optional().describe('Deprecated: use `document_date`. Epoch milliseconds, read as its UTC day; not together with `document_date`.'),
188
+ due_at: z.number().int().optional().describe('Deprecated: use `due_date`. Epoch milliseconds; not together with `due_date`.'),
164
189
  }),
165
190
  access: 'write',
166
191
  permission: 'invoice.finalize',
167
- async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number; external_number?: string }) {
192
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; document_date?: string; due_date?: string; external_number?: string; issued_at?: number; due_at?: number }) {
168
193
  const { ref, ...input } = a
169
194
  return { invoice: await ctx.clients.invoice.finalize(ref, input) }
170
195
  },
@@ -172,15 +197,31 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
172
197
 
173
198
  defineTool({
174
199
  name: 'invoice_set_external_number',
175
- title: 'Set the portal number of an issued invoice',
200
+ title: 'Set or change the portal number',
176
201
  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.') }),
202
+ 'Sets or CHANGES the number another system (the e-Arşiv / GİB portal, say) gave an invoice that is already finalized, paid or void, and returns the invoice. WRITES; every change is kept on record with the previous value. ' +
203
+ 'It needs the fiscal permission (`invoice.fiscal_update`). Ask the user to confirm the number first. The same number again changes nothing; a number another invoice holds (a void one included) is `external_number_taken`: to move it from a void invoice give `from_invoice_id` (one operation), or take it off that one first (invoice_clear_external_number). ' +
204
+ 'The invoice\'s internal `number` and `number_text` never change; `display_number` shows the external one. A draft is `use_update` (give `external_number` on invoice_finalize instead), a Stripe mirror `mirrored`.',
205
+ input: z.object({
206
+ ref: REF,
207
+ 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.'),
208
+ from_invoice_id: z.string().min(1).optional().describe('To MOVE the number: the VOID invoice that holds it now (its id or short id). The number leaves it and arrives on `ref` in one operation, so nobody can take it in between. Both changes are recorded.'),
209
+ }),
210
+ access: 'write',
211
+ permission: 'invoice.fiscal_update',
212
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; external_number: string; from_invoice_id?: string }) => ({ invoice: await ctx.clients.invoice.setExternalNumber(a.ref, a.external_number, a.from_invoice_id ? { from_invoice_id: a.from_invoice_id } : {}) }),
213
+ }),
214
+
215
+ defineTool({
216
+ name: 'invoice_clear_external_number',
217
+ title: 'Take the portal number off',
218
+ description:
219
+ 'Removes the external number from a finalized, paid or void invoice, and returns the invoice. WRITES; the change is kept on record with the previous value. The number is then free for another invoice (how a portal number is moved from a void invoice to the one that replaces it). ' +
220
+ 'It needs the fiscal permission (`invoice.fiscal_update`); ask the user to confirm first. The internal number stays. Nothing to remove changes nothing; a draft is `use_update`, a Stripe mirror `mirrored`.',
221
+ input: z.object({ ref: REF }),
181
222
  access: 'write',
182
223
  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) }),
224
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string }) => ({ invoice: await ctx.clients.invoice.clearExternalNumber(a.ref) }),
184
225
  }),
185
226
 
186
227
  defineTool({
@@ -190,17 +231,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
190
231
  'Records that money was received against a FINALIZED invoice, and returns the invoice with its new balance; when the balance reaches zero it becomes `paid`. WRITES to the books. ' +
191
232
  'The amount is integer cents and cannot exceed the balance (`overpayment`); a draft, void or already paid invoice is refused. ' +
192
233
  'Give `reference` (the bank or processor\'s own id) whenever you have one: a second call with the same reference on the same invoice changes nothing, so a retry is safe. ' +
234
+ '`document_date` is the day the money was received: send the day the user means: omitted, it is today in UTC, which is yesterday in Türkiye between 00:00 and 03:00. It is not before the invoice\'s own `document_date` (`date_before_invoice`); the payment that settles the invoice gives its `paid_date`. ' +
193
235
  'This records a payment that happened; it does not charge anybody.',
194
236
  input: z.object({
195
237
  ref: REF,
196
238
  amount_cents: z.number().int().positive().describe('Integer cents received: 100.00 is 10000.'),
197
239
  method: z.string().optional().describe('e.g. bank, cash, card.'),
198
240
  reference: z.string().optional().describe('The payer\'s or processor\'s own id for this payment; makes a retry safe.'),
241
+ document_date: documentDate(z),
199
242
  payment_id: z.string().optional().describe('The id of the payment record this settles (from pay-service); the same payment_id twice records it once. Needed to record a payment on an invoice that mirrors Stripe\'s.'),
200
243
  }),
201
244
  access: 'write',
202
245
  permission: 'invoice.record_payment',
203
- async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string; payment_id?: string }) {
246
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string; payment_id?: string; document_date?: string }) {
204
247
  const { ref, ...input } = a
205
248
  return { invoice: await ctx.clients.invoice.recordPayment(ref, input) }
206
249
  },
@@ -210,19 +253,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
210
253
  name: 'invoice_configure_numbering',
211
254
  title: 'Set the numbering series',
212
255
  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). ' +
256
+ 'Sets how the organization numbers its invoices from now on: a `prefix` of 3 uppercase letters or digits, then the year of the invoice date, then a counter zero-padded to `digits` (prefix BSF, 9 digits: BSF2026000000148). ' +
257
+ '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 invoice\'s `document_date`; `next` continues an existing series from that counter and can only go forward (`next_behind` otherwise). ' +
215
258
  '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
259
  input: z.object({
217
260
  prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe('Exactly 3 uppercase letters or digits.'),
218
261
  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).'),
262
+ yearly: z.boolean().describe('true: the counter restarts each calendar year (of `document_date`).'),
263
+ time_zone: z.string().optional().describe('Deprecated: accepted and ignored.'),
221
264
  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.'),
265
+ year: z.number().int().min(1).max(9999).optional().describe('Which year\'s series `next` applies to (yearly series only). Omit for the current year (UTC).'),
222
266
  }),
223
267
  access: 'write',
224
268
  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) }),
269
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { prefix: string; digits: number; yearly: boolean; time_zone?: string; next?: number; year?: number }) => ({ numbering: await ctx.clients.invoice.setNumbering(a) }),
226
270
  }),
227
271
 
228
272
  defineTool({
@@ -230,11 +274,11 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
230
274
  title: 'Void an invoice',
231
275
  description:
232
276
  'Cancels a FINALIZED invoice that has no payments: its status becomes `void` and it stays on record. WRITES, and it cannot be undone. Ask the user to confirm first. ' +
233
- 'Drafts are not voided (edit them or leave them); an invoice with payments or already paid is refused (`has_payments`, `already_paid`). Give a `reason`.',
234
- input: z.object({ ref: REF, reason: z.string().optional().describe('Why it is being voided; kept on the record.') }),
277
+ 'Drafts are not voided (edit them or leave them); an invoice with payments or already paid is refused (`has_payments`, `already_paid`). Give a `reason`. `void_date` is the day it is voided, not before the invoice date: send the day the user means: omitted, it is today in UTC, which is yesterday in Türkiye between 00:00 and 03:00. The invoice keeps its numbers.',
278
+ input: z.object({ ref: REF, reason: z.string().optional().describe('Why it is being voided; kept on the record.'), void_date: documentDate(z).describe('The day it is voided, YYYY-MM-DD. Defaults to today in UTC; a future date is refused.') }),
235
279
  access: 'write',
236
280
  permission: 'invoice.void',
237
- run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; reason?: string }) => ({ invoice: await ctx.clients.invoice.void(a.ref, a.reason) }),
281
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; reason?: string; void_date?: string }) => ({ invoice: await ctx.clients.invoice.void(a.ref, a.reason, a.void_date !== undefined ? { void_date: a.void_date } : {}) }),
238
282
  }),
239
283
  ]
240
284
  }
@@ -43,8 +43,10 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
43
43
  lines: e.lines,
44
44
  subtotal_cents: e.subtotal_cents,
45
45
  total_cents: e.total_cents,
46
- issued_at: e.issued_at,
47
- due_at: e.due_at,
46
+ document_date: e.document_date ?? null,
47
+ due_date: e.due_date ?? null,
48
+ issued_at: e.issued_at ?? null, // events before 2.0; NULL for newer ones
49
+ due_at: e.due_at ?? null,
48
50
  number_text: e.number_text ?? null,
49
51
  series_key: e.series_key ?? null,
50
52
  external_number: e.external_number ?? null,
@@ -52,13 +54,20 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
52
54
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
53
55
  amount_paid_cents: e.amount_paid_cents,
54
56
  status: e.status,
57
+ paid_date: e.paid_date ?? null,
55
58
  })),
56
- InvoiceVoided: on.InvoiceVoided.upsert(() => ({
59
+ InvoiceVoided: on.InvoiceVoided.upsert((e) => ({
57
60
  status: 'void',
61
+ void_date: e.void_date ?? null,
62
+ void_reason: e.reason,
63
+ voided_at: e.at,
58
64
  })),
59
65
  InvoiceExternalNumberSet: on.InvoiceExternalNumberSet.upsert((e) => ({
60
66
  external_number: e.external_number,
61
67
  })),
68
+ InvoiceExternalNumberCleared: on.InvoiceExternalNumberCleared.upsert(() => ({
69
+ external_number: '',
70
+ })),
62
71
  // The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
63
72
  InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
64
73
  source: e.source,
@@ -74,10 +83,14 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
74
83
  tax_cents: e.tax_cents,
75
84
  total_cents: e.total_cents,
76
85
  amount_paid_cents: e.amount_paid_cents,
77
- issued_at: e.issued_at,
78
- due_at: e.due_at,
79
- paid_at: e.paid_at,
80
- voided_at: e.voided_at,
86
+ document_date: e.document_date ?? null,
87
+ due_date: e.due_date ?? null,
88
+ paid_date: e.paid_date ?? null,
89
+ void_date: e.void_date ?? null,
90
+ issued_at: e.issued_at ?? null,
91
+ due_at: e.due_at ?? null,
92
+ paid_at: e.paid_at ?? null,
93
+ voided_at: e.voided_at ?? null,
81
94
  provider_updated_at: e.provider_updated_at,
82
95
  metadata: e.metadata,
83
96
  short_id: e.short_id,
@@ -108,6 +121,7 @@ export const readTransactions = defineProjection('transactions', TransactionEven
108
121
  method: e.method,
109
122
  reference: e.reference,
110
123
  payment_id: e.payment_id ?? null,
124
+ document_date: e.document_date ?? null,
111
125
  created_at: e.at,
112
126
  })),
113
127
  }))
package/src/types.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import type { DocumentDate } from '@baseworks/core/document-date'
1
2
  import type { FiscalStatus, InvoiceSource, InvoiceStatus } from './events.js'
3
+ export type { DocumentDate } from '@baseworks/core/document-date'
2
4
  export type { FiscalStatus, InvoiceSource, InvoiceStatus } from './events.js'
3
5
 
4
6
  // ── read-model row (snake_case — foldbase read_invoices table) ────────────────
@@ -15,8 +17,9 @@ export interface InvoiceRow {
15
17
  subtotal_cents: number
16
18
  total_cents: number
17
19
  amount_paid_cents: number
18
- issued_at: number // 0 while draft
19
- due_at: number // 0 = none
20
+ // Before 2.0 (epoch millis): what rows folded from old events hold. Newer rows hold the days below.
21
+ issued_at: number | null // 0 while draft
22
+ due_at: number | null // 0 = none
20
23
  created_at: number
21
24
  updated_at: number
22
25
  // 1.1.0: NULL on rows written before it (read as `local`, no refs, `{}`, no tax, no fiscal state).
@@ -37,6 +40,12 @@ export interface InvoiceRow {
37
40
  number_text: string | null
38
41
  series_key: string | null
39
42
  external_number: string | null
43
+ // 2.0: calendar days `YYYY-MM-DD`
44
+ document_date: string | null
45
+ due_date: string | null
46
+ paid_date: string | null
47
+ void_date: string | null
48
+ void_reason: string | null
40
49
  }
41
50
 
42
51
  // ── REST DTOs (snake_case, as every service in the realm speaks: ADR-0003) ───
@@ -100,7 +109,10 @@ export interface InvoicePayment {
100
109
  currency: string
101
110
  method: string | null
102
111
  reference: string | null
103
- paid_at: number
112
+ /** The day of the payment. */
113
+ document_date: DocumentDate
114
+ /** When it was recorded (epoch millis): audit and the order inside one day. */
115
+ created_at: number
104
116
  }
105
117
 
106
118
  export interface InvoiceDto {
@@ -118,8 +130,13 @@ export interface InvoiceDto {
118
130
  amount_paid_cents: number
119
131
  /** total_cents − amount_paid_cents (0 for draft/void semantics aside). */
120
132
  balance_cents: number
121
- issued_at: number | null
122
- due_at: number | null
133
+ /** The invoice date (calendar day); `null` while a draft. Every period, number and list window follows it. */
134
+ document_date: DocumentDate | null
135
+ due_date: DocumentDate | null
136
+ /** The day of the payment that settled it; `null` unless paid (and for a mirror paid with no date and no payment). */
137
+ paid_date: DocumentDate | null
138
+ void_date: DocumentDate | null
139
+ void_reason: string | null
123
140
  created_at: number
124
141
  updated_at: number
125
142
  /** `local` (made here), `stripe`, `manual` (entered from a document issued elsewhere). Old invoices are `local`. */
@@ -130,12 +147,15 @@ export interface InvoiceDto {
130
147
  payment_status: PaymentStatus
131
148
  fiscal: Fiscal | null
132
149
  /**
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).
150
+ * The internal number as printed: `BSF2026000000148` in a series, `7` without one. `null` while a draft and for a
151
+ * mirror. (An invoice finalized with an external number before 2.0 took no internal one: `number` is `null` and this
152
+ * holds that external number.)
135
153
  */
136
154
  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. */
155
+ /** A number given by another system (an e-Fatura portal, say), up to 64 characters. Unique among the invoices that hold one. */
138
156
  external_number: string | null
157
+ /** Read only: `external_number` if there is one, else `number_text`. */
158
+ display_number: string | null
139
159
  /** Only `GET /invoices/:ref` includes the payments. */
140
160
  payments?: InvoicePayment[]
141
161
  }
@@ -155,10 +175,6 @@ export interface InvoiceDeprecated {
155
175
  amountPaidCents: number
156
176
  /** @deprecated Read `balance_cents`. */
157
177
  balanceCents: number
158
- /** @deprecated Read `issued_at`. */
159
- issuedAt: number | null
160
- /** @deprecated Read `due_at`. */
161
- dueAt: number | null
162
178
  /** @deprecated Read `created_at`. */
163
179
  createdAt: number
164
180
  /** @deprecated Read `updated_at`. */
@@ -185,7 +201,7 @@ export interface CreateInvoiceInput {
185
201
  currency: string
186
202
  lines: InvoiceLineInput[]
187
203
  metadata?: Metadata
188
- /** A number from another system; the invoice keeps it and takes none from the series at finalize. */
204
+ /** A number from another system; the invoice keeps it beside the internal number it gets at finalize. */
189
205
  external_number?: string
190
206
  /** @deprecated Send `customer_id`. */
191
207
  customerId?: string
@@ -203,15 +219,19 @@ export interface UpdateInvoiceInput {
203
219
  }
204
220
 
205
221
  export interface FinalizeInvoiceInput {
206
- /** Epoch millis; defaults to now server-side. */
222
+ /** `YYYY-MM-DD`; defaults to today (UTC) server-side; a future date is refused. */
223
+ document_date?: DocumentDate | string
224
+ /** `YYYY-MM-DD`; omitted = no due date. */
225
+ due_date?: DocumentDate | string
226
+ /** The number another system gave it, kept beside the internal number. */
227
+ external_number?: string
228
+ /** @deprecated Send `document_date`. Epoch millis, read as its UTC day; not together with `document_date`. */
207
229
  issued_at?: number
208
- /** Epoch millis; 0/omitted = no due date. */
230
+ /** @deprecated Send `due_date`. Epoch millis, read as its UTC day (0 = none); not together with `due_date`. */
209
231
  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
212
- /** @deprecated Send `issued_at`. */
232
+ /** @deprecated Send `document_date`. */
213
233
  issuedAt?: number
214
- /** @deprecated Send `due_at`. */
234
+ /** @deprecated Send `due_date`. */
215
235
  dueAt?: number
216
236
  }
217
237
 
@@ -221,17 +241,34 @@ export interface RecordPaymentInput {
221
241
  reference?: string
222
242
  /** The pay record this settles. Idempotency key: the same id twice changes nothing. */
223
243
  payment_id?: string
244
+ /** The day of the payment, `YYYY-MM-DD`; defaults to today (UTC); a future date is refused. */
245
+ document_date?: DocumentDate | string
224
246
  /** @deprecated Send `amount_cents`. */
225
247
  amountCents?: number
226
248
  }
227
249
 
250
+ export interface VoidInvoiceInput {
251
+ /** `YYYY-MM-DD`; defaults to today (UTC); a future date is refused. */
252
+ void_date?: DocumentDate | string
253
+ }
254
+
255
+ /** The `from` / `to` window of a list: calendar days, both included, compared with `document_date`. */
256
+ export interface DocumentDateRangeInput {
257
+ from?: DocumentDate | string
258
+ to?: DocumentDate | string
259
+ }
260
+
228
261
  export interface ListInvoicesOptions {
262
+ /** Only invoices dated this day or later (`document_date`); drafts have no date and are left out. */
263
+ from?: DocumentDate | string
264
+ /** Only invoices dated this day or earlier. */
265
+ to?: DocumentDate | string
229
266
  limit?: number
230
267
  offset?: number
231
268
  status?: string
232
269
  /** One or several (an array is sent comma-separated). */
233
270
  payment_status?: PaymentStatus | PaymentStatus[]
234
- /** Unpaid or partially paid, with a due date in the past. */
271
+ /** Unpaid or partially paid, with a due date before today (UTC). */
235
272
  overdue?: boolean
236
273
  source?: InvoiceSource
237
274
  fiscal_status?: FiscalStatus
@@ -251,9 +288,18 @@ export interface MirrorInvoiceInput {
251
288
  tax_cents: number
252
289
  total_cents: number
253
290
  status: 'finalized' | 'paid' | 'void'
254
- issued_at: number
291
+ /** The provider's invoice date, `YYYY-MM-DD`. Required (unless the deprecated `issued_at` is sent). */
292
+ document_date?: DocumentDate | string
293
+ due_date?: DocumentDate | string
294
+ paid_date?: DocumentDate | string
295
+ void_date?: DocumentDate | string
296
+ /** @deprecated Send `document_date`. Epoch millis, read as its UTC day; never together with the new name. */
297
+ issued_at?: number
298
+ /** @deprecated Send `due_date`. */
255
299
  due_at?: number
300
+ /** @deprecated Send `paid_date`. */
256
301
  paid_at?: number
302
+ /** @deprecated Send `void_date`. */
257
303
  voided_at?: number
258
304
  /** The provider's own "updated" time: an upsert older than what is stored is ignored. */
259
305
  provider_updated_at: number
@@ -268,13 +314,11 @@ export interface MirrorResult {
268
314
  stale?: boolean
269
315
  }
270
316
 
271
- /** An organization's numbering series. `number_text` is `${prefix}${issue year}${counter, zero-padded to digits}`. */
317
+ /** An organization's numbering series. `number_text` is `${prefix}${year of document_date}${counter, zero-padded to digits}`. */
272
318
  export interface Numbering {
273
319
  prefix: string
274
320
  digits: number
275
321
  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
322
  /** The counter the next invoice finalized now would get. */
279
323
  next: number
280
324
  /** What that number would read, for the current year. */
@@ -287,12 +331,14 @@ export interface NumberingInput {
287
331
  prefix: string
288
332
  /** 1 to 12; 9 for e-Fatura. */
289
333
  digits: number
290
- /** true: the counter restarts each calendar year (of the issue date). */
334
+ /** true: the counter restarts each calendar year (of `document_date`). */
291
335
  yearly: boolean
292
- /** IANA name. Omitted: stays as it was (UTC if never set). */
336
+ /** @deprecated Accepted and ignored in 2.0, to be removed: the year is that of `document_date`, a calendar day. */
293
337
  time_zone?: string
294
338
  /** The counter to continue from (this year's, when yearly). Omitted: the series continues where it is. It can only go forward. */
295
339
  next?: number
340
+ /** Which year's series `next` applies to, for a yearly series. Default: the current year (UTC). */
341
+ year?: number
296
342
  }
297
343
 
298
344
  export interface FiscalInput {
@@ -316,6 +362,8 @@ export interface TransactionRow {
316
362
  method: string
317
363
  reference: string
318
364
  payment_id: string | null
365
+ /** 2.0; NULL on rows folded from older events (the day of `created_at`). */
366
+ document_date: string | null
319
367
  created_at: number
320
368
  updated_at: number
321
369
  }
@@ -332,6 +380,8 @@ export interface TransactionDto {
332
380
  method: string | null
333
381
  reference: string | null
334
382
  payment_id: string | null
383
+ /** The day of the payment. */
384
+ document_date: DocumentDate
335
385
  created_at: number
336
386
  }
337
387