@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/README.md CHANGED
@@ -37,7 +37,7 @@ const draft = await invoices.create({
37
37
  })
38
38
 
39
39
  // 2. finalize — assigns a per-org number, freezes lines + totals
40
- const final = await invoices.finalize(draft.id, { due_at: Date.parse('2026-08-01') })
40
+ const final = await invoices.finalize(draft.id, { document_date: '2026-07-01', due_date: '2026-08-01' }) // days; document_date defaults to today (UTC)
41
41
 
42
42
  // 3. record payments — balance can't go below zero (overpayment is rejected)
43
43
  await invoices.recordPayment(final.id, { amount_cents: 100000, method: 'bank', reference: 'TXN-1' })
@@ -66,7 +66,7 @@ const inv = await invoices.get(id) // inv.payment_status, inv.source, inv.exte
66
66
 
67
67
  // a provider's document, whole: creates or replaces by external_ref (system + id); `created`, `stale`
68
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 })
69
+ customer_id, currency, lines, subtotal_cents, tax_cents, total_cents, status: 'finalized', document_date, provider_updated_at })
70
70
 
71
71
  await invoices.recordPayment(id, { amount_cents: 990, payment_id: 'pay_…' }) // the same payment_id twice records it once
72
72
  await invoices.setFiscal(id, { status: 'submitted', system: 'gib', external_id }) // needs invoice.fiscal_update
