@baseworks/invoice 1.2.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -12,6 +12,8 @@ import type {
12
12
  UpdateInvoiceInput,
13
13
  FinalizeInvoiceInput,
14
14
  RecordPaymentInput,
15
+ VoidInvoiceInput,
16
+ DocumentDateRangeInput,
15
17
  } from './types.js'
16
18
 
17
19
  export type {
@@ -45,6 +47,9 @@ export type {
45
47
  UpdateInvoiceInput,
46
48
  FinalizeInvoiceInput,
47
49
  RecordPaymentInput,
50
+ VoidInvoiceInput,
51
+ DocumentDateRangeInput,
52
+ DocumentDate,
48
53
  } from './types.js'
49
54
 
50
55
  export interface InvoiceClientOptions {
@@ -153,6 +158,8 @@ export class InvoiceClient {
153
158
  /** One page and `next_offset` (null on the last page): pass it back as `offset` to read on. */
154
159
  async listPage(opts: ListInvoicesOptions = {}): Promise<{ invoices: Invoice[]; next_offset?: number | null }> {
155
160
  const q = new URLSearchParams()
161
+ if (opts.from !== undefined) q.set('from', opts.from)
162
+ if (opts.to !== undefined) q.set('to', opts.to)
156
163
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
157
164
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
158
165
  if (opts.status) q.set('status', opts.status)
@@ -204,12 +211,19 @@ export class InvoiceClient {
204
211
  return oldNamesOnInvoice(invoice)
205
212
  }
206
213
  /**
207
- * Record the number another system gave an invoice that is already finalized or paid (the e-Arşiv / GİB portal's).
208
- * Once: the same number again changes nothing, another one is `409 external_number_set`. Needs `invoice.fiscal_update`.
209
- * A draft is `409 use_update`.
214
+ * Set or change the number another system gave an issued invoice (finalized, paid or void; the e-Arşiv / GİB portal's).
215
+ * The same number again changes nothing; one another invoice holds is `409 external_number_taken`. A draft is
216
+ * `409 use_update`. Needs `invoice.fiscal_update`.
217
+ * `from_invoice_id` MOVES the number from that void invoice to this one in one operation (nobody can take it in between;
218
+ * `409 from_not_void`, `409 from_number_mismatch`).
210
219
  */
211
- async setExternalNumber(ref: string, external_number: string): Promise<Invoice> {
212
- const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/external-number`, { external_number })
220
+ async setExternalNumber(ref: string, external_number: string, opts: { from_invoice_id?: string } = {}): Promise<Invoice> {
221
+ const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/external-number`, { external_number, ...(opts.from_invoice_id ? { from_invoice_id: opts.from_invoice_id } : {}) })
222
+ return oldNamesOnInvoice(invoice)
223
+ }
224
+ /** Take the external number off an issued invoice, which frees it for another. Needs `invoice.fiscal_update`. */
225
+ async clearExternalNumber(ref: string): Promise<Invoice> {
226
+ const { invoice } = await this.api<{ invoice: Invoice }>('DELETE', `/invoices/${ref}/external-number`)
213
227
  return oldNamesOnInvoice(invoice)
214
228
  }
215
229
  async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
@@ -220,25 +234,28 @@ export class InvoiceClient {
220
234
  const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/payments`, newNamesOnPayment(input))
221
235
  return oldNamesOnInvoice(invoice)
222
236
  }
223
- async void(ref: string, reason?: string): Promise<Invoice> {
224
- const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/void`, { reason: reason ?? '' })
237
+ /** `void_date` defaults to today (UTC) server-side. */
238
+ async void(ref: string, reason?: string, input: VoidInvoiceInput = {}): Promise<Invoice> {
239
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/void`, { reason: reason ?? '', ...(input.void_date !== undefined ? { void_date: input.void_date } : {}) })
225
240
  return oldNamesOnInvoice(invoice)
226
241
  }
227
242
 
228
243
  // ── transactions (the payment ledger) ───────────────────────────────────────
229
244
 
230
- /** All transactions for the org, newest first. */
231
- async transactions(opts: { limit?: number; offset?: number } = {}): Promise<Transaction[]> {
245
+ /** All transactions for the org, newest first by (document_date, created_at, id). */
246
+ async transactions(opts: TransactionListOptions = {}): Promise<Transaction[]> {
232
247
  return (await this.transactionsPage(opts)).transactions
233
248
  }
234
249
 
235
250
  /** One page of the organization's transactions and `next_offset` (null on the last page). */
236
- transactionsPage(opts: { limit?: number; offset?: number } = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
251
+ transactionsPage(opts: TransactionListOptions = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
237
252
  return this.transactionList('/transactions', opts)
238
253
  }
239
254
 
240
- private async transactionList(path: string, opts: { limit?: number; offset?: number }): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
255
+ private async transactionList(path: string, opts: TransactionListOptions): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
241
256
  const q = new URLSearchParams()
257
+ if (opts.from !== undefined) q.set('from', opts.from)
258
+ if (opts.to !== undefined) q.set('to', opts.to)
242
259
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
243
260
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
244
261
  const qs = q.toString()
@@ -252,11 +269,13 @@ export class InvoiceClient {
252
269
  }
253
270
 
254
271
  /** One page of an invoice's transactions and `next_offset` (null on the last page). */
255
- invoiceTransactionsPage(ref: string, opts: { limit?: number; offset?: number } = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
272
+ invoiceTransactionsPage(ref: string, opts: TransactionListOptions = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
256
273
  return this.transactionList(`/invoices/${ref}/payments`, opts)
257
274
  }
258
275
  }
259
276
 
277
+ export type TransactionListOptions = DocumentDateRangeInput & { limit?: number; offset?: number }
278
+
260
279
  /** Factory used by the SDK capability registry. */
261
280
  export function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient {
262
281
  return new InvoiceClient(opts)
package/src/compat.ts CHANGED
@@ -5,15 +5,14 @@
5
5
  *
6
6
  * - answers: each old name is put back on the object as a non-enumerable getter of the snake_case
7
7
  * field, so `invoice.totalCents` still reads while `JSON.stringify` and `toEqual` see only the
8
- * snake_case object;
8
+ * snake_case object (`issuedAt` / `dueAt` went in 2.0 with the fields they read);
9
9
  * - requests: old input names are renamed to snake_case before they are sent. The new name wins
10
10
  * when both are given.
11
11
  */
12
12
 
13
13
  const INVOICE: Record<string, string> = {
14
14
  shortId: 'short_id', customerId: 'customer_id', customerName: 'customer_name', subtotalCents: 'subtotal_cents',
15
- totalCents: 'total_cents', amountPaidCents: 'amount_paid_cents', balanceCents: 'balance_cents', issuedAt: 'issued_at',
16
- dueAt: 'due_at', createdAt: 'created_at', updatedAt: 'updated_at',
15
+ totalCents: 'total_cents', amountPaidCents: 'amount_paid_cents', balanceCents: 'balance_cents', createdAt: 'created_at', updatedAt: 'updated_at',
17
16
  }
18
17
  const LINE: Record<string, string> = { unitPriceCents: 'unit_price_cents', amountCents: 'amount_cents', productId: 'product_id' }
19
18
  const TRANSACTION: Record<string, string> = {
package/src/events.ts CHANGED
@@ -13,7 +13,10 @@ import { defineAggregate } from '@baseworks/foldbase'
13
13
  * amounts, subtotal/total, the running amount-paid, the per-org invoice number,
14
14
  * and the resulting status — is computed by the STORE before emit and carried as
15
15
  * absolute values in the event, so the projection is a plain upsert (no
16
- * accumulation). `lines` is a serialized JSON array. Timestamps are epoch millis.
16
+ * accumulation). `lines` is a serialized JSON array. Timestamps (`at`, `created_at`) are epoch millis; business dates
17
+ * (`document_date`, `due_date`, `paid_date`, `void_date`, since 2.0) are calendar days `YYYY-MM-DD` (workspace ADR 0010).
18
+ * Events written before 2.0 say `issued_at`, `due_at`, `paid_at`, `voided_at` in epoch millis; they stay in the log and
19
+ * the service reads them as UTC days.
17
20
  * A FINALIZED invoice is immutable: only PaymentRecorded / InvoiceVoided follow.
18
21
  *
19
22
  * Payload fields are snake_case (0.3.0). Events written before are camelCase
@@ -52,6 +55,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
52
55
  total_cents: z.number().int(),
53
56
  metadata: z.string().optional(), // 1.1.0
54
57
  external_number: z.string().optional(), // 1.2.0
58
+ previous_external_number: z.string().optional(), // 2.0: present when this update changed it ('' = none before)
55
59
  at: z.number().int(),
56
60
  }),
57
61
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -60,10 +64,13 @@ export const InvoiceEvents = defineAggregate('invoice', {
60
64
  lines: z.string(),
61
65
  subtotal_cents: z.number().int(),
62
66
  total_cents: z.number().int(),
63
- issued_at: z.number().int(),
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
+ document_date: z.string().optional(), // 2.0: the invoice date, `YYYY-MM-DD`
68
+ due_date: z.string().optional(), // 2.0: absent = no due date
69
+ issued_at: z.number().int().optional(), // before 2.0, epoch millis
70
+ due_at: z.number().int().optional(), // before 2.0; 0 = no due date
71
+ // 1.2.0. `number` is the counter of the series; `number_text` is it as printed (`BSF2026000000148`, `7`); `series_key`
72
+ // says which counter `number` belongs to. Between 1.2.0 and 2.0 an invoice given an external number at finalize took
73
+ // none: `number` 0 and `number_text` the external number. Those stay as they are.
67
74
  number_text: z.string().optional(),
68
75
  series_key: z.string().optional(),
69
76
  external_number: z.string().optional(),
@@ -79,16 +86,27 @@ export const InvoiceEvents = defineAggregate('invoice', {
79
86
  method: z.string(),
80
87
  reference: z.string(),
81
88
  payment_id: z.string().optional(), // 1.1.0: the pay record this settles; the idempotency key when present
89
+ document_date: z.string().optional(), // 2.0: the day of the payment
90
+ paid_date: z.string().optional(), // 2.0: present when `status` is `paid`: the day of the payment that settled it
82
91
  at: z.number().int(),
83
92
  }),
84
93
  InvoiceVoided: z.object({
85
94
  reason: z.string(),
95
+ void_date: z.string().optional(), // 2.0; before it, the day of `at`
86
96
  at: z.number().int(),
87
97
  }),
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.
98
+ // 1.2.1. The number another system gave an invoice that was already issued (the e-Arşiv / GİB portal's); since 2.0 it
99
+ // can be changed. `number`, `number_text` and the series are not touched.
90
100
  InvoiceExternalNumberSet: z.object({
91
101
  external_number: z.string().min(1),
102
+ previous: z.string().optional(), // 2.0: what it was ('' = none)
103
+ moved_from: z.string().optional(), // 2.0: the void invoice it was taken from, in the same operation
104
+ at: z.number().int(),
105
+ }),
106
+ // 2.0. The external number taken off an issued invoice (a number is moved by clearing it first).
107
+ InvoiceExternalNumberCleared: z.object({
108
+ previous: z.string().min(1),
109
+ moved_to: z.string().optional(), // 2.0: the invoice it was moved to, in the same operation
92
110
  at: z.number().int(),
93
111
  }),
94
112
  // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
@@ -106,10 +124,14 @@ export const InvoiceEvents = defineAggregate('invoice', {
106
124
  total_cents: z.number().int(),
107
125
  amount_paid_cents: z.number().int(), // from the payment entries, not from the provider
108
126
  status: InvoiceStatus,
109
- issued_at: z.number().int(),
110
- due_at: z.number().int(), // 0 = none
111
- paid_at: z.number().int(), // 0 = none
112
- voided_at: z.number().int(), // 0 = none
127
+ document_date: z.string().optional(), // 2.0; the four days are absent when there is none
128
+ due_date: z.string().optional(),
129
+ paid_date: z.string().optional(),
130
+ void_date: z.string().optional(),
131
+ issued_at: z.number().int().optional(), // the four before 2.0, epoch millis, 0 = none
132
+ due_at: z.number().int().optional(),
133
+ paid_at: z.number().int().optional(),
134
+ voided_at: z.number().int().optional(),
113
135
  provider_updated_at: z.number().int(),
114
136
  metadata: z.string(),
115
137
  short_id: z.string().min(1),
@@ -138,15 +160,23 @@ export const NumberingEvents = defineAggregate('numbering', {
138
160
  yearly: z.boolean(),
139
161
  next: z.number().int(), // the counter `next_key` starts from
140
162
  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
163
+ time_zone: z.string().optional(), // before 2.0; read by nothing now: the year is the `document_date`'s
142
164
  at: z.number().int(),
143
165
  }),
144
166
  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() }),
167
+ NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), claim_id: z.string().optional(), at: z.number().int() }),
146
168
  NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
147
169
  // `invoice_version` (1.2.1): the version of the invoice's stream the claiming write emits at. While the stream is still
148
170
  // 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() }),
171
+ ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), invoice_version: z.number().int().optional(), claim_id: z.string().optional(), at: z.number().int() }),
172
+ // 2.0, fencing. Written at the version a claim was made at, right before the write the claim is for: if the lease ran out
173
+ // and another writer took the claim over, the stream has moved and this append is refused, so the write does not happen.
174
+ // It also starts the lease again. Read like the claim it confirms.
175
+ NumberConfirmed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), claim_id: z.string().optional(), at: z.number().int() }),
176
+ ExternalNumberConfirmed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), invoice_version: z.number().int().optional(), claim_id: z.string().optional(), at: z.number().int() }),
177
+ // 2.0. `claim_id` tells two writers of one invoice apart: a claim is given back, or confirmed, only by the writer that made it.
178
+ // A finalize or a set that failed gives its external number back at once.
179
+ ExternalNumberReleased: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() }),
150
180
  })
151
181
 
152
182
  export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
@@ -176,6 +206,7 @@ export const TransactionEvents = defineAggregate('transaction', {
176
206
  method: z.string(),
177
207
  reference: z.string(),
178
208
  payment_id: z.string().optional(), // 1.1.0
209
+ document_date: z.string().optional(), // 2.0: the day of the payment; before it, the day of `at`
179
210
  at: z.number().int(),
180
211
  }),
181
212
  })
package/src/graphql.ts CHANGED
@@ -16,7 +16,8 @@ export const typeDefs = /* GraphQL */ `
16
16
  totalCents: Int!
17
17
  amountPaidCents: Int!
18
18
  balanceCents: Int!
19
- dueAt: Float
19
+ documentDate: String
20
+ dueDate: String
20
21
  createdAt: Float!
21
22
  lines: [InvoiceLine!]!
22
23
  customer: Customer
@@ -69,7 +70,8 @@ export const resolvers = {
69
70
  totalCents: (p: Invoice) => p.total_cents,
70
71
  amountPaidCents: (p: Invoice) => p.amount_paid_cents,
71
72
  balanceCents: (p: Invoice) => p.balance_cents,
72
- dueAt: (p: Invoice) => p.due_at,
73
+ documentDate: (p: Invoice) => p.document_date,
74
+ dueDate: (p: Invoice) => p.due_date,
73
75
  createdAt: (p: Invoice) => p.created_at,
74
76
  customer: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.customerLoader.load(parent.customer_id),
75
77
  transactions: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.invoice.invoiceTransactions(parent.id).catch(() => []),
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
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,6 +29,10 @@ 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
 
33
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`.'
@@ -48,11 +53,12 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
48
53
  name: 'invoice_list',
49
54
  title: 'List invoices',
50
55
  description:
51
- '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. ' +
52
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: ' +
53
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 }`. ' +
54
59
  `${PAGED} Read only.`,
55
60
  input: z.object(withPaging(z, {
61
+ ...documentDateRange(z),
56
62
  status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
57
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.'),
58
64
  overdue: z.boolean().optional().describe('true: only what is owed and past its due date.'),
@@ -64,10 +70,11 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
64
70
  })),
65
71
  access: 'read',
66
72
  permission: 'invoice.read',
67
- 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; cursor?: string; offset?: number }) => {
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 }) => {
68
74
  const page = pageOf(a)
69
75
  const res = await ctx.clients.invoice.listPage({
70
76
  limit: page.limit,
77
+ ...(a.from !== undefined ? { from: a.from } : {}), ...(a.to !== undefined ? { to: a.to } : {}),
71
78
  ...(page.offset ? { offset: page.offset } : {}), ...(a.status ? { status: a.status } : {}),
72
79
  ...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
73
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 } : {}),
@@ -80,7 +87,7 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
80
87
  name: 'invoice_get',
81
88
  title: 'Get one invoice',
82
89
  description:
83
- '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. ' +
84
91
  '`ref` is the invoice\'s id or short id. Fails with `not_found` if there is no such invoice. Read only.',
85
92
  input: z.object({ ref: REF }),
86
93
  access: 'read',
@@ -92,8 +99,8 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
92
99
  name: 'invoice_numbering',
93
100
  title: 'Show the numbering series',
94
101
  description:
95
- '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. ' +
96
- '`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). ' +
97
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.',
98
105
  input: z.object({}),
99
106
  access: 'read',
@@ -105,18 +112,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
105
112
  name: 'invoice_transactions',
106
113
  title: 'List payments',
107
114
  description:
108
- '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. ' +
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. ' +
109
116
  'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. ' +
110
117
  `${PAGED} Read only.`,
111
118
  input: z.object(withPaging(z, {
112
119
  ref: REF.optional().describe('An invoice id or short id; leave out for the whole organization.'),
120
+ ...documentDateRange(z),
113
121
  offset: Offset,
114
122
  })),
115
123
  access: 'read',
116
124
  permission: 'invoice.read',
117
- run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; cursor?: string; offset?: number }) => {
125
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; from?: string; to?: string; limit?: number; cursor?: string; offset?: number }) => {
118
126
  const page = pageOf(a)
119
- const q = { limit: page.limit, ...(page.offset ? { offset: page.offset } : {}) }
127
+ const q = { limit: page.limit, ...(page.offset ? { offset: page.offset } : {}), ...(a.from !== undefined ? { from: a.from } : {}), ...(a.to !== undefined ? { to: a.to } : {}) }
120
128
  const res = a.ref ? await ctx.clients.invoice.invoiceTransactionsPage(a.ref, q) : await ctx.clients.invoice.transactionsPage(q)
121
129
  return { transactions: res.transactions, next: nextOf(res.next_offset) }
122
130
  },
