@baseworks/invoice 1.0.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
@@ -55,6 +55,44 @@ await invoices.void(final.id, 'issued in error')
55
55
  Errors throw `InvoiceError` (`.status`, `.code`): `403 forbidden` (with the missing permission, e.g. `invoice.write`),
56
56
  `409 not_draft` (edit a finalized invoice), `409 overpayment` / `409 already_paid`, `404 customer_not_found`.
57
57
 
58
+ ### 1.1.0: sources, payment status, filters, fiscal state
59
+
60
+ ```ts
61
+ // what is still owed, and what is late
62
+ await invoices.list({ payment_status: ['unpaid', 'partially_paid'] })
63
+ await invoices.list({ overdue: true, source: 'local', customer_id: 'cus_1' }) // filters combine
64
+
65
+ const inv = await invoices.get(id) // inv.payment_status, inv.source, inv.external_refs, inv.metadata, inv.fiscal, inv.payments
66
+
67
+ // a provider's document, whole: creates or replaces by external_ref (system + id); `created`, `stale`
68
+ await invoices.mirror({ source: 'stripe', external_ref: { system: 'stripe', id: 'in_…', number, url, pdf_url, account_id, livemode },
69
+ customer_id, currency, lines, subtotal_cents, tax_cents, total_cents, status: 'finalized', issued_at, provider_updated_at })
70
+
71
+ await invoices.recordPayment(id, { amount_cents: 990, payment_id: 'pay_…' }) // the same payment_id twice records it once
72
+ await invoices.setFiscal(id, { status: 'submitted', system: 'gib', external_id }) // needs invoice.fiscal_update
73
+ ```
74
+
75
+ The CLI lists with `--payment-status unpaid,partially_paid`, `--overdue`, `--source`, `--fiscal-status`, `--customer-id`, and shows
76
+ a PAYMENT column. A mirror (`source: stripe | manual`) is read-only except through `mirror`: `update`, `finalize` and `void`
77
+ throw `InvoiceError` `409 mirrored`.
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
+
58
96
  ### Deprecated names
59
97
 
60
98
  Until 0.3.0 the client and the service spoke camelCase. A caller that has not moved (billing-service, stripe-service, apps)
@@ -100,7 +138,11 @@ optional peer.
100
138
  | `invoice_list`, `invoice_get`, `invoice_transactions` | read | `invoice.read` |
101
139
  | `invoice_create`, `invoice_update` (drafts only) | write | `invoice.write` |
102
140
  | `invoice_finalize` (irreversible) | write | `invoice.finalize` |
141
+ | `invoice_numbering` | read | `invoice.read` |
142
+ | `invoice_configure_numbering` | write | `invoice.configure` |
103
143
  | `invoice_record_payment` | write | `invoice.record_payment` |
144
+
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.
104
146
  | `invoice_void` (irreversible) | write | `invoice.void` |
105
147
 