@@ -76,33 +76,43 @@ 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
79
+ ## Upgrading to 2.0
80
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()
81
+ The full list of renamed fields and changed rules is in the [service README](../../README.md#upgrading-to-20). For a caller:
86
82
 
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
- ```
83
+ - Read `document_date`, `due_date`, `paid_date`, `void_date` (`YYYY-MM-DD` strings, typed `DocumentDate` from
84
+ `@baseworks/core`); `issued_at`, `due_at`, `issuedAt`, `dueAt` and `payments[].paid_at` are gone from answers.
85
+ - Send days. `issued_at` / `due_at` (finalize) and `issued_at` / `due_at` / `paid_at` / `voided_at` (mirror) are still
86
+ accepted for this release, never together with the new names; `time_zone` is accepted and ignored.
87
+ - `number` is now set on every local invoice, also with an external number: print `display_number`.
88
+ - A payment or void dated before the invoice, or a `due_date` before `document_date`, is `400`; a finalize or set that lost its claim while waiting is `409 claim_lost` (retry).
89
+ - `finalize` can refuse with `409 date_before_series`; an external number can be changed, cleared, and is unique even
90
+ against void invoices.
91
+ - Needs **invoice-service 2.0** and `@baseworks/core` ^0.6.0.
92
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.
93
+ ```ts
94
+ await invoices.finalize(id, { document_date: '2026-07-01', due_date: '2026-08-01', external_number: 'GIB2026000000001' })
95
+ await invoices.recordPayment(id, { amount_cents: 990, document_date: '2026-07-10' })
96
+ await invoices.void(id, 'issued in error', { void_date: '2026-07-11' })
97
+ await invoices.list({ from: '2026-07-01', to: '2026-07-31' }) // by document_date; newest first
98
+ await invoices.transactions({ from: '2026-07-01' })
95
99
 
96
- ### 1.2.1: the number of an invoice already issued
100
+ await invoices.setExternalNumber(id, 'GIB2026000000002') // set or change; needs invoice.fiscal_update
101
+ await invoices.clearExternalNumber(id) // frees it
102
+ await invoices.setExternalNumber(id, 'GIB2026000000002', { from_invoice_id: voidId }) // MOVE it from a void invoice, in one operation
97
103
 
98
- ```ts
99
- // once, on a finalized or paid invoice (the e-Arşiv / GİB portal's number); needs invoice.fiscal_update
100
- await invoices.setExternalNumber(id, 'GIB2026000000001')
104
+ await invoices.getNumbering() // null (plain 1, 2, 3) or { prefix, digits, yearly, next, next_text, updated_at }
105
+ await invoices.setNumbering({ prefix: 'BSF', digits: 9, yearly: true, next: 148 }) // needs invoice.configure; never renumbers
106
+ // `year: 2025` says which year's counter `next` applies to (yearly only; default the current year, UTC)
107
+ await invoices.clearNumbering()
108
+ // invoice.number / number_text (internal), invoice.external_number, invoice.display_number
101
109
  ```
102
110
 
103
- CLI: `invoices set-external-number <ref> <number>`. A draft is `409 use_update`, a void invoice `409 void`, a Stripe mirror
104
- `409 mirrored`, another number `409 external_number_set`; the same one changes nothing. A wrong number is not corrected:
105
- void and re-issue. Needs **invoice-service 1.2.1**.
111
+ CLI: `invoices --from <date> --to <date>`; `invoices finalize <ref> --date <date> --due <date> --number <external>`;
112
+ `invoices pay <ref> --amount 9.90 --date <date>`; `invoices void <ref> --date <date>`; `invoices payments [<ref>] --from <date>`;
113
+ `invoices set-external-number <ref> <number> [--from-invoice <void invoice>]`; `invoices clear-external-number <ref>`;
114
+ `invoices numbering set --prefix BSF --digits 9 --yearly --next 148 [--year 2025]`, `invoices numbering clear`. The NO column shows
115
+ `display_number`, DATE the `document_date`.
106
116
 
107
117
  ### Deprecated names
108
118
 
@@ -112,10 +122,10 @@ still builds and runs: **every old name is kept as a deprecated alias** and goes
112
122
  | | Old | Now |
113
123
  |---|---|---|
114
124
  | options | `baseUrl`, `orgId` | `base_url`, `org_id` |
115
- | invoice | `shortId`, `customerId`, `customerName`, `subtotalCents`, `totalCents`, `amountPaidCents`, `balanceCents`, `issuedAt`, `dueAt`, `createdAt`, `updatedAt` | `short_id`, `customer_id`, `customer_name`, `subtotal_cents`, `total_cents`, `amount_paid_cents`, `balance_cents`, `issued_at`, `due_at`, `created_at`, `updated_at` |
125
+ | invoice | `shortId`, `customerId`, `customerName`, `subtotalCents`, `totalCents`, `amountPaidCents`, `balanceCents`, `createdAt`, `updatedAt` | `short_id`, `customer_id`, `customer_name`, `subtotal_cents`, `total_cents`, `amount_paid_cents`, `balance_cents`, `created_at`, `updated_at` |
116
126
  | line | `unitPriceCents`, `amountCents`, `productId` | `unit_price_cents`, `amount_cents`, `product_id` |
117
127
  | transaction | `invoiceId`, `invoiceNumber`, `customerId`, `customerName`, `amountCents`, `createdAt` | `invoice_id`, `invoice_number`, `customer_id`, `customer_name`, `amount_cents`, `created_at` |
118
- | inputs | `customerId`, `unitPriceCents`, `productId`, `issuedAt`, `dueAt`, `amountCents` | `customer_id`, `unit_price_cents`, `product_id`, `issued_at`, `due_at`, `amount_cents` |
128
+ | inputs | `customerId`, `unitPriceCents`, `productId`, `issuedAt`, `dueAt`, `amountCents` | `customer_id`, `unit_price_cents`, `product_id`, `issued_at`, `due_at` (themselves deprecated, see 2.0), `amount_cents` |
119
129
 
120
130
  On **answers** the old names are readable properties (`invoice.totalCents`) but not data: they are non-enumerable getters of
121
131
  the snake_case field, so `JSON.stringify`, spreading and `toEqual` see the snake_case object only. On **inputs** the old names
@@ -132,7 +142,7 @@ import { buildInvoiceCommand } from '@baseworks/invoice/cli'
132
142
 
133
143
  program.addCommand(buildInvoiceCommand({ http, cliName: 'dtab' }))
134
144
  // the CLI reads and sends the service's snake_case, so it needs invoice-service 0.3.0
135
- // dtab invoices | inv list (--status) · create · get · update · finalize · pay · void
145
+ // dtab invoices | inv list (--status, --from, --to) · create · get · update · finalize · pay · void · set/clear-external-number
136
146
  // dtab invoices create --customer <ref> --currency USD --line "Consulting|10|150.00"
137
147
  // dtab invoices pay <ref> --amount 150.00 --method bank
138
148
  // dtab invoices payments [<ref>] (the transaction ledger)
@@ -149,13 +159,15 @@ optional peer.
149
159
  | `invoice_list`, `invoice_get`, `invoice_transactions` | read | `invoice.read` |
150
160
  | `invoice_create`, `invoice_update` (drafts only) | write | `invoice.write` |
151
161
  | `invoice_finalize` (irreversible) | write | `invoice.finalize` |
152
- | `invoice_set_external_number` (one-time) | write | `invoice.fiscal_update` |
162
+ | `invoice_set_external_number` (set or change), `invoice_clear_external_number` | write | `invoice.fiscal_update` |
153
163
  | `invoice_numbering` | read | `invoice.read` |
154
164
  | `invoice_configure_numbering` | write | `invoice.configure` |
155
165
  | `invoice_record_payment` | write | `invoice.record_payment` |
156
166
  | `invoice_void` (irreversible) | write | `invoice.void` |
157
167
 
158
- `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. `invoice_set_external_number` takes the fiscal permission, as that is fiscal identity.
168
+ The list tools are paged: `limit` (default 100, max 500) and `cursor` in, `next` out (null when there is nothing more). `offset` is still accepted for one release (not together with `cursor`).
169
+
170
+ `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` and `document_date`; `invoice_void` takes `void_date`; `invoice_list` and `invoice_transactions` take `from` / `to`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension. The external-number tools take the fiscal permission, as that is fiscal identity.
159
171
 
160
172
  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
161
173
  the service registered with org-service, used to hide a tool from somebody who may not use it. Money is integer cents; a
@@ -34,6 +34,8 @@ var InvoiceEvents = defineAggregate("invoice", {
34
34
  // 1.1.0
35
35
  external_number: z.string().optional(),
36
36
  // 1.2.0
37
+ previous_external_number: z.string().optional(),
38
+ // 2.0: present when this update changed it ('' = none before)
37
39
  at: z.number().int()
38
40
  }),
39
41
  // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
@@ -42,11 +44,17 @@ var InvoiceEvents = defineAggregate("invoice", {
42
44
  lines: z.string(),
43
45
  subtotal_cents: z.number().int(),
44
46
  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.
47
+ document_date: z.string().optional(),
48
+ // 2.0: the invoice date, `YYYY-MM-DD`
49
+ due_date: z.string().optional(),
50
+ // 2.0: absent = no due date
51
+ issued_at: z.number().int().optional(),
52
+ // before 2.0, epoch millis
53
+ due_at: z.number().int().optional(),
54
+ // before 2.0; 0 = no due date
55
+ // 1.2.0. `number` is the counter of the series; `number_text` is it as printed (`BSF2026000000148`, `7`); `series_key`
56
+ // says which counter `number` belongs to. Between 1.2.0 and 2.0 an invoice given an external number at finalize took
57
+ // none: `number` 0 and `number_text` the external number. Those stay as they are.
50
58
  number_text: z.string().optional(),
51
59
  series_key: z.string().optional(),
52
60
  external_number: z.string().optional(),
@@ -63,16 +71,33 @@ var InvoiceEvents = defineAggregate("invoice", {
63
71
  reference: z.string(),
64
72
  payment_id: z.string().optional(),
65
73
  // 1.1.0: the pay record this settles; the idempotency key when present
74
+ document_date: z.string().optional(),
75
+ // 2.0: the day of the payment
76
+ paid_date: z.string().optional(),
77
+ // 2.0: present when `status` is `paid`: the day of the payment that settled it
66
78
  at: z.number().int()
67
79
  }),
68
80
  InvoiceVoided: z.object({
69
81
  reason: z.string(),
82
+ void_date: z.string().optional(),
83
+ // 2.0; before it, the day of `at`
70
84
  at: z.number().int()
71
85
  }),
72
- // 1.2.1. The number another system gave an invoice that was already issued (the e-Arşiv / GİB portal's), set once.
73
- // `number`, `number_text` and the series are not touched.
86
+ // 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
87
+ // can be changed. `number`, `number_text` and the series are not touched.
74
88
  InvoiceExternalNumberSet: z.object({
75
89
  external_number: z.string().min(1),
90
+ previous: z.string().optional(),
91
+ // 2.0: what it was ('' = none)
92
+ moved_from: z.string().optional(),
93
+ // 2.0: the void invoice it was taken from, in the same operation
94
+ at: z.number().int()
95
+ }),
96
+ // 2.0. The external number taken off an issued invoice (a number is moved by clearing it first).
97
+ InvoiceExternalNumberCleared: z.object({
98
+ previous: z.string().min(1),
99
+ moved_to: z.string().optional(),
100
+ // 2.0: the invoice it was moved to, in the same operation
76
101
  at: z.number().int()
77
102
  }),
78
103
  // 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
@@ -94,13 +119,16 @@ var InvoiceEvents = defineAggregate("invoice", {
94
119
  amount_paid_cents: z.number().int(),
95
120
  // from the payment entries, not from the provider
96
121
  status: InvoiceStatus,
97
- issued_at: z.number().int(),
98
- due_at: z.number().int(),
99
- // 0 = none
100
- paid_at: z.number().int(),
101
- // 0 = none
102
- voided_at: z.number().int(),
103
- // 0 = none
122
+ document_date: z.string().optional(),
123
+ // 2.0; the four days are absent when there is none
124
+ due_date: z.string().optional(),
125
+ paid_date: z.string().optional(),
126
+ void_date: z.string().optional(),
127
+ issued_at: z.number().int().optional(),
128
+ // the four before 2.0, epoch millis, 0 = none
129
+ due_at: z.number().int().optional(),
130
+ paid_at: z.number().int().optional(),
131
+ voided_at: z.number().int().optional(),
104
132
  provider_updated_at: z.number().int(),
105
133
  metadata: z.string(),
106
134
  short_id: z.string().min(1),
@@ -128,15 +156,23 @@ var NumberingEvents = defineAggregate("numbering", {
128
156
  next_key: z.string(),
129
157
  // the series key `next` applies to (prefix + year when yearly)
130
158
  time_zone: z.string().optional(),
131
- // IANA name; absent = UTC. The year in the number and the yearly reset follow it
159
+ // before 2.0; read by nothing now: the year is the `document_date`'s
132
160
  at: z.number().int()
133
161
  }),
134
162
  NumberingCleared: z.object({ at: z.number().int() }),
135
- NumberClaimed: z.object({ invoice_id: z.string().min(1), series_key: z.string(), number: z.number().int(), at: z.number().int() }),
163
+ 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() }),
136
164
  NumberReleased: z.object({ invoice_id: z.string().min(1), at: z.number().int() }),
137
165
  // `invoice_version` (1.2.1): the version of the invoice's stream the claiming write emits at. While the stream is still
138
166
  // there, that write is in flight. Absent from claims written before.
139
- 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() })
167
+ 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() }),
168
+ // 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
169
+ // and another writer took the claim over, the stream has moved and this append is refused, so the write does not happen.
170
+ // It also starts the lease again. Read like the claim it confirms.
171
+ 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() }),
172
+ 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() }),
173
+ // 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.
174
+ // A finalize or a set that failed gives its external number back at once.
175
+ ExternalNumberReleased: z.object({ external_number: z.string().min(1), invoice_id: z.string().min(1), at: z.number().int() })
140
176
  });
141
177
  var FISCAL_STATUSES = ["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"];
142
178
  var INVOICE_SOURCES = ["local", "stripe", "manual"];
@@ -155,6 +191,8 @@ var TransactionEvents = defineAggregate("transaction", {
155
191
  reference: z.string(),
156
192
  payment_id: z.string().optional(),
157
193
  // 1.1.0
194
+ document_date: z.string().optional(),
195
+ // 2.0: the day of the payment; before it, the day of `at`
158
196
  at: z.number().int()
159
197
  })
160
198
  });
package/dist/cli.d.ts CHANGED
@@ -10,8 +10,9 @@ import { ApiClient } from '@baseworks/cli/client';
10
10
  *
11
11
  * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
12
12
  * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
13
- * `invoices finalize <ref>` · `invoices set-external-number <ref> <number>` ·
14
- * `invoices pay <ref> --amount 150.00` · `invoices void <ref>`
13
+ * `invoices finalize <ref> [--date YYYY-MM-DD]` · `invoices set-external-number <ref> <number>` ·
14
+ * `invoices clear-external-number <ref>` · `invoices pay <ref> --amount 150.00` · `invoices void <ref>` ·
15
+ * `invoices ls --from 2027-01-01 --to 2027-01-31`
15
16
  */
16
17
  interface InvoiceCliDeps {
17
18
  http: ApiClient;
package/dist/cli.js CHANGED
@@ -23,12 +23,14 @@ function parseLine(spec) {
23
23
  return { description, quantity, unit_price_cents: toCents(parts[2].trim(), "--line unitPrice") };
24
24
  }
25
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
+ var filterOptions = (c) => c.option("--status <status>", "Filter: draft | finalized | paid | void").option("--from <date>", "Invoice date on or after, YYYY-MM-DD").option("--to <date>", "Invoice date on or before, YYYY-MM-DD").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";
30
30
  const listInvoices = async (opts) => {
31
31
  const params = new URLSearchParams();
32
+ if (opts.from) params.set("from", opts.from);
33
+ if (opts.to) params.set("to", opts.to);
32
34
  if (opts.status) params.set("status", opts.status);
33
35
  if (opts.paymentStatus) params.set("payment_status", opts.paymentStatus);
34
36
  if (opts.overdue) params.set("overdue", "true");
@@ -41,7 +43,8 @@ function buildInvoiceCommand(deps) {
41
43
  printOutput(res.invoices, opts.output, (wide) => {
42
44
  table(res.invoices, [
43
45
  { key: "short_id", label: "ID" },
44
- { key: "number_text", label: "NO", fmt: NUMBER_COL },
46
+ { key: "display_number", label: "NO", fmt: NUMBER_COL },
47
+ { key: "document_date", label: "DATE", fmt: (v) => v ?? "\u2014" },
45
48
  { key: "status", label: "STATUS" },
46
49
  { key: "payment_status", label: "PAYMENT", fmt: (v) => v ?? "" },
47
50
  { key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
@@ -62,6 +65,8 @@ function buildInvoiceCommand(deps) {
62
65
  const parent = this.parent?.opts() ?? {};
63
66
  return listInvoices({
64
67
  output: self.output && self.output !== "table" ? self.output : parent.output ?? "table",
68
+ ...self.from ?? parent.from ? { from: self.from ?? parent.from } : {},
69
+ ...self.to ?? parent.to ? { to: self.to ?? parent.to } : {},
65
70
  ...self.status ?? parent.status ? { status: self.status ?? parent.status } : {},
66
71
  ...self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: self.paymentStatus ?? parent.paymentStatus } : {},
67
72
  ...self.overdue ?? parent.overdue ? { overdue: true } : {},
@@ -73,7 +78,7 @@ function buildInvoiceCommand(deps) {
73
78
  })
74
79
  );
75
80
  cmd.addCommand(
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) => {
81
+ 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), kept beside the internal number it gets at finalize").action(async (opts) => {
77
82
  const lines = opts.line.map(parseLine);
78
83
  const res = await http.post("/invoices", {
79
84
  customer_id: opts.customer,
@@ -93,12 +98,15 @@ function buildInvoiceCommand(deps) {
93
98
  printOutput(inv, opts.output, () => {
94
99
  kv([
95
100
  ["id", String(inv["short_id"])],
96
- ["number", inv["number_text"] ? NUMBER_COL(inv["number_text"]) : "\u2014 (draft)"],
101
+ ["number", inv["number_text"] ? NUMBER_COL(inv["number_text"]) : "\u2014"],
97
102
  ...inv["external_number"] ? [["external_number", String(inv["external_number"])]] : [],
98
103
  ["status", String(inv["status"])],
99
104
  ["customer", String(inv["customer_name"] ?? inv["customer_id"])],
100
- ["issued", inv["issued_at"] ? fmtDate(inv["issued_at"]) : "\u2014"],
101
- ["due", inv["due_at"] ? fmtDate(inv["due_at"]) : "\u2014"]
105
+ ["date", String(inv["document_date"] ?? "\u2014")],
106
+ ["due", String(inv["due_date"] ?? "\u2014")],
107
+ ...inv["paid_date"] ? [["paid on", String(inv["paid_date"])]] : [],
108
+ ...inv["void_date"] ? [["voided on", String(inv["void_date"])]] : [],
109
+ ...inv["void_reason"] ? [["void reason", String(inv["void_reason"])]] : []
102
110
  ]);
103
111
  const lines = inv["lines"] ?? [];
104
112
  if (lines.length) {
@@ -132,56 +140,61 @@ function buildInvoiceCommand(deps) {
132
140
  })
133
141
  );
134
142
  cmd.addCommand(
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) => {
143
+ new Command("finalize").argument("<ref>").description("Finalize a draft \u2014 assigns a number, freezes it (immutable)").option("--date <date>", "Invoice date YYYY-MM-DD (default today, UTC)").option("--due <date>", "Due date YYYY-MM-DD").option("--number <external>", "A number another system gave it, kept beside the internal number").action(async (ref, opts) => {
136
144
  const body = {};
137
145
  if (opts.number) body["external_number"] = opts.number;
138
- if (opts.due) {
139
- const ms = Date.parse(opts.due);
140
- if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`);
141
- body["due_at"] = ms;
142
- }
146
+ if (opts.date) body["document_date"] = opts.date;
147
+ if (opts.due) body["due_date"] = opts.due;
143
148
  const res = await http.post(`/invoices/${ref}/finalize`, body).catch(die);
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)]]);
149
+ success(`Invoice finalized: ${NUMBER_COL(res.invoice.display_number)}`);
150
+ kv([["id", res.invoice.short_id], ["number", NUMBER_COL(res.invoice.number_text)], ["date", res.invoice.document_date ?? "\u2014"], ...res.invoice.external_number ? [["external_number", res.invoice.external_number]] : [], ["total", fmtMoney(res.invoice.total_cents, res.invoice.currency)], ["balance", fmtMoney(res.invoice.balance_cents, res.invoice.currency)]]);
146
151
  })