@@ -129,13 +137,13 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
129
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. ' +
130
138
  'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
131
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. ' +
132
- '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. ' +
133
141
  'It is recorded as you, the agent acting for the person who connected you.',
134
142
  input: z.object({
135
143
  customer_id,
136
144
  currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
137
145
  lines: z.array(Line).min(1).describe('At least one line.'),
138
- 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`).'),
139
147
  }),
140
148
  access: 'write',
141
149
  permission: 'invoice.write',
@@ -168,18 +176,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
168
176
  name: 'invoice_finalize',
169
177
  title: 'Finalize an invoice',
170
178
  description:
171
- '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). ' +
172
- '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). ' +
173
- '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`.',
174
182
  input: z.object({
175
183
  ref: REF,
176
- issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
177
- due_at: z.number().int().optional().describe('Epoch milliseconds; omit for no due date.'),
178
- 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`.'),
179
189
  }),
180
190
  access: 'write',
181
191
  permission: 'invoice.finalize',
182
- 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 }) {
183
193
  const { ref, ...input } = a
184
194
  return { invoice: await ctx.clients.invoice.finalize(ref, input) }
185
195
  },
@@ -187,15 +197,31 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
187
197
 
188
198
  defineTool({
189
199
  name: 'invoice_set_external_number',
190
- title: 'Set the portal number of an issued invoice',
200
+ title: 'Set or change the portal number',
191
201
  description:
192
- '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). ' +
193
- '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`. ' +
194
- '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`.',
195
- 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 }),
196
222
  access: 'write',
197
223
  permission: 'invoice.fiscal_update',
198
- 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) }),
199
225
  }),