106
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
@@ -0,0 +1,162 @@
1
+ // src/events.ts
2
+ import { z } from "zod";
3
+ import { defineAggregate } from "@baseworks/foldbase";
4
+ var InvoiceStatus = z.enum(["draft", "finalized", "paid", "void"]);
5
+ var InvoiceEvents = defineAggregate("invoice", {
6
+ // Draft created (with its initial lines + computed totals). Numeric fields are
7
+ // initialised to 0 so their read-model columns are stable integers.
8
+ InvoiceDrafted: z.object({
9
+ customer_id: z.string().min(1),
10
+ customer_name: z.string(),
11
+ // snapshot at draft time; '' if unknown
12
+ currency: z.string().length(3),
13
+ lines: z.string(),
14
+ // JSON array of { description, quantity, unit_price_cents, amount_cents, product_id }
15
+ subtotal_cents: z.number().int(),
16
+ total_cents: z.number().int(),
17
+ short_id: z.string().min(1),
18
+ // 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
19
+ source: z.string().optional(),
20
+ metadata: z.string().optional(),
21
+ // JSON object, serialized
22
+ external_number: z.string().optional(),
23
+ // 1.2.0: a number given by another system ('' = none)
24
+ at: z.number().int()
25
+ }),
26
+ // Draft edited (customer / lines). Only valid while status = draft.
27
+ InvoiceUpdated: z.object({
28
+ customer_id: z.string().min(1),
29
+ customer_name: z.string(),
30
+ lines: z.string(),
31
+ subtotal_cents: z.number().int(),
32
+ total_cents: z.number().int(),
33
+ metadata: z.string().optional(),
34
+ // 1.1.0
35
+ external_number: z.string().optional(),
36
+ // 1.2.0
37
+ at: z.number().int()
38
+ }),
39
+ // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
40
+ InvoiceFinalized: z.object({
41
+ number: z.number().int(),
42
+ lines: z.string(),
43
+ subtotal_cents: z.number().int(),
44
+ total_cents: z.number().int(),
45
+ issued_at: z.number().int(),
46
+ due_at: z.number().int(),
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(),
53
+ at: z.number().int()
54
+ }),
55
+ // A payment applied to a finalized invoice. `amount_paid_cents` is the new running
56
+ // total; `status` is the resulting status ('paid' when balance ≤ 0, else
57
+ // 'finalized') — both computed by the store.
58
+ PaymentRecorded: z.object({
59
+ amount_cents: z.number().int(),
60
+ amount_paid_cents: z.number().int(),
61
+ status: InvoiceStatus,
62
+ method: z.string(),
63
+ reference: z.string(),
64
+ payment_id: z.string().optional(),
65
+ // 1.1.0: the pay record this settles; the idempotency key when present
66
+ at: z.number().int()
67
+ }),
68
+ InvoiceVoided: z.object({
69
+ reason: z.string(),
70
+ at: z.number().int()
71
+ }),
72
+ // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
73
+ // first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
74
+ InvoiceMirrored: z.object({
75
+ source: z.string(),
76
+ // 'stripe' | 'manual'
77
+ mirror_key: z.string().min(1),
78
+ // `${system}:${external_id}`
79
+ external_refs: z.string(),
80
+ // JSON array, serialized
81
+ customer_id: z.string().min(1),
82
+ customer_name: z.string(),
83
+ currency: z.string().length(3),
84
+ lines: z.string(),
85
+ subtotal_cents: z.number().int(),
86
+ tax_cents: z.number().int(),
87
+ total_cents: z.number().int(),
88
+ amount_paid_cents: z.number().int(),
89
+ // from the payment entries, not from the provider
90
+ status: InvoiceStatus,
91
+ issued_at: z.number().int(),
92
+ due_at: z.number().int(),
93
+ // 0 = none
94
+ paid_at: z.number().int(),
95
+ // 0 = none
96
+ voided_at: z.number().int(),
97
+ // 0 = none
98
+ provider_updated_at: z.number().int(),
99
+ metadata: z.string(),
100
+ short_id: z.string().min(1),
101
+ created_at: z.number().int(),
102
+ at: z.number().int()
103
+ }),
104
+ // 1.1.0. Where the invoice stands with a tax system. Only changed through `invoice.fiscal_update`.
105
+ InvoiceFiscalChanged: z.object({
106
+ status: z.string(),
107
+ // FISCAL_STATUSES
108
+ system: z.string(),
109
+ external_id: z.string(),
110
+ message: z.string(),
111
+ at: z.number().int()
112
+ })
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
+ });
133
+ var FISCAL_STATUSES = ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
134
+ var INVOICE_SOURCES = ["local", "stripe", "manual"];
135
+ var TransactionKind = z.enum(["payment", "refund", "adjustment"]);
136
+ var TransactionEvents = defineAggregate("transaction", {
137
+ TransactionRecorded: z.object({
138
+ invoice_id: z.string().min(1),
139
+ invoice_number: z.number().int(),
140
+ // the invoice's number at the time
141
+ customer_id: z.string(),
142
+ customer_name: z.string(),
143
+ kind: TransactionKind,
144
+ amount_cents: z.number().int(),
145
+ currency: z.string().length(3),
146
+ method: z.string(),
147
+ reference: z.string(),
148
+ payment_id: z.string().optional(),
149
+ // 1.1.0
150
+ at: z.number().int()
151
+ })
152
+ });
153
+
154
+ export {
155
+ InvoiceStatus,
156
+ InvoiceEvents,
157
+ NumberingEvents,
158
+ FISCAL_STATUSES,
159
+ INVOICE_SOURCES,
160
+ TransactionKind,
161
+ TransactionEvents
162
+ };
package/dist/cli.js CHANGED
@@ -22,45 +22,64 @@ 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";
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)");
26
27
  function buildInvoiceCommand(deps) {
27
28
  const { http } = deps;
28
29
  const cli = deps.cliName ?? "cli";
29
30
  const listInvoices = async (opts) => {
30
- const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : "";
31
+ const params = new URLSearchParams();
32
+ if (opts.status) params.set("status", opts.status);
33
+ if (opts.paymentStatus) params.set("payment_status", opts.paymentStatus);
34
+ if (opts.overdue) params.set("overdue", "true");
35
+ if (opts.source) params.set("source", opts.source);
36
+ if (opts.fiscalStatus) params.set("fiscal_status", opts.fiscalStatus);
37
+ if (opts.customerId) params.set("customer_id", opts.customerId);
38
+ if (opts.externalNumber) params.set("external_number", opts.externalNumber);
39
+ const q = params.toString() ? `?${params}` : "";
31
40
  const res = await http.get(`/invoices${q}`).catch(die);
32
41
  printOutput(res.invoices, opts.output, (wide) => {
33
42
  table(res.invoices, [
34
43
  { key: "short_id", label: "ID" },
35
- { key: "number", label: "NO", fmt: NUMBER_COL },
44
+ { key: "number_text", label: "NO", fmt: NUMBER_COL },
36
45
  { key: "status", label: "STATUS" },
46
+ { key: "payment_status", label: "PAYMENT", fmt: (v) => v ?? "" },
37
47
  { key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
38
48
  { key: "total_cents", label: "TOTAL", fmt: (v, r) => fmtMoney(v, r.currency) },
39
49
  { key: "balance_cents", label: "BALANCE", fmt: (v, r) => fmtMoney(v, r.currency) },
50
+ { key: "source", label: "SOURCE", wide: true, fmt: (v) => v ?? "local" },
40
51
  { key: "created_at", label: "CREATED", wide: true, fmt: (v) => fmtDate(v) },
41
52
  { key: "id", label: "FULL ID", wide: true }
42
53
  ], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` });
43
54
  summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? "s" : ""}`);
44
55
  }, "id");
45
56
  };
46
- const cmd = new Command("invoices").aliases(["inv", "invoice"]).description("Manage invoices (org-scoped \u2014 run `use <org>` first)").option(...outputOption()).option("--status <status>", "Filter: draft | finalized | paid | void").action(listInvoices);
57
+ const cmd = new Command("invoices").aliases(["inv", "invoice"]).description("Manage invoices (org-scoped \u2014 run `use <org>` first)").option(...outputOption());
58
+ filterOptions(cmd).action(listInvoices);
47
59
  cmd.addCommand(
48
- new Command("ls").description("List invoices (alias of the bare command)").option(...outputOption()).option("--status <status>", "Filter by status").action(function() {
60
+ filterOptions(new Command("ls").description("List invoices (alias of the bare command)").option(...outputOption())).action(function() {
49
61
  const self = this.opts();
50
62
  const parent = this.parent?.opts() ?? {};
51
63
  return listInvoices({
52
64
  output: self.output && self.output !== "table" ? self.output : parent.output ?? "table",
53
- status: self.status ?? parent.status
65
+ ...self.status ?? parent.status ? { status: self.status ?? parent.status } : {},
66
+ ...self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: self.paymentStatus ?? parent.paymentStatus } : {},
67
+ ...self.overdue ?? parent.overdue ? { overdue: true } : {},
68
+ ...self.source ?? parent.source ? { source: self.source ?? parent.source } : {},
69
+ ...self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: self.fiscalStatus ?? parent.fiscalStatus } : {},
70
+ ...self.customerId ?? parent.customerId ? { customerId: self.customerId ?? parent.customerId } : {},
71
+ ...self.externalNumber ?? parent.externalNumber ? { externalNumber: self.externalNumber ?? parent.externalNumber } : {}
54
72
  });
55
73
  })
56
74
  );
57
75
  cmd.addCommand(
58
- 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) => {
59
77
  const lines = opts.line.map(parseLine);
60
78
  const res = await http.post("/invoices", {
61
79
  customer_id: opts.customer,
62
80
  currency: opts.currency,
63
- lines
81
+ lines,
82
+ ...opts.number ? { external_number: opts.number } : {}
64
83
  }).catch(die);
65
84
  success(`Draft invoice created for ${res.invoice.customer_name ?? res.invoice.customer_id}`);
66
85
  kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)]]);