147
152
  );
148
153
  cmd.addCommand(
149
- new Command("set-external-number").argument("<ref>", "id or short_id").argument("<number>", "the number the other system gave it (up to 64 characters)").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.").action(async (ref, number) => {
150
- const res = await http.api("PUT", `/invoices/${ref}/external-number`, { external_number: number }).catch(die);
154
+ new Command("set-external-number").argument("<ref>", "id or short_id").argument("<number>", "the number the other system gave it (up to 64 characters)").option("--from-invoice <invoice>", "MOVE the number from this VOID invoice (id or short_id) to <ref>, in one operation").description("Set or change the portal number of a finalized, paid or void invoice (needs `invoice.fiscal_update`)").action(async (ref, number, opts) => {
155
+ const res = await http.api("PUT", `/invoices/${ref}/external-number`, { external_number: number, ...opts.fromInvoice ? { from_invoice_id: opts.fromInvoice } : {} }).catch(die);
151
156
  success(`External number set: ${res.invoice.external_number}`);
152
157
  kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["number", NUMBER_COL(res.invoice.number_text)], ["external_number", res.invoice.external_number ?? ""]]);
153
158
  })
154
159
  );
155
160
  cmd.addCommand(
156
- new Command("pay").argument("<ref>").description("Record a payment against a finalized invoice").requiredOption("--amount <amount>", "Amount, e.g. 150.00").option("--method <method>", "e.g. bank, cash, card").option("--ref <reference>", "External payment reference").action(async (ref, opts) => {
161
+ new Command("clear-external-number").argument("<ref>", "id or short_id").description("Take the portal number off a finalized, paid or void invoice, freeing it (needs `invoice.fiscal_update`)").action(async (ref) => {
162
+ const res = await http.del(`/invoices/${ref}/external-number`).catch(die);
163
+ success("External number cleared.");
164
+ kv([["id", res.invoice.short_id], ["status", res.invoice.status], ["number", NUMBER_COL(res.invoice.number_text)]]);
165
+ })
166
+ );
167
+ cmd.addCommand(
168
+ new Command("pay").argument("<ref>").description("Record a payment against a finalized invoice").requiredOption("--amount <amount>", "Amount, e.g. 150.00").option("--method <method>", "e.g. bank, cash, card").option("--ref <reference>", "External payment reference").option("--date <date>", "The day of the payment, YYYY-MM-DD (default today, UTC)").action(async (ref, opts) => {
157
169
  const res = await http.post(`/invoices/${ref}/payments`, {
158
170
  amount_cents: toCents(opts.amount),
159
171
  ...opts.method ? { method: opts.method } : {},
160
- ...opts.ref ? { reference: opts.ref } : {}
172
+ ...opts.ref ? { reference: opts.ref } : {},
173
+ ...opts.date ? { document_date: opts.date } : {}
161
174
  }).catch(die);
162
175
  success(`Payment recorded. Invoice is now ${res.invoice.status}.`);
163
176
  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)]]);
164
177
  })
