@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/cli.ts CHANGED
@@ -13,8 +13,9 @@ import type { ApiClient } from '@baseworks/cli/client'
13
13
  *
14
14
  * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
15
15
  * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
16
- * `invoices finalize <ref>` · `invoices set-external-number <ref> <number>` ·
17
- * `invoices pay <ref> --amount 150.00` · `invoices void <ref>`
16
+ * `invoices finalize <ref> [--date YYYY-MM-DD]` · `invoices set-external-number <ref> <number>` ·
17
+ * `invoices clear-external-number <ref>` · `invoices pay <ref> --amount 150.00` · `invoices void <ref>` ·
18
+ * `invoices ls --from 2027-01-01 --to 2027-01-31`
18
19
  */
19
20
  export interface InvoiceCliDeps {
20
21
  http: ApiClient
@@ -33,6 +34,9 @@ type InvoiceRow = {
33
34
  amount_paid_cents: number
34
35
  balance_cents: number
35
36
  created_at?: number
37
+ document_date?: string | null
38
+ due_date?: string | null
39
+ display_number?: string | null
36
40
  number_text?: string | null
37
41
  external_number?: string | null
38
42
  payment_status?: string
@@ -73,6 +77,8 @@ const NUMBER_COL = (v: unknown): string => (v ? (/^\d+$/.test(String(v)) ? `#${v
73
77
  /** The list's filters, on the bare command and on `ls`. */
74
78
  const filterOptions = (c: Command): Command =>
75
79
  c.option('--status <status>', 'Filter: draft | finalized | paid | void')
80
+ .option('--from <date>', 'Invoice date on or after, YYYY-MM-DD')
81
+ .option('--to <date>', 'Invoice date on or before, YYYY-MM-DD')
76
82
  .option('--payment-status <list>', 'unpaid | partially_paid | paid | not_due (comma-separated)')
77
83
  .option('--overdue', 'Owed, with a due date in the past')
78
84
  .option('--source <source>', 'local | stripe | manual')
@@ -84,9 +90,11 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
84
90
  const { http } = deps
85
91
  const cli = deps.cliName ?? 'cli'
86
92
 
87
- type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
93
+ type ListOpts = { output: string; from?: string; to?: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string; externalNumber?: string }
88
94
  const listInvoices = async (opts: ListOpts) => {
89
95
  const params = new URLSearchParams()
96
+ if (opts.from) params.set('from', opts.from)
97
+ if (opts.to) params.set('to', opts.to)
90
98
  if (opts.status) params.set('status', opts.status)
91
99
  if (opts.paymentStatus) params.set('payment_status', opts.paymentStatus)
92
100
  if (opts.overdue) params.set('overdue', 'true')
@@ -99,7 +107,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
99
107
  printOutput(res.invoices, opts.output, (wide) => {
100
108
  table(res.invoices, [
101
109
  { key: 'short_id', label: 'ID' },
102
- { key: 'number_text', label: 'NO', fmt: NUMBER_COL },
110
+ { key: 'display_number', label: 'NO', fmt: NUMBER_COL },
111
+ { key: 'document_date', label: 'DATE', fmt: (v) => (v as string) ?? '—' },
103
112
  { key: 'status', label: 'STATUS' },
104
113
  { key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
105
114
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
@@ -128,6 +137,8 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
128
137
  const parent = (this.parent?.opts() ?? {}) as ListOpts
129
138
  return listInvoices({
130
139
  output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
140
+ ...(self.from ?? parent.from ? { from: (self.from ?? parent.from) as string } : {}),
141
+ ...(self.to ?? parent.to ? { to: (self.to ?? parent.to) as string } : {}),
131
142
  ...(self.status ?? parent.status ? { status: (self.status ?? parent.status) as string } : {}),
132
143
  ...(self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: (self.paymentStatus ?? parent.paymentStatus) as string } : {}),
133
144
  ...(self.overdue ?? parent.overdue ? { overdue: true } : {}),
@@ -145,7 +156,7 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
145
156
  .requiredOption('--customer <ref>', 'Customer id, short_id, or external_id')
146
157
  .requiredOption('--currency <cur>', 'ISO-4217 currency (e.g. USD)')
147
158
  .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
148
- .option('--number <external>', 'A number another system gave it (up to 64 characters): the invoice keeps it and takes none from the series')
159
+ .option('--number <external>', 'A number another system gave it (up to 64 characters), kept beside the internal number it gets at finalize')
149
160
  .action(async (opts: { customer: string; currency: string; line: string[]; number?: string }) => {
150
161
  const lines = opts.line.map(parseLine)
151
162
  const res = await http.post<{ invoice: InvoiceRow }>('/invoices', {
@@ -170,12 +181,15 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
170
181
  printOutput(inv, opts.output, () => {
171
182
  kv([
172
183
  ['id', String(inv['short_id'])],
173
- ['number', inv['number_text'] ? NUMBER_COL(inv['number_text']) : '— (draft)'],
184
+ ['number', inv['number_text'] ? NUMBER_COL(inv['number_text']) : '—'],
174
185
  ...(inv['external_number'] ? [['external_number', String(inv['external_number'])] as [string, string]] : []),
175
186
  ['status', String(inv['status'])],
176
187
  ['customer', String(inv['customer_name'] ?? inv['customer_id'])],
177
- ['issued', inv['issued_at'] ? fmtDate(inv['issued_at'] as number) : '—'],
178
- ['due', inv['due_at'] ? fmtDate(inv['due_at'] as number) : '—'],
188
+ ['date', String(inv['document_date'] ?? '—')],
189
+ ['due', String(inv['due_date'] ?? '—')],
190
+ ...(inv['paid_date'] ? [['paid on', String(inv['paid_date'])] as [string, string]] : []),
191
+ ...(inv['void_date'] ? [['voided on', String(inv['void_date'])] as [string, string]] : []),
192
+ ...(inv['void_reason'] ? [['void reason', String(inv['void_reason'])] as [string, string]] : []),
179
193
  ])
180
194
  const lines = (inv['lines'] as Array<{ description: string; quantity: number; unit_price_cents: number; amount_cents: number }>) ?? []
181
195
  if (lines.length) {
@@ -217,43 +231,54 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
217
231
  cmd.addCommand(
218
232
  new Command('finalize').argument('<ref>')
219
233
  .description('Finalize a draft — assigns a number, freezes it (immutable)')
234
+ .option('--date <date>', 'Invoice date YYYY-MM-DD (default today, UTC)')
220
235
  .option('--due <date>', 'Due date YYYY-MM-DD')
221
- .option('--number <external>', 'A number another system gave it: it becomes the invoice\'s number and the series does not advance')
222
- .action(async (ref: string, opts: { due?: string; number?: string }) => {
236
+ .option('--number <external>', 'A number another system gave it, kept beside the internal number')
237
+ .action(async (ref: string, opts: { date?: string; due?: string; number?: string }) => {
223
238
  const body: Record<string, unknown> = {}
224
239
  if (opts.number) body['external_number'] = opts.number
225
- if (opts.due) {
226
- const ms = Date.parse(opts.due)
227
- if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
228
- body['due_at'] = ms
229
- }
240
+ if (opts.date) body['document_date'] = opts.date
241
+ if (opts.due) body['due_date'] = opts.due
230
242
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/finalize`, body).catch(die)
231
- success(`Invoice finalized: ${NUMBER_COL(res.invoice.number_text)}`)
232
- kv([['id', res.invoice.short_id], ['number', NUMBER_COL(res.invoice.number_text)], ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
243
+ success(`Invoice finalized: ${NUMBER_COL(res.invoice.display_number)}`)
244
+ kv([['id', res.invoice.short_id], ['number', NUMBER_COL(res.invoice.number_text)], ['date', res.invoice.document_date ?? '—'], ...(res.invoice.external_number ? [['external_number', res.invoice.external_number] as [string, string]] : []), ['total', fmtMoney(res.invoice.total_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
233
245
  }),
234
246
  )
235
247
 
236
248
  cmd.addCommand(
237
249
  new Command('set-external-number').argument('<ref>', 'id or short_id').argument('<number>', 'the number the other system gave it (up to 64 characters)')
238
- .description('Record the portal number of an already finalized or paid invoice, ONCE (needs `invoice.fiscal_update`). A wrong one is not corrected: void and re-issue.')
239
- .action(async (ref: string, number: string) => {
240
- const res = await http.api<{ invoice: InvoiceRow }>('PUT', `/invoices/${ref}/external-number`, { external_number: number }).catch(die)
250
+ .option('--from-invoice <invoice>', 'MOVE the number from this VOID invoice (id or short_id) to <ref>, in one operation')
251
+ .description('Set or change the portal number of a finalized, paid or void invoice (needs `invoice.fiscal_update`)')
252
+ .action(async (ref: string, number: string, opts: { fromInvoice?: string }) => {
253
+ const res = await http.api<{ invoice: InvoiceRow }>('PUT', `/invoices/${ref}/external-number`, { external_number: number, ...(opts.fromInvoice ? { from_invoice_id: opts.fromInvoice } : {}) }).catch(die)
241
254
  success(`External number set: ${res.invoice.external_number}`)
242
255
  kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['number', NUMBER_COL(res.invoice.number_text)], ['external_number', res.invoice.external_number ?? '']])
243
256
  }),
244
257
  )
245
258
 
259
+ cmd.addCommand(
260
+ new Command('clear-external-number').argument('<ref>', 'id or short_id')
261
+ .description('Take the portal number off a finalized, paid or void invoice, freeing it (needs `invoice.fiscal_update`)')
262
+ .action(async (ref: string) => {
263
+ const res = await http.del<{ invoice: InvoiceRow }>(`/invoices/${ref}/external-number`).catch(die)
264
+ success('External number cleared.')
265
+ kv([['id', res.invoice.short_id], ['status', res.invoice.status], ['number', NUMBER_COL(res.invoice.number_text)]])
266
+ }),
267
+ )
268
+
246
269
  cmd.addCommand(
247
270
  new Command('pay').argument('<ref>')
248
271
  .description('Record a payment against a finalized invoice')
249
272
  .requiredOption('--amount <amount>', 'Amount, e.g. 150.00')
250
273
  .option('--method <method>', 'e.g. bank, cash, card')
251
274
  .option('--ref <reference>', 'External payment reference')
252
- .action(async (ref: string, opts: { amount: string; method?: string; ref?: string }) => {
275
+ .option('--date <date>', 'The day of the payment, YYYY-MM-DD (default today, UTC)')
276
+ .action(async (ref: string, opts: { amount: string; method?: string; ref?: string; date?: string }) => {
253
277
  const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/payments`, {
254
278
  amount_cents: toCents(opts.amount),
255
279
  ...(opts.method ? { method: opts.method } : {}),
256
280
  ...(opts.ref ? { reference: opts.ref } : {}),
281
+ ...(opts.date ? { document_date: opts.date } : {}),
257
282
  }).catch(die)
258
283
  success(`Payment recorded. Invoice is now ${res.invoice.status}.`)
259
284
  kv([['id', res.invoice.short_id], ['paid', fmtMoney(res.invoice.amount_paid_cents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balance_cents, res.invoice.currency)]])
@@ -264,15 +289,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
264
289
  new Command('void').argument('<ref>')
265
290
  .description('Void a finalized invoice')
266
291
  .option('--reason <reason>', 'Reason')
267
- .action(async (ref: string, opts: { reason?: string }) => {
268
- const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
292
+ .option('--date <date>', 'The day it is voided, YYYY-MM-DD (default today, UTC)')
293
+ .action(async (ref: string, opts: { reason?: string; date?: string }) => {
294
+ const res = await http.post<{ invoice: InvoiceRow }>(`/invoices/${ref}/void`, { reason: opts.reason ?? '', ...(opts.date ? { void_date: opts.date } : {}) }).catch(die)
269
295
  success(`Invoice voided: ${res.invoice.short_id}`)
270
296
  }),
271
297
  )
272
298
 
273
- const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; time_zone: string; next: number; next_text: string } | null) =>
299
+ const showNumbering = (n: { prefix: string; digits: number; yearly: boolean; next: number; next_text: string } | null) =>
274
300
  n
275
- ? kv([['prefix', n.prefix], ['digits', String(n.digits)], ['yearly', n.yearly ? 'yes (the counter restarts each year)' : 'no'], ['time_zone', n.time_zone], ['next', `${n.next} → ${n.next_text}`]])
301
+ ? kv([['prefix', n.prefix], ['digits', String(n.digits)], ['yearly', n.yearly ? 'yes (the counter restarts each year)' : 'no'], ['next', `${n.next} → ${n.next_text}`]])
276
302
  : console.log('No series: invoices are numbered 1, 2, 3.')
277
303
  cmd.addCommand(
278
304
  new Command('numbering')
@@ -284,15 +310,16 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
284
310
  })
285
311
  .addCommand(
286
312
  new Command('set')
287
- .description('Set the series: PREFIX (3 uppercase letters or digits) + the issue year + a counter of --digits. Never renumbers a finalized invoice. Needs `invoice.configure`.')
313
+ .description('Set the series: PREFIX (3 uppercase letters or digits) + the year of the invoice date + a counter of --digits. Never renumbers a finalized invoice. Needs `invoice.configure`.')
288
314
  .requiredOption('--prefix <prefix>', '3 uppercase letters or digits, e.g. BSF')
289
315
  .requiredOption('--digits <n>', 'Counter width, 1 to 12 (9 for e-Fatura)')
290
316
  .option('--yearly', 'The counter restarts each calendar year')
291
- .option('--time-zone <zone>', 'IANA name, e.g. Europe/Istanbul: the year follows the issue date there (kept when omitted; UTC if never set)')
317
+ .option('--time-zone <zone>', 'Deprecated: accepted and ignored')
292
318
  .option('--next <n>', 'Continue from this counter (this year\'s, when yearly); it can only go forward')
293
- .action(async (opts: { prefix: string; digits: string; yearly?: boolean; timeZone?: string; next?: string }) => {
319
+ .option('--year <year>', 'Which year\'s series --next applies to (yearly only; default the current year, UTC)')
320
+ .action(async (opts: { prefix: string; digits: string; yearly?: boolean; next?: string; year?: string }) => {
294
321
  const res = await http.api<{ numbering: Parameters<typeof showNumbering>[0] }>('PUT', '/settings/numbering', {
295
- prefix: opts.prefix, digits: Number(opts.digits), yearly: !!opts.yearly, ...(opts.next ? { next: Number(opts.next) } : {}), ...(opts.timeZone ? { time_zone: opts.timeZone } : {}),
322
+ prefix: opts.prefix, digits: Number(opts.digits), yearly: !!opts.yearly, ...(opts.next ? { next: Number(opts.next) } : {}), ...(opts.year ? { year: Number(opts.year) } : {}),
296
323
  }).catch(die)
297
324
  success('Numbering series set.')
298
325
  showNumbering(res.numbering)
@@ -310,18 +337,27 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
310
337
 
311
338
  type TxnRow = {
312
339
  id: string; invoice_number: number; customer_name: string | null; customer_id: string
313
- kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; created_at?: number
340
+ kind: string; amount_cents: number; currency: string; method: string | null; reference: string | null; document_date?: string; created_at?: number
314
341
  }
315
342
  cmd.addCommand(
316
343
  new Command('payments').alias('transactions').argument('[ref]', 'invoice id/short_id (omit for all org transactions)')
317
344
  .description('List payments / transactions (the money ledger)')
345
+ .option('--from <date>', 'Paid on or after, YYYY-MM-DD')
346
+ .option('--to <date>', 'Paid on or before, YYYY-MM-DD')
318
347
  .option(...outputOption())
319
- .action(async (ref: string | undefined, opts: { output: string }) => {
320
- const path = ref ? `/invoices/${ref}/payments` : '/transactions'
348
+ .action(async function (this: Command, ref: string | undefined, opts: { output: string; from?: string; to?: string }) {
349
+ // `--from` / `--to` are the list's options too: commander gives them to whichever command declares them first
350
+ const parent = (this.parent?.opts() ?? {}) as { from?: string; to?: string }
351
+ const params = new URLSearchParams()
352
+ const from = opts.from ?? parent.from
353
+ const to = opts.to ?? parent.to
354
+ if (from) params.set('from', from)
355
+ if (to) params.set('to', to)
356
+ const path = `${ref ? `/invoices/${ref}/payments` : '/transactions'}${params.size ? `?${params}` : ''}`
321
357
  const res = await http.get<{ transactions: TxnRow[] }>(path).catch(die)
322
358
  printOutput(res.transactions, opts.output, (wide) => {
323
359
  table(res.transactions, [
324
- { key: 'created_at', label: 'DATE', fmt: (v) => fmtDate(v as number) },
360
+ { key: 'document_date', label: 'DATE', fmt: (v) => (v as string) ?? '—' },
325
361
  { key: 'invoice_number', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
326
362
  { key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customer_id },
327
363
  { key: 'kind', label: 'KIND' },
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 {
@@ -148,7 +153,13 @@ export class InvoiceClient {
148
153
  // ── invoices ──────────────────────────────────────────────────────────────
149
154
 
150
155
  async list(opts: ListInvoicesOptions = {}): Promise<Invoice[]> {
156
+ return (await this.listPage(opts)).invoices
157
+ }
158
+ /** One page and `next_offset` (null on the last page): pass it back as `offset` to read on. */
159
+ async listPage(opts: ListInvoicesOptions = {}): Promise<{ invoices: Invoice[]; next_offset?: number | null }> {
151
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)
152
163
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
153
164
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
154
165
  if (opts.status) q.set('status', opts.status)
@@ -159,8 +170,8 @@ export class InvoiceClient {
159
170
  if (opts.customer_id) q.set('customer_id', opts.customer_id)
160
171
  if (opts.external_number) q.set('external_number', opts.external_number)
161
172
  const qs = q.toString()
162
- const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
163
- return invoices.map(oldNamesOnInvoice)
173
+ const { invoices, next_offset } = await this.api<{ invoices: Invoice[]; next_offset?: number | null }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
174
+ return { invoices: invoices.map(oldNamesOnInvoice), next_offset }
164
175
  }
165
176
  async get(ref: string): Promise<Invoice> {
166
177
  const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/invoices/${ref}`)
@@ -200,12 +211,19 @@ export class InvoiceClient {
200
211
  return oldNamesOnInvoice(invoice)
201
212
  }
202
213
  /**
203
- * Record the number another system gave an invoice that is already finalized or paid (the e-Arşiv / GİB portal's).
204
- * Once: the same number again changes nothing, another one is `409 external_number_set`. Needs `invoice.fiscal_update`.
205
- * A draft is `409 use_update`.
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`).
206
219
  */
207
- async setExternalNumber(ref: string, external_number: string): Promise<Invoice> {
208
- const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/external-number`, { external_number })
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`)
209
227
  return oldNamesOnInvoice(invoice)
210
228
  }
211
229
  async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
@@ -216,30 +234,48 @@ export class InvoiceClient {
216
234
  const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/payments`, newNamesOnPayment(input))
217
235
  return oldNamesOnInvoice(invoice)
218
236
  }
219
- async void(ref: string, reason?: string): Promise<Invoice> {
220
- 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 } : {}) })
221
240
  return oldNamesOnInvoice(invoice)
222
241
  }
223
242
 
224
243
  // ── transactions (the payment ledger) ───────────────────────────────────────
225
244
 
226
- /** All transactions for the org, newest first. */
227
- 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[]> {
247
+ return (await this.transactionsPage(opts)).transactions
248
+ }
249
+
250
+ /** One page of the organization's transactions and `next_offset` (null on the last page). */
251
+ transactionsPage(opts: TransactionListOptions = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
252
+ return this.transactionList('/transactions', opts)
253
+ }
254
+
255
+ private async transactionList(path: string, opts: TransactionListOptions): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
228
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)
229
259
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
230
260
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
231
261
  const qs = q.toString()
232
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/transactions${qs ? `?${qs}` : ''}`)
233
- return transactions.map(oldNamesOnTransaction)
262
+ const { transactions, next_offset } = await this.api<{ transactions: Transaction[]; next_offset?: number | null }>('GET', `${path}${qs ? `?${qs}` : ''}`)
263
+ return { transactions: transactions.map(oldNamesOnTransaction), next_offset }
234
264
  }
235
265
 
236
- /** Transactions recorded against one invoice. */
266
+ /** Transactions recorded against one invoice: its first 100. `invoiceTransactionsPage` reads on. */
237
267
  async invoiceTransactions(ref: string): Promise<Transaction[]> {
238
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/invoices/${ref}/payments`)
239
- return transactions.map(oldNamesOnTransaction)
268
+ return (await this.invoiceTransactionsPage(ref)).transactions
269
+ }
270
+
271
+ /** One page of an invoice's transactions and `next_offset` (null on the last page). */
272
+ invoiceTransactionsPage(ref: string, opts: TransactionListOptions = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
273
+ return this.transactionList(`/invoices/${ref}/payments`, opts)
240
274
  }
241
275
  }
242
276
 
277
+ export type TransactionListOptions = DocumentDateRangeInput & { limit?: number; offset?: number }
278
+
243
279
  /** Factory used by the SDK capability registry. */
244
280
  export function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient {
245
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(() => []),