@@ -74,7 +93,8 @@ function buildInvoiceCommand(deps) {
74
93
  printOutput(inv, opts.output, () => {
75
94
  kv([
76
95
  ["id", String(inv["short_id"])],
77
- ["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"])]] : [],
78
98
  ["status", String(inv["status"])],
79
99
  ["customer", String(inv["customer_name"] ?? inv["customer_id"])],
80
100
  ["issued", inv["issued_at"] ? fmtDate(inv["issued_at"]) : "\u2014"],
@@ -112,16 +132,17 @@ function buildInvoiceCommand(deps) {
112
132
  })
113
133
  );
114
134
  cmd.addCommand(
115
- 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) => {
116
136
  const body = {};
137
+ if (opts.number) body["external_number"] = opts.number;
117
138
  if (opts.due) {
118
139
  const ms = Date.parse(opts.due);
119
140
  if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`);
120
141
  body["due_at"] = ms;
121
142
  }
122
143
  const res = await http.post(`/invoices/${ref}/finalize`, body).catch(die);
123
- success(`Invoice finalized: #${res.invoice.number}`);
124
- 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)]]);
125
146
  })
126
147
  );
127
148
  cmd.addCommand(
@@ -141,6 +162,30 @@ function buildInvoiceCommand(deps) {
141
162
  success(`Invoice voided: ${res.invoice.short_id}`);
142
163
  })