165
178
  );
166
179
  cmd.addCommand(
167
- new Command("void").argument("<ref>").description("Void a finalized invoice").option("--reason <reason>", "Reason").action(async (ref, opts) => {
168
- const res = await http.post(`/invoices/${ref}/void`, { reason: opts.reason ?? "" }).catch(die);
180
+ new Command("void").argument("<ref>").description("Void a finalized invoice").option("--reason <reason>", "Reason").option("--date <date>", "The day it is voided, YYYY-MM-DD (default today, UTC)").action(async (ref, opts) => {
181
+ const res = await http.post(`/invoices/${ref}/void`, { reason: opts.reason ?? "", ...opts.date ? { void_date: opts.date } : {} }).catch(die);
169
182
  success(`Invoice voided: ${res.invoice.short_id}`);
170
183
  })
171
184
  );
172
- 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.");
185
+ const showNumbering = (n) => n ? kv([["prefix", n.prefix], ["digits", String(n.digits)], ["yearly", n.yearly ? "yes (the counter restarts each year)" : "no"], ["next", `${n.next} \u2192 ${n.next_text}`]]) : console.log("No series: invoices are numbered 1, 2, 3.");
173
186
  cmd.addCommand(
174
187
  new Command("numbering").description("Show the organization's numbering series (needs `invoice.read`)").option(...outputOption()).action(async (opts) => {
175
188
  const res = await http.get("/settings/numbering").catch(die);
176
189
  printOutput(res.numbering ?? {}, opts.output, () => showNumbering(res.numbering), "prefix");
177
190
  }).addCommand(
178
- 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) => {
191
+ new Command("set").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`.").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>", "Deprecated: accepted and ignored").option("--next <n>", "Continue from this counter (this year's, when yearly); it can only go forward").option("--year <year>", "Which year's series --next applies to (yearly only; default the current year, UTC)").action(async (opts) => {
179
192
  const res = await http.api("PUT", "/settings/numbering", {
180
193
  prefix: opts.prefix,
181
194
  digits: Number(opts.digits),
182
195
  yearly: !!opts.yearly,
183
196
  ...opts.next ? { next: Number(opts.next) } : {},
184
- ...opts.timeZone ? { time_zone: opts.timeZone } : {}
197
+ ...opts.year ? { year: Number(opts.year) } : {}
185
198
  }).catch(die);
186
199
  success("Numbering series set.");
187
200
  showNumbering(res.numbering);
@@ -194,12 +207,18 @@ function buildInvoiceCommand(deps) {
194
207
  )
195
208
  );
196
209
  cmd.addCommand(
197
- 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) => {
198
- const path = ref ? `/invoices/${ref}/payments` : "/transactions";
210
+ new Command("payments").alias("transactions").argument("[ref]", "invoice id/short_id (omit for all org transactions)").description("List payments / transactions (the money ledger)").option("--from <date>", "Paid on or after, YYYY-MM-DD").option("--to <date>", "Paid on or before, YYYY-MM-DD").option(...outputOption()).action(async function(ref, opts) {
211
+ const parent = this.parent?.opts() ?? {};
212
+ const params = new URLSearchParams();
213
+ const from = opts.from ?? parent.from;
214
+ const to = opts.to ?? parent.to;
215
+ if (from) params.set("from", from);
216
+ if (to) params.set("to", to);
217
+ const path = `${ref ? `/invoices/${ref}/payments` : "/transactions"}${params.size ? `?${params}` : ""}`;
199
218
  const res = await http.get(path).catch(die);
200
219
  printOutput(res.transactions, opts.output, (wide) => {
201
220
  table(res.transactions, [
202
- { key: "created_at", label: "DATE", fmt: (v) => fmtDate(v) },
221
+ { key: "document_date", label: "DATE", fmt: (v) => v ?? "\u2014" },
203
222
  { key: "invoice_number", label: "INVOICE", fmt: (v) => v ? `#${v}` : "\u2014" },
204
223
  { key: "customer_name", label: "CUSTOMER", fmt: (v, r) => v ?? r.customer_id },
205
224
  { key: "kind", label: "KIND" },