200
226
 
201
227
  defineTool({
@@ -205,17 +231,19 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
205
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. ' +
206
232
  'The amount is integer cents and cannot exceed the balance (`overpayment`); a draft, void or already paid invoice is refused. ' +
207
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`. ' +
208
235
  'This records a payment that happened; it does not charge anybody.',
209
236
  input: z.object({
210
237
  ref: REF,
211
238
  amount_cents: z.number().int().positive().describe('Integer cents received: 100.00 is 10000.'),
212
239
  method: z.string().optional().describe('e.g. bank, cash, card.'),
213
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),
214
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.'),
215
243
  }),
216
244
  access: 'write',
217
245
  permission: 'invoice.record_payment',
218
- 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 }) {
219
247
  const { ref, ...input } = a
220
248
  return { invoice: await ctx.clients.invoice.recordPayment(ref, input) }
221
249
  },
@@ -225,19 +253,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
225
253
  name: 'invoice_configure_numbering',
226
254
  title: 'Set the numbering series',
227
255
  description:
228
- '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). ' +
229
- '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). ' +
230
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.',
231
259
  input: z.object({
232
260
  prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe('Exactly 3 uppercase letters or digits.'),
233
261
  digits: z.number().int().min(1).max(12).describe('Counter width: 9 for e-Fatura.'),
234
- yearly: z.boolean().describe('true: the counter restarts each calendar year (of the issue date).'),
235
- 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.'),
236
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).'),
237
266
  }),
238
267
  access: 'write',
239
268
  permission: 'invoice.configure',
240
- 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) }),
241
270
  }),
242
271
 
243
272
  defineTool({
@@ -245,11 +274,11 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
245
274
  title: 'Void an invoice',
246
275
  description:
247
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. ' +
248
- '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`.',
249
- 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.') }),
250
279
  access: 'write',
251
280
  permission: 'invoice.void',
252
- 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 } : {}) }),
253
282
  }),
254
283
  ]
255
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
  }))