143
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
+ );
144
189
  cmd.addCommand(
145
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) => {
146
191
  const path = ref ? `/invoices/${ref}/payments` : "/transactions";
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { InvoiceStatus } from './events.js';
1
+ import { FiscalStatus, InvoiceStatus, InvoiceSource } from './events.js';
2
2
  import '@baseworks/foldbase';
3
3
  import 'zod';
4
4
 
@@ -18,6 +18,22 @@ interface InvoiceRow {
18
18
  due_at: number;
19
19
  created_at: number;
20
20
  updated_at: number;
21
+ source: string | null;
22
+ mirror_key: string | null;
23
+ external_refs: string | null;
24
+ metadata: string | null;
25
+ tax_cents: number | null;
26
+ paid_at: number | null;
27
+ voided_at: number | null;
28
+ provider_updated_at: number | null;
29
+ fiscal_status: string | null;
30
+ fiscal_system: string | null;
31
+ fiscal_external_id: string | null;
32
+ fiscal_message: string | null;
33
+ fiscal_updated_at: number | null;
34
+ number_text: string | null;
35
+ series_key: string | null;
36
+ external_number: string | null;
21
37
  }
22
38
  interface InvoiceLineDto {
23
39
  description: string;
@@ -39,6 +55,35 @@ interface InvoiceLineDeprecated {
39
55
  productId: string | null;
40
56
  }
41
57
  type InvoiceLine = InvoiceLineDto & InvoiceLineDeprecated;
58
+ /** A reference to the same document in another system. At most 10 per invoice. */
59
+ interface ExternalRef {
60
+ system: string;
61
+ id: string;
62
+ number?: string;
63
+ url?: string;
64
+ pdf_url?: string;
65
+ account_id?: string;
66
+ livemode?: boolean;
67
+ }
68
+ type Metadata = Record<string, string | number | boolean | null>;
69
+ /** `unpaid`, `partially_paid`, `paid`; `not_due` for a draft and a void invoice. Derived, never stored. */
70
+ type PaymentStatus = 'unpaid' | 'partially_paid' | 'paid' | 'not_due';
71
+ interface Fiscal {
72
+ status: FiscalStatus;
73
+ system: string | null;
74
+ external_id: string | null;
75
+ message: string | null;
76
+ updated_at: number;
77
+ }
78
+ /** One payment on an invoice, as `GET /invoices/:ref` lists them. */
79
+ interface InvoicePayment {
80
+ payment_id: string;
81
+ amount_cents: number;
82
+ currency: string;
83
+ method: string | null;
84
+ reference: string | null;
85
+ paid_at: number;
86
+ }
42
87
  interface InvoiceDto {
43
88
  id: string;
44
89
  short_id: string;
@@ -58,6 +103,22 @@ interface InvoiceDto {
58
103
  due_at: number | null;
59
104
  created_at: number;
60
105
  updated_at: number;
106
+ /** `local` (made here), `stripe`, `manual` (entered from a document issued elsewhere). Old invoices are `local`. */
107
+ source: InvoiceSource;
108
+ external_refs: ExternalRef[];
109
+ metadata: Metadata;
110
+ tax_cents: number;
111
+ payment_status: PaymentStatus;
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;
120
+ /** Only `GET /invoices/:ref` includes the payments. */
121
+ payments?: InvoicePayment[];
61
122
  }
62
123
  interface InvoiceDeprecated {
63
124
  /** @deprecated Read `short_id`. */
@@ -103,12 +164,19 @@ interface CreateInvoiceInput {
103
164
  customer_id?: string;
104
165
  currency: string;
105
166
  lines: InvoiceLineInput[];
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;
106
170
  /** @deprecated Send `customer_id`. */
107
171
  customerId?: string;
108
172
  }
109
173
  interface UpdateInvoiceInput {
110
174
  customer_id?: string;
111
175
  lines?: InvoiceLineInput[];
176
+ /** Replaces the invoice's metadata. */
177
+ metadata?: Metadata;
178
+ /** Sets (or, with null, clears) the external number of a draft. */
179
+ external_number?: string | null;
112
180
  /** @deprecated Send `customer_id`. */
113
181
  customerId?: string;
114
182
  }
@@ -117,6 +185,8 @@ interface FinalizeInvoiceInput {
117
185
  issued_at?: number;
118
186
  /** Epoch millis; 0/omitted = no due date. */
119
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;
120
190
  /** @deprecated Send `issued_at`. */
121
191
  issuedAt?: number;
122
192
  /** @deprecated Send `due_at`. */
@@ -126,9 +196,88 @@ interface RecordPaymentInput {
126
196
  amount_cents?: number;
127
197
  method?: string;
128
198
  reference?: string;
199
+ /** The pay record this settles. Idempotency key: the same id twice changes nothing. */
200
+ payment_id?: string;
129
201
  /** @deprecated Send `amount_cents`. */
130
202
  amountCents?: number;
131
203
  }
204
+ interface ListInvoicesOptions {
205
+ limit?: number;
206
+ offset?: number;
207
+ status?: string;
208
+ /** One or several (an array is sent comma-separated). */
209
+ payment_status?: PaymentStatus | PaymentStatus[];
210
+ /** Unpaid or partially paid, with a due date in the past. */
211
+ overdue?: boolean;
212
+ source?: InvoiceSource;
213
+ fiscal_status?: FiscalStatus;
214
+ customer_id?: string;
215
+ /** Exact. */
216
+ external_number?: string;
217
+ }
218
+ /** The provider's whole document, for `PUT /invoices/mirror`. */
219
+ interface MirrorInvoiceInput {
220
+ source: 'stripe' | 'manual';
221
+ external_ref: ExternalRef;
222
+ customer_id: string;
223
+ currency: string;
224
+ lines: Array<{
225
+ description: string;
226
+ quantity: number;
227
+ unit_price_cents: number;
228
+ amount_cents: number;
229
+ product_id?: string;
230
+ }>;
231
+ subtotal_cents: number;
232
+ tax_cents: number;
233
+ total_cents: number;
234
+ status: 'finalized' | 'paid' | 'void';
235
+ issued_at: number;
236
+ due_at?: number;
237
+ paid_at?: number;
238
+ voided_at?: number;
239
+ /** The provider's own "updated" time: an upsert older than what is stored is ignored. */
240
+ provider_updated_at: number;
241
+ metadata?: Metadata;
242
+ }
243
+ interface MirrorResult {
244
+ invoice: Invoice;
245
+ /** True when this call created the invoice. */
246
+ created: boolean;
247
+ /** True when the document was older than the one stored and was ignored. */
248
+ stale?: boolean;
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
+ }
275
+ interface FiscalInput {
276
+ status: FiscalStatus;
277
+ system?: string;
278
+ external_id?: string;
279
+ message?: string;
280
+ }
132
281
  interface TransactionRow {
133
282
  id: string;
134
283
  invoice_id: string;
@@ -140,6 +289,7 @@ interface TransactionRow {
140
289
  currency: string;
141
290
  method: string;
142
291
  reference: string;
292
+ payment_id: string | null;
143
293
  created_at: number;
144
294
  updated_at: number;
145
295
  }
@@ -154,6 +304,7 @@ interface TransactionDto {
154
304
  currency: string;
155
305
  method: string | null;
156
306
  reference: string | null;
307
+ payment_id: string | null;
157
308
  created_at: number;
158
309
  }
159
310
  interface TransactionDeprecated {
@@ -220,14 +371,23 @@ declare class InvoiceClient {
220
371
  api<T>(method: string, path: string, body?: unknown, extra?: Record<string, string>): Promise<T>;
221
372
  /** Generic ApiClient (get/post/patch/del) — used by the CLI plugin. */
222
373
  get http(): HttpClient;
223
- list(opts?: {
224
- limit?: number;
225
- offset?: number;
226
- status?: string;
227
- }): Promise<Invoice[]>;
374
+ list(opts?: ListInvoicesOptions): Promise<Invoice[]>;
228
375
  get(ref: string): Promise<Invoice>;
229
376
  create(input: CreateInvoiceInput): Promise<Invoice>;
230
377
  update(ref: string, input: UpdateInvoiceInput): Promise<Invoice>;
378
+ /**
379
+ * Keep the provider's document (Stripe's invoice, a hand-entered one) as this invoice: creates it or replaces it by
380
+ * `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
381
+ */
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>;
389
+ /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
390
+ setFiscal(ref: string, input: FiscalInput): Promise<Invoice>;
231
391
  finalize(ref: string, input?: FinalizeInvoiceInput): Promise<Invoice>;
232
392
  recordPayment(ref: string, input: RecordPaymentInput): Promise<Invoice>;
233
393
  void(ref: string, reason?: string): Promise<Invoice>;
@@ -242,4 +402,4 @@ declare class InvoiceClient {
242
402
  /** Factory used by the SDK capability registry. */
243
403
  declare function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient;
244
404
 
245
- export { type CreateInvoiceInput, type FinalizeInvoiceInput, type HttpClient, type Invoice, InvoiceClient, type InvoiceClientOptions, type InvoiceDeprecated, type InvoiceDto, InvoiceError, type InvoiceLine, type InvoiceLineDeprecated, type InvoiceLineDto, type InvoiceLineInput, type InvoiceRow, InvoiceStatus, 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
@@ -119,6 +119,12 @@ var InvoiceClient = class _InvoiceClient {
119
119
  if (opts.limit !== void 0) q.set("limit", String(opts.limit));
120
120
  if (opts.offset !== void 0) q.set("offset", String(opts.offset));
121
121
  if (opts.status) q.set("status", opts.status);
122
+ if (opts.payment_status) q.set("payment_status", [opts.payment_status].flat().join(","));
123
+ if (opts.overdue !== void 0) q.set("overdue", String(opts.overdue));
124
+ if (opts.source) q.set("source", opts.source);
125
+ if (opts.fiscal_status) q.set("fiscal_status", opts.fiscal_status);
126
+ if (opts.customer_id) q.set("customer_id", opts.customer_id);
127
+ if (opts.external_number) q.set("external_number", opts.external_number);
122
128
  const qs = q.toString();
123
129
  const { invoices } = await this.api("GET", `/invoices${qs ? `?${qs}` : ""}`);
124
130
  return invoices.map(oldNamesOnInvoice);
@@ -135,6 +141,31 @@ var InvoiceClient = class _InvoiceClient {
135
141
  const { invoice } = await this.api("PATCH", `/invoices/${ref}`, newNamesOnLines(input));
136
142
  return oldNamesOnInvoice(invoice);
137
143
  }
144
+ /**
145
+ * Keep the provider's document (Stripe's invoice, a hand-entered one) as this invoice: creates it or replaces it by
146
+ * `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
147
+ */
148
+ async mirror(input) {
149
+ const r = await this.api("PUT", "/invoices/mirror", input);
150
+ return { ...r, invoice: oldNamesOnInvoice(r.invoice) };
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
+ }
164
+ /** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
165
+ async setFiscal(ref, input) {
166
+ const { invoice } = await this.api("PUT", `/invoices/${ref}/fiscal`, input);
167
+ return oldNamesOnInvoice(invoice);
168
+ }
138
169
  async finalize(ref, input = {}) {
139
170
  const { invoice } = await this.api("POST", `/invoices/${ref}/finalize`, newNamesOnFinalize(input));
140
171
  return oldNamesOnInvoice(invoice);