@baseworks/invoice 1.1.0 → 1.2.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/README.md CHANGED
@@ -76,6 +76,23 @@ The CLI lists with `--payment-status unpaid,partially_paid`, `--overdue`, `--sou
76
76
  a PAYMENT column. A mirror (`source: stripe | manual`) is read-only except through `mirror`: `update`, `finalize` and `void`
77
77
  throw `InvoiceError` `409 mirrored`.
78
78
 
79
+ ### 1.2.0: numbering series and external numbers
80
+
81
+ ```ts
82
+ await invoices.getNumbering() // null (plain 1, 2, 3) or { prefix, digits, yearly, next, next_text, updated_at }
83
+ await invoices.setNumbering({ prefix: 'BSF', digits: 9, yearly: true, next: 148, time_zone: 'Europe/Istanbul' }) // needs invoice.configure; never renumbers
84
+ // time_zone: the year in the number and the yearly restart follow the issue date there (UTC when never set; kept when omitted)
85
+ await invoices.clearNumbering()
86
+
87
+ await invoices.create({ customer_id, currency, lines, external_number: 'PORTAL-77' }) // another system's number
88
+ await invoices.finalize(id, { external_number: 'PORTAL-77' }) // it becomes the number; the series does not advance
89
+ await invoices.list({ external_number: 'PORTAL-77' }) // exact
90
+ // invoice.number (the counter), invoice.number_text ('BSF2026000000148'), invoice.external_number
91
+ ```
92
+
93
+ CLI: `invoices numbering`, `invoices numbering set --prefix BSF --digits 9 --yearly --time-zone Europe/Istanbul --next 148`, `invoices numbering clear`;
94
+ `invoices create|finalize --number <external>`; `invoices --external-number <n>`; the NO column shows the printed number.
95
+
79
96
  ### Deprecated names
80
97
 
81
98
  Until 0.3.0 the client and the service spoke camelCase. A caller that has not moved (billing-service, stripe-service, apps)
@@ -121,9 +138,11 @@ optional peer.
121
138
  | `invoice_list`, `invoice_get`, `invoice_transactions` | read | `invoice.read` |
122
139
  | `invoice_create`, `invoice_update` (drafts only) | write | `invoice.write` |
123
140
  | `invoice_finalize` (irreversible) | write | `invoice.finalize` |
141
+ | `invoice_numbering` | read | `invoice.read` |
142
+ | `invoice_configure_numbering` | write | `invoice.configure` |
124
143
  | `invoice_record_payment` | write | `invoice.record_payment` |
125
144
 
126
- `invoice_list` takes the same filters as the client; `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension.
145
+ `invoice_create` and `invoice_finalize` take `external_number`; `invoice_list` takes the same filters as the client (`external_number` too); `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension.
127
146
  | `invoice_void` (irreversible) | write | `invoice.void` |
128
147
 
129
148
  A tool is a thin wrapper over the same client, so it can never do what the API would refuse, and `permission` is the name
@@ -19,6 +19,8 @@ var InvoiceEvents = defineAggregate("invoice", {
19
19
  source: z.string().optional(),
20
20
  metadata: z.string().optional(),
21
21
  // JSON object, serialized
22
+ external_number: z.string().optional(),
23
+ // 1.2.0: a number given by another system ('' = none)
22
24
  at: z.number().int()
23
25
  }),
24
26
  // Draft edited (customer / lines). Only valid while status = draft.
@@ -30,6 +32,8 @@ var InvoiceEvents = defineAggregate("invoice", {
30
32
  total_cents: z.number().int(),
31
33
  metadata: z.string().optional(),
32
34
  // 1.1.0
35
+ external_number: z.string().optional(),
36
+ // 1.2.0
33
37
  at: z.number().int()
34
38
  }),
35
39
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -41,6 +45,11 @@ var InvoiceEvents = defineAggregate("invoice", {
41
45
  issued_at: z.number().int(),
42
46
  due_at: z.number().int(),
43
47
  // 0 = no due date
48
+ // 1.2.0. `number` is the counter of the series (0 when the number is the external one); `number_text` is the number as
49
+ // printed (`BSF2026000000148`, `7`, or the external number); `series_key` says which counter `number` belongs to.
50
+ number_text: z.string().optional(),
51
+ series_key: z.string().optional(),
52
+ external_number: z.string().optional(),
44
53
  at: z.number().int()
45
54
  }),
46
55
  // A payment applied to a finalized invoice. `amount_paid_cents` is the new running
@@ -102,6 +111,25 @@ var InvoiceEvents = defineAggregate("invoice", {
102
111
  at: z.number().int()
103
112
  })
104
113
  });
114
+ var NumberingEvents = defineAggregate("numbering", {
115
+ NumberingConfigured: z.object({
116
+ prefix: z.string(),
117
+ // 3 characters, A-Z 0-9
118
+ digits: z.number().int(),
119
+ yearly: z.boolean(),
120
+ next: z.number().int(),
121
+ // the counter `next_key` starts from
122
+ next_key: z.string(),
123
+ // the series key `next` applies to (prefix + year when yearly)
124
+ time_zone: z.string().optional(),
125
+ // IANA name; absent = UTC. The year in the number and the yearly reset follow it
126
+ at: z.number().int()
127
+ }),
128
+ NumberingCleared: z.object({ at: z.number().int() }),
129
+ NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
130
+ NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
131
+ ExternalNumberClaimed: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() })
132
+ });
105
133
  var FISCAL_STATUSES = ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
106
134
  var INVOICE_SOURCES = ["local", "stripe", "manual"];
107
135
  var TransactionKind = z.enum(["payment", "refund", "adjustment"]);
@@ -126,6 +154,7 @@ var TransactionEvents = defineAggregate("transaction", {
126
154
  export {
127
155
  InvoiceStatus,
128
156
  InvoiceEvents,
157
+ NumberingEvents,
129
158
  FISCAL_STATUSES,
130
159
  INVOICE_SOURCES,
131
160
  TransactionKind,
package/dist/cli.js CHANGED
@@ -22,8 +22,8 @@ function parseLine(spec) {
22
22
  if (!Number.isFinite(quantity) || quantity <= 0) fatal(`--line qty must be > 0 in '${spec}'`);
23
23
  return { description, quantity, unit_price_cents: toCents(parts[2].trim(), "--line unitPrice") };
24
24
  }
25
- var NUMBER_COL = (v) => v ? `#${v}` : "\u2014";
26
- var filterOptions = (c) => c.option("--status <status>", "Filter: draft | finalized | paid | void").option("--payment-status <list>", "unpaid | partially_paid | paid | not_due (comma-separated)").option("--overdue", "Owed, with a due date in the past").option("--source <source>", "local | stripe | manual").option("--fiscal-status <status>", "not_submitted | queued | submitted | accepted | rejected | cancelled").option("--customer-id <id>", "Only this customer (its id)");
25
+ var NUMBER_COL = (v) => v ? /^\d+$/.test(String(v)) ? `#${v}` : String(v) : "\u2014";
26
+ var filterOptions = (c) => c.option("--status <status>", "Filter: draft | finalized | paid | void").option("--payment-status <list>", "unpaid | partially_paid | paid | not_due (comma-separated)").option("--overdue", "Owed, with a due date in the past").option("--source <source>", "local | stripe | manual").option("--fiscal-status <status>", "not_submitted | queued | submitted | accepted | rejected | cancelled").option("--customer-id <id>", "Only this customer (its id)").option("--external-number <number>", "Only the invoice with this external number (exact)");
27
27
  function buildInvoiceCommand(deps) {
28
28
  const { http } = deps;
29
29
  const cli = deps.cliName ?? "cli";
@@ -35,12 +35,13 @@ function buildInvoiceCommand(deps) {
35
35
  if (opts.source) params.set("source", opts.source);
36
36
  if (opts.fiscalStatus) params.set("fiscal_status", opts.fiscalStatus);
37
37
  if (opts.customerId) params.set("customer_id", opts.customerId);
38
+ if (opts.externalNumber) params.set("external_number", opts.externalNumber);
38
39
  const q = params.toString() ? `?${params}` : "";
39
40
  const res = await http.get(`/invoices${q}`).catch(die);
40
41
  printOutput(res.invoices, opts.output, (wide) => {
41
42
  table(res.invoices, [
42
43
  { key: "short_id", label: "ID" },
43
- { key: "number", label: "NO", fmt: NUMBER_COL },
44
+ { key: "number_text", label: "NO", fmt: NUMBER_COL },
44
45
  { key: "status", label: "STATUS" },
45
46
  { key: "payment_status", label: "PAYMENT", fmt: (v) => v ?? "" },
46
47
  { key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
@@ -66,17 +67,19 @@ function buildInvoiceCommand(deps) {
66
67
  ...self.overdue ?? parent.overdue ? { overdue: true } : {},
67
68
  ...self.source ?? parent.source ? { source: self.source ?? parent.source } : {},
68
69
  ...self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: self.fiscalStatus ?? parent.fiscalStatus } : {},
69
- ...self.customerId ?? parent.customerId ? { customerId: self.customerId ?? parent.customerId } : {}
70
+ ...self.customerId ?? parent.customerId ? { customerId: self.customerId ?? parent.customerId } : {},
71
+ ...self.externalNumber ?? parent.externalNumber ? { externalNumber: self.externalNumber ?? parent.externalNumber } : {}
70
72
  });
71
73
  })
72
74
  );
73
75
  cmd.addCommand(
74
- new Command("create").description("Create a draft invoice").requiredOption("--customer <ref>", "Customer id, short_id, or external_id").requiredOption("--currency <cur>", "ISO-4217 currency (e.g. USD)").requiredOption("--line <spec...>", 'Line "description|qty|unitPrice" (repeatable)').action(async (opts) => {
76
+ new Command("create").description("Create a draft invoice").requiredOption("--customer <ref>", "Customer id, short_id, or external_id").requiredOption("--currency <cur>", "ISO-4217 currency (e.g. USD)").requiredOption("--line <spec...>", 'Line "description|qty|unitPrice" (repeatable)').option("--number <external>", "A number another system gave it (up to 64 characters): the invoice keeps it and takes none from the series").action(async (opts) => {
75
77
  const lines = opts.line.map(parseLine);
76
78
  const res = await http.post("/invoices", {
77
79
  customer_id: opts.customer,
78
80
  currency: opts.currency,
79
- lines
81
+ lines,
82
+ ...opts.number ? { external_number: opts.number } : {}
80
83
  }).catch(die);
81
84
  success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`);
82
85
  kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)]]);
@@ -90,7 +93,8 @@ function buildInvoiceCommand(deps) {
90
93
  printOutput(inv, opts.output, () => {
91
94
  kv([
92
95
  ["id", String(inv["short_id"])],
93
- ["number", inv["number"] ? `#${inv["number"]}` : "\u2014 (draft)"],
96
+ ["number", inv["number_text"] ? NUMBER_COL(inv["number_text"]) : "\u2014 (draft)"],
97
+ ...inv["external_number"] ? [["external_number", String(inv["external_number"])]] : [],
94
98
  ["status", String(inv["status"])],
95
99
  ["customer", String(inv["customer_name"] ?? inv["customer_id"])],
96
100
  ["issued", inv["issued_at"] ? fmtDate(inv["issued_at"]) : "\u2014"],
@@ -128,16 +132,17 @@ function buildInvoiceCommand(deps) {
128
132
  })
129
133
  );
130
134
  cmd.addCommand(
131
- new Command("finalize").argument("<ref>").description("Finalize a draft \u2014 assigns a number, freezes it (immutable)").option("--due <date>", "Due date YYYY-MM-DD").action(async (ref, opts) => {
135
+ new Command("finalize").argument("<ref>").description("Finalize a draft \u2014 assigns a number, freezes it (immutable)").option("--due <date>", "Due date YYYY-MM-DD").option("--number <external>", "A number another system gave it: it becomes the invoice's number and the series does not advance").action(async (ref, opts) => {
132
136
  const body = {};
137
+ if (opts.number) body["external_number"] = opts.number;
133
138
  if (opts.due) {
134
139
  const ms = Date.parse(opts.due);
135
140
  if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`);
136
141
  body["due_at"] = ms;
137
142
  }
138
143
  const res = await http.post(`/invoices/${ref}/finalize`, body).catch(die);
139
- success(`Invoice finalized: #${res.invoice.number}`);
140
- kv([["id", res.invoice.short_id], ["number", `#${res.invoice.number}`], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balance_cents, res.invoice.currency)]]);
144
+ success(`Invoice finalized: ${NUMBER_COL(res.invoice.number_text)}`);
145
+ kv([["id", res.invoice.short_id], ["number", NUMBER_COL(res.invoice.number_text)], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balance_cents, res.invoice.currency)]]);
141
146
  })
142
147
  );
143
148
  cmd.addCommand(
@@ -157,6 +162,30 @@ function buildInvoiceCommand(deps) {
157
162
  success(`Invoice voided: ${res.invoice.short_id}`);
158
163
  })
159
164
  );
165
+ const showNumbering = (n) => n ? 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} \u2192 ${n.next_text}`]]) : console.log("No series: invoices are numbered 1, 2, 3.");
166
+ cmd.addCommand(
167
+ new Command("numbering").description("Show the organization's numbering series (needs `invoice.read`)").option(...outputOption()).action(async (opts) => {
168
+ const res = await http.get("/settings/numbering").catch(die);
169
+ printOutput(res.numbering ?? {}, opts.output, () => showNumbering(res.numbering), "prefix");
170
+ }).addCommand(
171
+ new Command("set").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`.").requiredOption("--prefix <prefix>", "3 uppercase letters or digits, e.g. BSF").requiredOption("--digits <n>", "Counter width, 1 to 12 (9 for e-Fatura)").option("--yearly", "The counter restarts each calendar year").option("--time-zone <zone>", "IANA name, e.g. Europe/Istanbul: the year follows the issue date there (kept when omitted; UTC if never set)").option("--next <n>", "Continue from this counter (this year's, when yearly); it can only go forward").action(async (opts) => {
172
+ const res = await http.api("PUT", "/settings/numbering", {
173
+ prefix: opts.prefix,
174
+ digits: Number(opts.digits),
175
+ yearly: !!opts.yearly,
176
+ ...opts.next ? { next: Number(opts.next) } : {},
177
+ ...opts.timeZone ? { time_zone: opts.timeZone } : {}
178
+ }).catch(die);
179
+ success("Numbering series set.");
180
+ showNumbering(res.numbering);
181
+ })
182
+ ).addCommand(
183
+ new Command("clear").description("Back to plain 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`.").action(async () => {
184
+ await http.del("/settings/numbering").catch(die);
185
+ success("No series: invoices are numbered 1, 2, 3.");
186
+ })
187
+ )
188
+ );
160
189
  cmd.addCommand(
161
190
  new Command("payments").alias("transactions").argument("[ref]", "invoice id/short_id (omit for all org transactions)").description("List payments / transactions (the money ledger)").option(...outputOption()).action(async (ref, opts) => {
162
191
  const path = ref ? `/invoices/${ref}/payments` : "/transactions";
package/dist/client.d.ts CHANGED
@@ -31,6 +31,9 @@ interface InvoiceRow {
31
31
  fiscal_external_id: string | null;
32
32
  fiscal_message: string | null;
33
33
  fiscal_updated_at: number | null;
34
+ number_text: string | null;
35
+ series_key: string | null;
36
+ external_number: string | null;
34
37
  }
35
38
  interface InvoiceLineDto {
36
39
  description: string;
@@ -107,6 +110,13 @@ interface InvoiceDto {
107
110
  tax_cents: number;
108
111
  payment_status: PaymentStatus;
109
112
  fiscal: Fiscal | null;
113
+ /**
114
+ * The number as printed: `BSF2026000000148` in a series, `7` without one, the external number when the invoice has one.
115
+ * `null` while a draft. `number` is the series' counter (`null` when the number is the external one).
116
+ */
117
+ number_text: string | null;
118
+ /** A number given by another system (an e-Fatura portal, say), up to 64 characters. Unique among non-void invoices. */
119
+ external_number: string | null;
110
120
  /** Only `GET /invoices/:ref` includes the payments. */
111
121
  payments?: InvoicePayment[];
112
122
  }
@@ -155,6 +165,8 @@ interface CreateInvoiceInput {
155
165
  currency: string;
156
166
  lines: InvoiceLineInput[];
157
167
  metadata?: Metadata;
168
+ /** A number from another system; the invoice keeps it and takes none from the series at finalize. */
169
+ external_number?: string;
158
170
  /** @deprecated Send `customer_id`. */
159
171
  customerId?: string;
160
172
  }
@@ -163,6 +175,8 @@ interface UpdateInvoiceInput {
163
175
  lines?: InvoiceLineInput[];
164
176
  /** Replaces the invoice's metadata. */
165
177
  metadata?: Metadata;
178
+ /** Sets (or, with null, clears) the external number of a draft. */
179
+ external_number?: string | null;
166
180
  /** @deprecated Send `customer_id`. */
167
181
  customerId?: string;
168
182
  }
@@ -171,6 +185,8 @@ interface FinalizeInvoiceInput {
171
185
  issued_at?: number;
172
186
  /** Epoch millis; 0/omitted = no due date. */
173
187
  due_at?: number;
188
+ /** The number another system gave it. Then it is the invoice's number and the series does not advance. */
189
+ external_number?: string;
174
190
  /** @deprecated Send `issued_at`. */
175
191
  issuedAt?: number;
176
192
  /** @deprecated Send `due_at`. */
@@ -196,6 +212,8 @@ interface ListInvoicesOptions {
196
212
  source?: InvoiceSource;
197
213
  fiscal_status?: FiscalStatus;
198
214
  customer_id?: string;
215
+ /** Exact. */
216
+ external_number?: string;
199
217
  }
200
218
  /** The provider's whole document, for `PUT /invoices/mirror`. */
201
219
  interface MirrorInvoiceInput {
@@ -229,6 +247,31 @@ interface MirrorResult {
229
247
  /** True when the document was older than the one stored and was ignored. */
230
248
  stale?: boolean;
231
249
  }
250
+ /** An organization's numbering series. `number_text` is `${prefix}${issue year}${counter, zero-padded to digits}`. */
251
+ interface Numbering {
252
+ prefix: string;
253
+ digits: number;
254
+ yearly: boolean;
255
+ /** IANA name (`Europe/Istanbul`); `UTC` when none is set. The year in the number and the yearly reset follow the issue date in it. */
256
+ time_zone: string;
257
+ /** The counter the next invoice finalized now would get. */
258
+ next: number;
259
+ /** What that number would read, for the current year. */
260
+ next_text: string;
261
+ updated_at: number;
262
+ }
263
+ interface NumberingInput {
264
+ /** 3 uppercase letters or digits. */
265
+ prefix: string;
266
+ /** 1 to 12; 9 for e-Fatura. */
267
+ digits: number;
268
+ /** true: the counter restarts each calendar year (of the issue date). */
269
+ yearly: boolean;
270
+ /** IANA name. Omitted: stays as it was (UTC if never set). */
271
+ time_zone?: string;
272
+ /** The counter to continue from (this year's, when yearly). Omitted: the series continues where it is. It can only go forward. */
273
+ next?: number;
274
+ }
232
275
  interface FiscalInput {
233
276
  status: FiscalStatus;
234
277
  system?: string;
@@ -337,6 +380,12 @@ declare class InvoiceClient {
337
380
  * `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
338
381
  */
339
382
  mirror(input: MirrorInvoiceInput): Promise<MirrorResult>;
383
+ /** The organization's numbering series; `null` while it has none (invoices are numbered 1, 2, 3). */
384
+ getNumbering(): Promise<Numbering | null>;
385
+ /** Set the series (`BSF` + issue year + a counter of `digits`). Needs `invoice.configure`. Never renumbers a finalized invoice. */
386
+ setNumbering(input: NumberingInput): Promise<Numbering>;
387
+ /** Back to 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`. */
388
+ clearNumbering(): Promise<void>;
340
389
  /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
341
390
  setFiscal(ref: string, input: FiscalInput): Promise<Invoice>;
342
391
  finalize(ref: string, input?: FinalizeInvoiceInput): Promise<Invoice>;
@@ -353,4 +402,4 @@ declare class InvoiceClient {
353
402
  /** Factory used by the SDK capability registry. */
354
403
  declare function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient;
355
404
 
356
- export { type CreateInvoiceInput, type ExternalRef, type FinalizeInvoiceInput, type Fiscal, type FiscalInput, FiscalStatus, type HttpClient, type Invoice, InvoiceClient, type InvoiceClientOptions, type InvoiceDeprecated, type InvoiceDto, InvoiceError, type InvoiceLine, type InvoiceLineDeprecated, type InvoiceLineDto, type InvoiceLineInput, type InvoicePayment, type InvoiceRow, InvoiceSource, InvoiceStatus, type ListInvoicesOptions, type Metadata, type MirrorInvoiceInput, type MirrorResult, type PaymentStatus, type RecordPaymentInput, type Transaction, type TransactionDeprecated, type TransactionDto, type TransactionRow, type UpdateInvoiceInput, createInvoiceClient };
405
+ export { type CreateInvoiceInput, type ExternalRef, type FinalizeInvoiceInput, type Fiscal, type FiscalInput, FiscalStatus, type HttpClient, type Invoice, InvoiceClient, type InvoiceClientOptions, type InvoiceDeprecated, type InvoiceDto, InvoiceError, type InvoiceLine, type InvoiceLineDeprecated, type InvoiceLineDto, type InvoiceLineInput, type InvoicePayment, type InvoiceRow, InvoiceSource, InvoiceStatus, type ListInvoicesOptions, type Metadata, type MirrorInvoiceInput, type MirrorResult, type Numbering, type NumberingInput, type PaymentStatus, type RecordPaymentInput, type Transaction, type TransactionDeprecated, type TransactionDto, type TransactionRow, type UpdateInvoiceInput, createInvoiceClient };
package/dist/client.js CHANGED
@@ -124,6 +124,7 @@ var InvoiceClient = class _InvoiceClient {
124
124
  if (opts.source) q.set("source", opts.source);
125
125
  if (opts.fiscal_status) q.set("fiscal_status", opts.fiscal_status);
126
126
  if (opts.customer_id) q.set("customer_id", opts.customer_id);
127
+ if (opts.external_number) q.set("external_number", opts.external_number);
127
128
  const qs = q.toString();
128
129
  const { invoices } = await this.api("GET", `/invoices${qs ? `?${qs}` : ""}`);
129
130
  return invoices.map(oldNamesOnInvoice);
@@ -148,6 +149,18 @@ var InvoiceClient = class _InvoiceClient {
148
149
  const r = await this.api("PUT", "/invoices/mirror", input);
149
150
  return { ...r, invoice: oldNamesOnInvoice(r.invoice) };
150
151
  }
152
+ /** The organization's numbering series; `null` while it has none (invoices are numbered 1, 2, 3). */
153
+ async getNumbering() {
154
+ return (await this.api("GET", "/settings/numbering")).numbering;
155
+ }
156
+ /** Set the series (`BSF` + issue year + a counter of `digits`). Needs `invoice.configure`. Never renumbers a finalized invoice. */
157
+ async setNumbering(input) {
158
+ return (await this.api("PUT", "/settings/numbering", input)).numbering;
159
+ }
160
+ /** Back to 1, 2, 3 for what is finalized from now on. Needs `invoice.configure`. */
161
+ async clearNumbering() {
162
+ await this.api("DELETE", "/settings/numbering");
163
+ }
151
164
  /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
152
165
  async setFiscal(ref, input) {
153
166
  const { invoice } = await this.api("PUT", `/invoices/${ref}/fiscal`, input);
package/dist/events.d.ts CHANGED
@@ -35,6 +35,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
35
35
  short_id: z.ZodString;
36
36
  source: z.ZodOptional<z.ZodString>;
37
37
  metadata: z.ZodOptional<z.ZodString>;
38
+ external_number: z.ZodOptional<z.ZodString>;
38
39
  at: z.ZodNumber;
39
40
  }, "strip", z.ZodTypeAny, {
40
41
  at: number;
@@ -47,6 +48,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
47
48
  total_cents: number;
48
49
  source?: string | undefined;
49
50
  metadata?: string | undefined;
51
+ external_number?: string | undefined;
50
52
  }, {
51
53
  at: number;
52
54
  lines: string;
@@ -58,6 +60,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
58
60
  total_cents: number;
59
61
  source?: string | undefined;
60
62
  metadata?: string | undefined;
63
+ external_number?: string | undefined;
61
64
  }>;
62
65
  InvoiceUpdated: z.ZodObject<{
63
66
  customer_id: z.ZodString;
@@ -66,6 +69,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
66
69
  subtotal_cents: z.ZodNumber;
67
70
  total_cents: z.ZodNumber;
68
71
  metadata: z.ZodOptional<z.ZodString>;
72
+ external_number: z.ZodOptional<z.ZodString>;
69
73
  at: z.ZodNumber;
70
74
  }, "strip", z.ZodTypeAny, {
71
75
  at: number;
@@ -75,6 +79,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
75
79
  subtotal_cents: number;
76
80
  total_cents: number;
77
81
  metadata?: string | undefined;
82
+ external_number?: string | undefined;
78
83
  }, {
79
84
  at: number;
80
85
  lines: string;
@@ -83,6 +88,7 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
83
88
  subtotal_cents: number;
84
89
  total_cents: number;
85
90
  metadata?: string | undefined;
91
+ external_number?: string | undefined;
86
92
  }>;
87
93
  InvoiceFinalized: z.ZodObject<{
88
94
  number: z.ZodNumber;
@@ -91,6 +97,9 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
91
97
  total_cents: z.ZodNumber;
92
98
  issued_at: z.ZodNumber;
93
99
  due_at: z.ZodNumber;
100
+ number_text: z.ZodOptional<z.ZodString>;
101
+ series_key: z.ZodOptional<z.ZodString>;
102
+ external_number: z.ZodOptional<z.ZodString>;
94
103
  at: z.ZodNumber;
95
104
  }, "strip", z.ZodTypeAny, {
96
105
  number: number;
@@ -100,6 +109,9 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
100
109
  total_cents: number;
101
110
  issued_at: number;
102
111
  due_at: number;
112
+ number_text?: string | undefined;
113
+ external_number?: string | undefined;
114
+ series_key?: string | undefined;
103
115
  }, {
104
116
  number: number;
105
117
  at: number;
@@ -108,6 +120,9 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
108
120
  total_cents: number;
109
121
  issued_at: number;
110
122
  due_at: number;
123
+ number_text?: string | undefined;
124
+ external_number?: string | undefined;
125
+ series_key?: string | undefined;
111
126
  }>;
112
127
  PaymentRecorded: z.ZodObject<{
113
128
  amount_cents: z.ZodNumber;
@@ -233,6 +248,86 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
233
248
  }> & {
234
249
  newId(): string;
235
250
  };
251
+ /**
252
+ * 1.2.0. An organization's numbering series, and the claims that keep numbers unique. One aggregate, many streams:
253
+ * `numbering-settings` holds the series; one stream per (series key, counter) serializes who takes that number; one per
254
+ * external number serializes who holds it.
255
+ */
256
+ declare const NumberingEvents: _baseworks_foldbase.EventCatalog<{
257
+ NumberingConfigured: z.ZodObject<{
258
+ prefix: z.ZodString;
259
+ digits: z.ZodNumber;
260
+ yearly: z.ZodBoolean;
261
+ next: z.ZodNumber;
262
+ next_key: z.ZodString;
263
+ time_zone: z.ZodOptional<z.ZodString>;
264
+ at: z.ZodNumber;
265
+ }, "strip", z.ZodTypeAny, {
266
+ at: number;
267
+ prefix: string;
268
+ digits: number;
269
+ yearly: boolean;
270
+ next: number;
271
+ next_key: string;
272
+ time_zone?: string | undefined;
273
+ }, {
274
+ at: number;
275
+ prefix: string;
276
+ digits: number;
277
+ yearly: boolean;
278
+ next: number;
279
+ next_key: string;
280
+ time_zone?: string | undefined;
281
+ }>;
282
+ NumberingCleared: z.ZodObject<{
283
+ at: z.ZodNumber;
284
+ }, "strip", z.ZodTypeAny, {
285
+ at: number;
286
+ }, {
287
+ at: number;
288
+ }>;
289
+ NumberClaimed: z.ZodObject<{
290
+ invoice_id: z.ZodString;
291
+ series_key: z.ZodString;
292
+ number: z.ZodNumber;
293
+ at: z.ZodNumber;
294
+ }, "strip", z.ZodTypeAny, {
295
+ number: number;
296
+ at: number;
297
+ invoice_id: string;
298
+ series_key: string;
299
+ }, {
300
+ number: number;
301
+ at: number;
302
+ invoice_id: string;
303
+ series_key: string;
304
+ }>;
305
+ NumberReleased: z.ZodObject<{
306
+ invoice_id: z.ZodString;
307
+ at: z.ZodNumber;
308
+ }, "strip", z.ZodTypeAny, {
309
+ at: number;
310
+ invoice_id: string;
311
+ }, {
312
+ at: number;
313
+ invoice_id: string;
314
+ }>;
315
+ ExternalNumberClaimed: z.ZodObject<{
316
+ external_number: z.ZodString;
317
+ invoice_id: z.ZodString;
318
+ at: z.ZodNumber;
319
+ }, "strip", z.ZodTypeAny, {
320
+ at: number;
321
+ external_number: string;
322
+ invoice_id: string;
323
+ }, {
324
+ at: number;
325
+ external_number: string;
326
+ invoice_id: string;
327
+ }>;
328
+ }> & {
329
+ newId(): string;
330
+ };
236
331
  declare const FISCAL_STATUSES: readonly ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
237
332
  type FiscalStatus = (typeof FISCAL_STATUSES)[number];
238
333
  declare const INVOICE_SOURCES: readonly ["local", "stripe", "manual"];
@@ -288,4 +383,4 @@ declare const TransactionEvents: _baseworks_foldbase.EventCatalog<{
288
383
  newId(): string;
289
384
  };
290
385
 
291
- export { FISCAL_STATUSES, type FiscalStatus, INVOICE_SOURCES, InvoiceEvents, type InvoiceSource, InvoiceStatus, TransactionEvents, TransactionKind };
386
+ export { FISCAL_STATUSES, type FiscalStatus, INVOICE_SOURCES, InvoiceEvents, type InvoiceSource, InvoiceStatus, NumberingEvents, TransactionEvents, TransactionKind };
package/dist/events.js CHANGED
@@ -3,14 +3,16 @@ import {
3
3
  INVOICE_SOURCES,
4
4
  InvoiceEvents,
5
5
  InvoiceStatus,
6
+ NumberingEvents,
6
7
  TransactionEvents,
7
8
  TransactionKind
8
- } from "./chunk-335MPCTE.js";
9
+ } from "./chunk-THLNZVGO.js";
9
10
  export {
10
11
  FISCAL_STATUSES,
11
12
  INVOICE_SOURCES,
12
13
  InvoiceEvents,
13
14
  InvoiceStatus,
15
+ NumberingEvents,
14
16
  TransactionEvents,
15
17
  TransactionKind
16
18
  };
package/dist/mcp.js CHANGED
@@ -14,7 +14,7 @@ function invoiceTools() {
14
14
  defineTool({
15
15
  name: "invoice_list",
16
16
  title: "List invoices",
17
- description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. 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: filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
17
+ description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. 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: 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.',
18
18
  input: z.object({
19
19
  status: z.enum(["draft", "finalized", "paid", "void"]).optional().describe("Only invoices in this status."),
20
20
  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."),
@@ -22,6 +22,7 @@ function invoiceTools() {
22
22
  source: z.enum(["local", "stripe", "manual"]).optional().describe("`local` was made here, `stripe` mirrors a Stripe invoice, `manual` was entered from a document issued elsewhere."),
23
23
  fiscal_status: z.enum(["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"]).optional().describe("Only invoices in this state with a tax system."),
24
24
  customer_id: z.string().optional().describe("Only this customer's invoices: the customer's id."),
25
+ external_number: z.string().optional().describe("Only the invoice with this exact external number (the number another system gave it)."),
25
26
  limit: z.number().int().min(1).max(100).optional().describe("Page size, 1 to 100 (default 25)."),
26
27
  offset: z.number().int().min(0).optional().describe("How many to skip, for the next page.")
27
28
  }),
@@ -36,7 +37,8 @@ function invoiceTools() {
36
37
  ...a.overdue !== void 0 ? { overdue: a.overdue } : {},
37
38
  ...a.source ? { source: a.source } : {},
38
39
  ...a.fiscal_status ? { fiscal_status: a.fiscal_status } : {},
39
- ...a.customer_id ? { customer_id: a.customer_id } : {}
40
+ ...a.customer_id ? { customer_id: a.customer_id } : {},
41
+ ...a.external_number ? { external_number: a.external_number } : {}
40
42
  })
41
43
  })
42
44
  }),
@@ -49,6 +51,15 @@ function invoiceTools() {
49
51
  permission: "invoice.read",
50
52
  run: async (ctx, a) => ({ invoice: await ctx.clients.invoice.get(a.ref) })
51
53
  }),
54
+ defineTool({
55
+ name: "invoice_numbering",
56
+ title: "Show the numbering series",
57
+ description: "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. `next_text` is the number the next invoice finalized now would get (for example BSF2026000000149: the prefix, the issue year, then the counter). 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.",
58
+ input: z.object({}),
59
+ access: "read",
60
+ permission: "invoice.read",
61
+ run: async (ctx) => ({ numbering: await ctx.clients.invoice.getNumbering() })
62
+ }),
52
63
  defineTool({
53
64
  name: "invoice_transactions",
54
65
  title: "List payments",
@@ -67,11 +78,12 @@ function invoiceTools() {
67
78
  defineTool({
68
79
  name: "invoice_create",
69
80
  title: "Draft an invoice",
70
- description: "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. The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. 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. It is recorded as you, the agent acting for the person who connected you.",
81
+ description: "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. The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. 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. 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. It is recorded as you, the agent acting for the person who connected you.",
71
82
  input: z.object({
72
83
  customer_id,
73
84
  currency: z.string().length(3).describe("ISO 4217 code, e.g. EUR, USD, TRY."),
74
- lines: z.array(Line).min(1).describe("At least one line.")
85
+ lines: z.array(Line).min(1).describe("At least one line."),
86
+ 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`).")
75
87
  }),
76
88
  access: "write",
77
89
  permission: "invoice.write",
@@ -99,11 +111,12 @@ function invoiceTools() {
99
111
  defineTool({
100
112
  name: "invoice_finalize",
101
113
  title: "Finalize an invoice",
102
- description: "Issues a draft: it gets the next number of the organization, its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). 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). Only a draft can be finalized: otherwise `not_draft`.",
114
+ description: "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). 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). 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`.",
103
115
  input: z.object({
104
116
  ref: REF,
105
117
  issued_at: z.number().int().optional().describe("Epoch milliseconds; default now."),
106
- due_at: z.number().int().optional().describe("Epoch milliseconds; omit for no due date.")
118
+ due_at: z.number().int().optional().describe("Epoch milliseconds; omit for no due date."),
119
+ 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.")
107
120
  }),
108
121
  access: "write",
109
122
  permission: "invoice.finalize",
@@ -130,6 +143,21 @@ function invoiceTools() {
130
143
  return { invoice: await ctx.clients.invoice.recordPayment(ref, input) };
131
144
  }
132
145
  }),
146
+ defineTool({
147
+ name: "invoice_configure_numbering",
148
+ title: "Set the numbering series",
149
+ description: "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). 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). 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.",
150
+ input: z.object({
151
+ prefix: z.string().regex(/^[A-Z0-9]{3}$/).describe("Exactly 3 uppercase letters or digits."),
152
+ digits: z.number().int().min(1).max(12).describe("Counter width: 9 for e-Fatura."),
153
+ yearly: z.boolean().describe("true: the counter restarts each calendar year (of the issue date)."),
154
+ 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)."),
155
+ 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.")
156
+ }),
157
+ access: "write",
158
+ permission: "invoice.configure",
159
+ run: async (ctx, a) => ({ numbering: await ctx.clients.invoice.setNumbering(a) })
160
+ }),
133
161
  defineTool({
134
162
  name: "invoice_void",
135
163
  title: "Void an invoice",