@fleetless/contracts 6.3.0-next.4 → 6.3.0-next.5
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/CHANGELOG.md +9 -49
- package/artifacts/openapi.json +1841 -4344
- package/artifacts/routes.json +5 -330
- package/dist/errors.d.ts +5 -17
- package/dist/errors.js +6 -31
- package/dist/index.d.ts +2 -4
- package/dist/index.js +1 -5
- package/dist/plans.d.ts +9 -9
- package/dist/realtime.d.ts +2 -2
- package/dist/rest.d.ts +11 -10
- package/dist/rest.js +8 -7
- package/dist/routes.d.ts +1 -1
- package/dist/routes.js +12 -200
- package/package.json +1 -1
- package/artifacts/schema/billing-address.schema.json +0 -49
- package/artifacts/schema/billing-cancel-request.schema.json +0 -12
- package/artifacts/schema/billing-change-request.schema.json +0 -60
- package/artifacts/schema/billing-change-response.schema.json +0 -799
- package/artifacts/schema/billing-details-update.schema.json +0 -25
- package/artifacts/schema/billing-details.schema.json +0 -176
- package/artifacts/schema/billing-invoice.schema.json +0 -76
- package/artifacts/schema/billing-view.schema.json +0 -705
- package/artifacts/schema/checkout-request.schema.json +0 -252
- package/artifacts/schema/checkout-response.schema.json +0 -22
- package/artifacts/schema/checkout-status.schema.json +0 -49
- package/artifacts/schema/payment-method-change-request.schema.json +0 -19
- package/artifacts/schema/payment-method.schema.json +0 -86
- package/artifacts/schema/payment-provider-unavailable-details.schema.json +0 -29
- package/artifacts/schema/vat-id-check-request.schema.json +0 -22
- package/artifacts/schema/vat-id-check-response.schema.json +0 -36
- package/dist/billing.d.ts +0 -812
- package/dist/billing.js +0 -471
package/dist/billing.js
DELETED
|
@@ -1,471 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { ADDONS, PLANS, PLAN_ORDER, addonKey, orgAddons, planCurrency, planId, } from './plans.js';
|
|
4
|
-
/**
|
|
5
|
-
* Countries, VAT and the money math for billing through Mollie
|
|
6
|
-
* (fleetless/fleetless#104).
|
|
7
|
-
*
|
|
8
|
-
* Every price here reads from `plans.ts`'s `PLANS` / `ADDONS` catalogue,
|
|
9
|
-
* never a cent amount of its own, so a price change in one place is a price
|
|
10
|
-
* change everywhere. Money is integer cents throughout; the one rounding a
|
|
11
|
-
* proration or a VAT amount is allowed is `Math.round`, applied exactly
|
|
12
|
-
* once (`prorateCents`, `vatCents`, and `changeNetCents`'s single
|
|
13
|
-
* proration).
|
|
14
|
-
*/
|
|
15
|
-
/** ISO 3166-1 alpha-2, upper case. Greece is `GR` here; VIES calls it `EL`. */
|
|
16
|
-
export const countryCode = z.string().regex(/^[A-Z]{2}$/);
|
|
17
|
-
/** The 27 EU member states, as the billing country. Greece is `GR`. */
|
|
18
|
-
export const EU_COUNTRIES = [
|
|
19
|
-
'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV',
|
|
20
|
-
'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK',
|
|
21
|
-
];
|
|
22
|
-
/** The seller: Dehne Robotik GmbH. Fleetless never charges another EU country's VAT. */
|
|
23
|
-
export const SELLER_COUNTRY = 'DE';
|
|
24
|
-
/** Germany's VAT rate, in whole percent. */
|
|
25
|
-
export const DE_VAT_RATE_PERCENT = 19;
|
|
26
|
-
/** Whether `country` is one of the 27 EU member states. */
|
|
27
|
-
export function isEuCountry(country) {
|
|
28
|
-
return EU_COUNTRIES.includes(country);
|
|
29
|
-
}
|
|
30
|
-
/** EUR in the EU, USD elsewhere. */
|
|
31
|
-
export function currencyForCountry(country) {
|
|
32
|
-
return isEuCountry(country) ? 'eur' : 'usd';
|
|
33
|
-
}
|
|
34
|
-
/** Who is paying: a company (may hold a VAT ID) or a person (a full name, never a VAT ID). */
|
|
35
|
-
export const payerKind = z.enum(['company', 'person']);
|
|
36
|
-
/** The billing cycle: monthly, or yearly at twelve months for 15 % off (#103). */
|
|
37
|
-
export const billingCycle = z.enum(['monthly', 'yearly']);
|
|
38
|
-
/**
|
|
39
|
-
* How a charge is taxed: `de_standard` (German VAT), `reverse_charge` (0 %,
|
|
40
|
-
* an EU company whose VAT ID VIES confirms) or `outside_eu` (0 %, no
|
|
41
|
-
* reverse-charge note).
|
|
42
|
-
*/
|
|
43
|
-
export const vatTreatment = z.enum(['de_standard', 'reverse_charge', 'outside_eu']);
|
|
44
|
-
/**
|
|
45
|
-
* Why `vatFor` refused a payer: `eu_person` (a person outside Germany, in
|
|
46
|
-
* another EU country), `vat_id_required` (a company in another EU country
|
|
47
|
-
* gave no VAT ID) or `vat_id_invalid` (VIES said the given VAT ID is
|
|
48
|
-
* invalid).
|
|
49
|
-
*/
|
|
50
|
-
export const payerRefusalRule = z.enum(['eu_person', 'vat_id_required', 'vat_id_invalid']);
|
|
51
|
-
/**
|
|
52
|
-
* Who may pay, and the VAT they pay. `vatIdValid`: `null` = no VAT ID
|
|
53
|
-
* given; `true` = VIES valid **or unverified** (VIES unreachable is
|
|
54
|
-
* accepted); `false` = VIES said invalid.
|
|
55
|
-
*
|
|
56
|
-
* Germany is unconditional — company or person, VAT ID optional, 19 %
|
|
57
|
-
* regardless of whether a given ID checks out. A German VAT ID's validity
|
|
58
|
-
* never gates checkout, only the renewal sweep later (dunning);
|
|
59
|
-
* `vatFor` only ever prices the charge in hand.
|
|
60
|
-
*/
|
|
61
|
-
export function vatFor(input) {
|
|
62
|
-
const { kind, country, vatIdValid } = input;
|
|
63
|
-
if (country === SELLER_COUNTRY)
|
|
64
|
-
return { allowed: true, treatment: 'de_standard', rate_percent: DE_VAT_RATE_PERCENT };
|
|
65
|
-
if (isEuCountry(country)) {
|
|
66
|
-
if (kind === 'person')
|
|
67
|
-
return { allowed: false, rule: 'eu_person' };
|
|
68
|
-
if (vatIdValid === true)
|
|
69
|
-
return { allowed: true, treatment: 'reverse_charge', rate_percent: 0 };
|
|
70
|
-
if (vatIdValid === false)
|
|
71
|
-
return { allowed: false, rule: 'vat_id_invalid' };
|
|
72
|
-
return { allowed: false, rule: 'vat_id_required' };
|
|
73
|
-
}
|
|
74
|
-
return { allowed: true, treatment: 'outside_eu', rate_percent: 0 };
|
|
75
|
-
}
|
|
76
|
-
/** VIES's member-state code: `EL` for `GR`, the country otherwise. */
|
|
77
|
-
export function viesCountry(country) {
|
|
78
|
-
return country === 'GR' ? 'EL' : country;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Upper-case, without spaces, dots and dashes, and without a leading
|
|
82
|
-
* country prefix: the VIES code (`EL` for Greece) or, for Greece only, the
|
|
83
|
-
* address code `GR` as well, since a payer is as likely to type that. `null` for an
|
|
84
|
-
* empty string (trimmed).
|
|
85
|
-
*/
|
|
86
|
-
export function normalizeVatId(country, raw) {
|
|
87
|
-
const trimmed = raw.trim();
|
|
88
|
-
if (trimmed === '')
|
|
89
|
-
return null;
|
|
90
|
-
let cleaned = trimmed.toUpperCase().replace(/[\s.-]/g, '');
|
|
91
|
-
const vies = viesCountry(country);
|
|
92
|
-
const prefixes = country === 'GR' ? [vies, country] : [vies];
|
|
93
|
-
for (const prefix of prefixes) {
|
|
94
|
-
if (cleaned.startsWith(prefix)) {
|
|
95
|
-
cleaned = cleaned.slice(prefix.length);
|
|
96
|
-
break;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
return vies + cleaned;
|
|
100
|
-
}
|
|
101
|
-
function priceKeyFor(cycle, currency) {
|
|
102
|
-
return `${currency}_${cycle === 'monthly' ? 'month' : 'year'}`;
|
|
103
|
-
}
|
|
104
|
-
function planPriceCentsFor(plan, cycle, currency) {
|
|
105
|
-
const prices = PLANS[plan].prices;
|
|
106
|
-
if (prices === null)
|
|
107
|
-
throw new Error(`billing: ${plan} has no catalogue price — sold by contract, never self-service`);
|
|
108
|
-
return prices[priceKeyFor(cycle, currency)];
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Net price of one period: the plan plus each add-on × units, for the
|
|
112
|
-
* cycle and currency. Add-ons count only on Pro — `plans.ts`'s own rule for
|
|
113
|
-
* which plans may buy them at all (`planFeature.addons`). Throws for
|
|
114
|
-
* `enterprise`: its price is `null`, sold by contract, and self-service
|
|
115
|
-
* never charges it.
|
|
116
|
-
*/
|
|
117
|
-
export function periodNetCents(input) {
|
|
118
|
-
const { plan, addons, cycle, currency } = input;
|
|
119
|
-
const key = priceKeyFor(cycle, currency);
|
|
120
|
-
let total = planPriceCentsFor(plan, cycle, currency);
|
|
121
|
-
if (plan === 'pro') {
|
|
122
|
-
for (const addon of addonKey.options) {
|
|
123
|
-
const units = addons[addon];
|
|
124
|
-
if (units > 0)
|
|
125
|
-
total += ADDONS[addon].prices[key] * units;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
return total;
|
|
129
|
-
}
|
|
130
|
-
/** `Math.round(priceCents * remainingDays / periodDays)` — the one rounding every proration in this module uses. */
|
|
131
|
-
export function prorateCents(priceCents, remainingDays, periodDays) {
|
|
132
|
-
return Math.round((priceCents * remainingDays) / periodDays);
|
|
133
|
-
}
|
|
134
|
-
/** `Math.round(netCents * ratePercent / 100)`. */
|
|
135
|
-
export function vatCents(netCents, ratePercent) {
|
|
136
|
-
return Math.round((netCents * ratePercent) / 100);
|
|
137
|
-
}
|
|
138
|
-
/** Net, VAT (`vatCents`) and gross for one charge. */
|
|
139
|
-
export function chargeAmounts(netCents, ratePercent) {
|
|
140
|
-
const vat = vatCents(netCents, ratePercent);
|
|
141
|
-
return { net_cents: netCents, vat_cents: vat, gross_cents: netCents + vat };
|
|
142
|
-
}
|
|
143
|
-
/** Milliseconds in a day. */
|
|
144
|
-
export const DAY_MS = 86_400_000;
|
|
145
|
-
/** Whole days between `start` and `end` (`Math.round`). */
|
|
146
|
-
export function periodDays(start, end) {
|
|
147
|
-
return Math.round((end.getTime() - start.getTime()) / DAY_MS);
|
|
148
|
-
}
|
|
149
|
-
/** Days left until `end`, as of `now` (`Math.ceil`), clamped to `[0, days]`. */
|
|
150
|
-
export function remainingDays(now, end, days) {
|
|
151
|
-
const left = Math.ceil((end.getTime() - now.getTime()) / DAY_MS);
|
|
152
|
-
return Math.min(Math.max(left, 0), days);
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
|
-
* The net amount charged NOW for moving `from` → `to` within the period
|
|
156
|
-
* — increases are charged at once, decreases wait for the period's end,
|
|
157
|
-
* nothing is credited. Three branches, in this order:
|
|
158
|
-
*
|
|
159
|
-
* 1. **Monthly → yearly**: the full yearly price of `to` (plan plus
|
|
160
|
-
* add-ons, Pro only) minus the unused share of `from`'s monthly price,
|
|
161
|
-
* floored at 0. The period restarts today with a new anchor, so this
|
|
162
|
-
* is the only branch that prices `to` and `from` on different cycles.
|
|
163
|
-
* 2. **Yearly → monthly**: the reverse is a cycle *decrease* — charged 0
|
|
164
|
-
* now, stored as `next_cycle` and applied at the period's end, like
|
|
165
|
-
* every other decrease.
|
|
166
|
-
* 3. **Same cycle**: the increase only — the plan difference when `to` is
|
|
167
|
-
* the higher plan (`PLAN_ORDER`), plus each add-on's added units × its
|
|
168
|
-
* unit price, summed and prorated once over the remaining days. A plan
|
|
169
|
-
* decrease and fewer add-ons contribute 0; add-ons count only when
|
|
170
|
-
* `to.plan` is `pro`, and units held on a plan other than Pro count as
|
|
171
|
-
* none.
|
|
172
|
-
*/
|
|
173
|
-
export function changeNetCents(input) {
|
|
174
|
-
const { from, to, currency, periodStart, periodEnd, now } = input;
|
|
175
|
-
const days = periodDays(periodStart, periodEnd);
|
|
176
|
-
const remaining = remainingDays(now, periodEnd, days);
|
|
177
|
-
if (from.cycle === 'monthly' && to.cycle === 'yearly') {
|
|
178
|
-
const yearlyTo = periodNetCents({ plan: to.plan, addons: to.addons, cycle: 'yearly', currency });
|
|
179
|
-
const unusedFromShare = prorateCents(periodNetCents({ plan: from.plan, addons: from.addons, cycle: 'monthly', currency }), remaining, days);
|
|
180
|
-
return Math.max(0, yearlyTo - unusedFromShare);
|
|
181
|
-
}
|
|
182
|
-
if (from.cycle === 'yearly' && to.cycle === 'monthly')
|
|
183
|
-
return 0;
|
|
184
|
-
const planIncrease = PLAN_ORDER.indexOf(to.plan) > PLAN_ORDER.indexOf(from.plan)
|
|
185
|
-
? planPriceCentsFor(to.plan, to.cycle, currency) - planPriceCentsFor(from.plan, to.cycle, currency)
|
|
186
|
-
: 0;
|
|
187
|
-
let addonIncrease = 0;
|
|
188
|
-
if (to.plan === 'pro') {
|
|
189
|
-
const fromAddons = from.plan === 'pro' ? from.addons : null;
|
|
190
|
-
const key = priceKeyFor(to.cycle, currency);
|
|
191
|
-
for (const addon of addonKey.options) {
|
|
192
|
-
const base = fromAddons ? fromAddons[addon] : 0;
|
|
193
|
-
const added = Math.max(0, to.addons[addon] - base);
|
|
194
|
-
if (added > 0)
|
|
195
|
-
addonIncrease += added * ADDONS[addon].prices[key];
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
return prorateCents(planIncrease + addonIncrease, remaining, days);
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* The first charge of a checkout: one full period of `plan` + `addons`.
|
|
202
|
-
* One line for the plan, then one line per add-on actually bought
|
|
203
|
-
* (quantity 0 is omitted, not a zero-amount line).
|
|
204
|
-
*
|
|
205
|
-
* The VAT is rounded once, over the whole net amount, because that is what
|
|
206
|
-
* is charged. Rounding it per line can land a cent off that total, so the
|
|
207
|
-
* plan line absorbs the difference: the gross lines always add up to
|
|
208
|
-
* `gross_cents`, and the amount a person sees is the amount charged.
|
|
209
|
-
*/
|
|
210
|
-
export function checkoutQuote(input) {
|
|
211
|
-
const { plan, addons, cycle, currency, rate_percent } = input;
|
|
212
|
-
const key = priceKeyFor(cycle, currency);
|
|
213
|
-
const lines = [];
|
|
214
|
-
const planNet = planPriceCentsFor(plan, cycle, currency);
|
|
215
|
-
lines.push({ item: 'plan', quantity: 1, net_cents: planNet, gross_cents: chargeAmounts(planNet, rate_percent).gross_cents });
|
|
216
|
-
if (plan === 'pro') {
|
|
217
|
-
for (const addon of addonKey.options) {
|
|
218
|
-
const quantity = addons[addon];
|
|
219
|
-
if (quantity > 0) {
|
|
220
|
-
const net = ADDONS[addon].prices[key] * quantity;
|
|
221
|
-
lines.push({ item: addon, quantity, net_cents: net, gross_cents: chargeAmounts(net, rate_percent).gross_cents });
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
const netCents = lines.reduce((sum, line) => sum + line.net_cents, 0);
|
|
226
|
-
const total = chargeAmounts(netCents, rate_percent);
|
|
227
|
-
lines[0].gross_cents += total.gross_cents - lines.reduce((sum, line) => sum + line.gross_cents, 0);
|
|
228
|
-
return { ...total, lines, rate_percent, currency, cycle };
|
|
229
|
-
}
|
|
230
|
-
/** Dunning after a failed renewal: retries on these days after the charge's due date. */
|
|
231
|
-
export const BILLING_RETRY_DAYS = [3, 7];
|
|
232
|
-
/** The day, after the charge's due date, the org is locked when still unpaid. */
|
|
233
|
-
export const BILLING_LOCK_DAY = 14;
|
|
234
|
-
/*
|
|
235
|
-
* ---------------------------------------------------------------------------
|
|
236
|
-
* Billing shapes: checkout, the billing account, invoices and the owner's
|
|
237
|
-
* self-service changes (2026-10-04, fleetless/fleetless#104, I-2).
|
|
238
|
-
*
|
|
239
|
-
* The wire shapes for `src/routes.ts`'s `billing` section
|
|
240
|
-
* (`GET /api/billing`, `POST /api/billing/*`). Money is the same
|
|
241
|
-
* integer-cents discipline as everything above; every price still comes
|
|
242
|
-
* from `plans.ts`'s catalogue through `periodNetCents` / `changeNetCents` —
|
|
243
|
-
* nothing here invents a cent amount of its own.
|
|
244
|
-
* ---------------------------------------------------------------------------
|
|
245
|
-
*/
|
|
246
|
-
/** A billing address. `country` gates VAT (`vatFor`) and currency (`currencyForCountry`). */
|
|
247
|
-
export const billingAddress = z.object({
|
|
248
|
-
line1: z.string().trim().min(1).max(200).meta({ description: 'Street and number, or the first address line.' }),
|
|
249
|
-
line2: z.string().trim().max(200).nullable().meta({ description: 'A second address line, or `null` when there is none.' }),
|
|
250
|
-
postal_code: z.string().trim().min(1).max(20).meta({ description: 'Postal or ZIP code.' }),
|
|
251
|
-
city: z.string().trim().min(1).max(100).meta({ description: 'City or town.' }),
|
|
252
|
-
country: countryCode.meta({ description: "The billing country. Decides VAT (`vatFor`) and currency (`currencyForCountry`)." }),
|
|
253
|
-
}).strict();
|
|
254
|
-
/**
|
|
255
|
-
* Who is paying: a `company` (may hold a VAT
|
|
256
|
-
* ID, checked through VIES) or a `person` (full name, never a VAT ID — only
|
|
257
|
-
* a company can be VAT-registered). The discriminant decides which other
|
|
258
|
-
* fields exist at all, so a person cannot even send `vat_id` or
|
|
259
|
-
* `company_name` — there is no field for `.strict()` to refuse, the shape
|
|
260
|
-
* itself has none.
|
|
261
|
-
*/
|
|
262
|
-
export const billingDetails = z.discriminatedUnion('kind', [
|
|
263
|
-
z.object({
|
|
264
|
-
kind: z.literal('company').meta({ description: 'Billed as a company.' }),
|
|
265
|
-
company_name: z.string().trim().min(1).max(200).meta({ description: "The company's legal name, printed on the invoice." }),
|
|
266
|
-
vat_id: z.string().trim().max(20).nullable().meta({
|
|
267
|
-
description: "The company's VAT ID, or `null` for none. Required, and must check out through VIES, for a company outside Germany.",
|
|
268
|
-
}),
|
|
269
|
-
address: billingAddress.meta({ description: 'The billing address.' }),
|
|
270
|
-
invoice_email: z.email().meta({ description: 'Where invoices and billing mail are sent.' }),
|
|
271
|
-
}).strict().meta({ description: "A company: name and an optional VAT ID, never 'full name'." }),
|
|
272
|
-
z.object({
|
|
273
|
-
kind: z.literal('person').meta({ description: 'Billed as a person.' }),
|
|
274
|
-
full_name: z.string().trim().min(1).max(200).meta({ description: "The person's full name, printed on the invoice." }),
|
|
275
|
-
address: billingAddress.meta({ description: 'The billing address.' }),
|
|
276
|
-
invoice_email: z.email().meta({ description: 'Where invoices and billing mail are sent.' }),
|
|
277
|
-
}).strict().meta({ description: 'A person: a full name, never a VAT ID — only a company can be VAT-registered.' }),
|
|
278
|
-
]);
|
|
279
|
-
/**
|
|
280
|
-
* `POST /api/billing/checkout`'s body: the plan and cycle to buy — Basic is
|
|
281
|
-
* free and never checked out — optional add-ons (Pro only; named on `plus`,
|
|
282
|
-
* or without `planFeature.addons`, is `400 validation_error`), the payer,
|
|
283
|
-
* and the terms and withdrawal confirmations: `accept_terms` is
|
|
284
|
-
* always required; `accept_withdrawal` is required for a person and refused
|
|
285
|
-
* for a company, which has no consumer right of withdrawal to confirm.
|
|
286
|
-
*/
|
|
287
|
-
export const checkoutRequest = z.object({
|
|
288
|
-
plan: z.enum(['plus', 'pro']).meta({ description: 'The plan to buy.' }),
|
|
289
|
-
cycle: billingCycle.meta({ description: 'Monthly, or yearly at 15 % off.' }),
|
|
290
|
-
addons: orgAddons.partial().strict().optional().meta({
|
|
291
|
-
description: 'Add-on counts to buy alongside the plan. Pro only; named on `plus`, or without the feature, `400 validation_error`.',
|
|
292
|
-
}),
|
|
293
|
-
billing: billingDetails.meta({ description: 'Who is paying, and where the invoice goes.' }),
|
|
294
|
-
accept_terms: z.literal(true).meta({ description: "Confirms Fleetless's terms of service. Always required." }),
|
|
295
|
-
accept_withdrawal: z.literal(true).optional().meta({
|
|
296
|
-
description: "Confirms the plan starts at once and the 14-day right of withdrawal ends with it. Required for a person; a company sending it is `400 validation_error` — it has no withdrawal right to confirm.",
|
|
297
|
-
}),
|
|
298
|
-
}).strict();
|
|
299
|
-
/** `POST /api/billing/checkout`'s answer: where to send the caller's browser. */
|
|
300
|
-
export const checkoutResponse = z.object({
|
|
301
|
-
checkout_id: z.uuid().meta({ description: 'Identifies this checkout: polled by `GET /api/billing/checkout/:id` and carried on the return URL.' }),
|
|
302
|
-
checkout_url: z.url().meta({ description: "Mollie's hosted checkout page. The caller's browser is sent here." }),
|
|
303
|
-
});
|
|
304
|
-
/** `GET /api/billing/checkout/:id`'s answer: the return page's poll. */
|
|
305
|
-
export const checkoutStatus = z.object({
|
|
306
|
-
checkout_id: z.uuid().meta({ description: 'The checkout this status is for.' }),
|
|
307
|
-
status: z.enum(['pending', 'paid', 'failed', 'canceled', 'expired']).meta({
|
|
308
|
-
description: "Mollie's payment status, as `reconcilePayment` last read it.",
|
|
309
|
-
}),
|
|
310
|
-
purpose: z.enum(['upgrade', 'payment_method', 'invoice']).meta({
|
|
311
|
-
description: 'What this checkout paid for: a plan upgrade, a payment-method change, or an open invoice.',
|
|
312
|
-
}),
|
|
313
|
-
plan: planId.meta({ description: "The org's plan after applying — unchanged unless `purpose` is `upgrade` and `status` is `paid`." }),
|
|
314
|
-
});
|
|
315
|
-
/** VIES's answer to a VAT-ID check: `unverified` when VIES could not be reached in time. */
|
|
316
|
-
export const vatIdStatus = z.enum(['valid', 'unverified', 'invalid']);
|
|
317
|
-
/** `POST /api/billing/vat-id/check`'s body: the VAT-ID-on-blur check the checkout and `PATCH /api/billing/details` both use. */
|
|
318
|
-
export const vatIdCheckRequest = z.object({
|
|
319
|
-
country: countryCode.meta({ description: "The VAT ID's country." }),
|
|
320
|
-
vat_id: z.string().trim().min(1).max(20).meta({ description: 'The VAT ID as typed; normalized before the VIES lookup (`normalizeVatId`).' }),
|
|
321
|
-
}).strict();
|
|
322
|
-
/** `POST /api/billing/vat-id/check`'s answer. */
|
|
323
|
-
export const vatIdCheckResponse = z.object({
|
|
324
|
-
status: vatIdStatus.meta({ description: "VIES's answer." }),
|
|
325
|
-
vat_id: z.string().meta({ description: 'The normalized VAT ID that was checked.' }),
|
|
326
|
-
name: z.string().nullable().meta({ description: 'The registered holder, when VIES named one; `null` otherwise.' }),
|
|
327
|
-
});
|
|
328
|
-
/**
|
|
329
|
-
* `POST /api/billing/change`'s body: the **absolute** target state, never a
|
|
330
|
-
* delta — the route compares it with the org's current state
|
|
331
|
-
* and splits the difference into what is charged now and what is only
|
|
332
|
-
* scheduled. At least one of `plan`, `cycle` or `addons` must be named; the
|
|
333
|
-
* `.refine()` below says so in prose rather than in the JSON Schema this
|
|
334
|
-
* exports as, the same discipline `auditQuery`'s pair already follows —
|
|
335
|
-
* `.refine()` has no JSON Schema rendering.
|
|
336
|
-
*/
|
|
337
|
-
export const billingChangeRequest = z.object({
|
|
338
|
-
plan: z.enum(['plus', 'pro']).optional().meta({ description: 'The target plan. Omitted leaves the plan as it is.' }),
|
|
339
|
-
cycle: billingCycle.optional().meta({ description: 'The target cycle. Omitted leaves the cycle as it is.' }),
|
|
340
|
-
addons: orgAddons.partial().strict().optional().meta({
|
|
341
|
-
description: 'Absolute add-on counts to end up with, not a delta. Omitted leaves add-ons as they are.',
|
|
342
|
-
}),
|
|
343
|
-
}).strict().refine((r) => r.plan !== undefined || r.cycle !== undefined || r.addons !== undefined, { message: 'Name a plan, a cycle or add-ons.' });
|
|
344
|
-
/** `POST /api/billing/cancel`'s body — optional, hence `requestOptional` on the route entry. */
|
|
345
|
-
export const billingCancelRequest = z.object({
|
|
346
|
-
reason: z.string().trim().max(500).optional().meta({ description: 'An optional free-text reason. Shown to nobody but Fleetless.' }),
|
|
347
|
-
}).strict();
|
|
348
|
-
/** `PATCH /api/billing/details`'s body: the invoice email and the VAT ID, the two fields an owner edits after checkout. */
|
|
349
|
-
export const billingDetailsUpdate = z.object({
|
|
350
|
-
invoice_email: z.email().optional().meta({ description: 'Replaces the invoice email. Omitted leaves it as it is.' }),
|
|
351
|
-
vat_id: z.string().trim().max(20).nullable().optional().meta({
|
|
352
|
-
description: 'Replaces the VAT ID; `null` clears it. Omitted leaves it as it is. A new ID is re-checked through VIES.',
|
|
353
|
-
}),
|
|
354
|
-
}).strict();
|
|
355
|
-
/**
|
|
356
|
-
* The payment methods Fleetless takes: card, PayPal and Apple Pay, in EUR and USD, and no others (André, 2026-10-04).
|
|
357
|
-
* Apple Pay is a Mollie method of its own at checkout and for a change, but the mandate it leaves is a card mandate.
|
|
358
|
-
*/
|
|
359
|
-
export const paymentMethodKind = z.enum(['card', 'paypal', 'applepay']);
|
|
360
|
-
/** `POST /api/billing/payment-method`'s body. */
|
|
361
|
-
export const paymentMethodChangeRequest = z.object({
|
|
362
|
-
method: paymentMethodKind.meta({
|
|
363
|
-
description: "The new mandate's method. Offer what `billingView.payment_method_options` lists: `applepay` may be refused with " +
|
|
364
|
-
"`400 validation_error` `{ field: 'method', rule: 'applepay_needs_open_invoice' }` unless an invoice is open.",
|
|
365
|
-
}),
|
|
366
|
-
}).strict();
|
|
367
|
-
/** The billing account's own status, distinct from the org's plan: `billing_accounts` holds no plan, currency or period of its own. */
|
|
368
|
-
export const billingAccountStatus = z.enum(['pending', 'active', 'past_due', 'canceled']);
|
|
369
|
-
/** The payment method on file, read from the active Mollie mandate — never a card or bank number, only its display fields. */
|
|
370
|
-
export const paymentMethod = z.discriminatedUnion('kind', [
|
|
371
|
-
z.object({
|
|
372
|
-
kind: z.literal('card').meta({ description: 'A card mandate.' }),
|
|
373
|
-
brand: z.string().meta({ description: "The card network, as Mollie's mandate reports it, e.g. 'Visa'." }),
|
|
374
|
-
last4: z.string().regex(/^\d{4}$/).meta({ description: 'The last four digits of the card.' }),
|
|
375
|
-
expires: z.string().regex(/^\d{2}\/\d{2}$/).meta({ description: "Expiry as Mollie's mandate shows it, 'MM/YY'." }),
|
|
376
|
-
}),
|
|
377
|
-
z.object({
|
|
378
|
-
kind: z.literal('applepay').meta({ description: "A card mandate from an Apple Pay first payment — Mollie stores it as `creditcard`; Fleetless labels it Apple Pay." }),
|
|
379
|
-
brand: z.string().meta({ description: "The card network, as Mollie's mandate reports it, e.g. 'Mastercard'." }),
|
|
380
|
-
last4: z.string().regex(/^\d{4}$/).meta({ description: 'The last four digits of the card behind Apple Pay.' }),
|
|
381
|
-
expires: z.string().regex(/^\d{2}\/\d{2}$/).meta({ description: "Expiry as Mollie's mandate shows it, 'MM/YY'." }),
|
|
382
|
-
}),
|
|
383
|
-
z.object({
|
|
384
|
-
kind: z.literal('paypal').meta({ description: 'A PayPal mandate.' }),
|
|
385
|
-
account: z.string().meta({ description: "The PayPal account Mollie's mandate names." }),
|
|
386
|
-
}),
|
|
387
|
-
]);
|
|
388
|
-
/** An invoice's status: `open` until paid, or `uncollectible` after a fallback to Basic with an unpaid balance. */
|
|
389
|
-
export const invoiceStatus = z.enum(['open', 'paid', 'uncollectible']);
|
|
390
|
-
/** One invoice, rendered by the cloud: the number is gapless, `FL-<year>-<seq>`. */
|
|
391
|
-
export const billingInvoice = z.object({
|
|
392
|
-
id: z.uuid().meta({ description: "The invoice's id." }),
|
|
393
|
-
number: z.string().regex(/^FL-\d{4}-\d{4,}$/).meta({
|
|
394
|
-
description: 'The invoice number: `FL-<year>-<seq>`, `seq` zero-padded to four digits, gapless per calendar year in `Europe/Berlin`.',
|
|
395
|
-
}),
|
|
396
|
-
issued_at: z.iso.datetime().meta({ description: 'When the invoice was issued.' }),
|
|
397
|
-
status: invoiceStatus.meta({ description: 'This invoice\'s own status.' }),
|
|
398
|
-
currency: planCurrency.meta({ description: "The org's billing currency." }),
|
|
399
|
-
net_cents: z.number().int().nonnegative().meta({ description: 'The charge, excluding VAT, in integer cents.' }),
|
|
400
|
-
vat_rate_percent: z.number().int().min(0).max(100).meta({ description: 'The VAT rate applied, in whole percent.' }),
|
|
401
|
-
vat_cents: z.number().int().nonnegative().meta({ description: 'VAT, in integer cents (`vatCents`).' }),
|
|
402
|
-
gross_cents: z.number().int().nonnegative().meta({ description: 'Net plus VAT, in integer cents.' }),
|
|
403
|
-
});
|
|
404
|
-
/**
|
|
405
|
-
* The org's billing account: the payer, the VAT treatment, the cycle and
|
|
406
|
-
* period, what is scheduled for the period's end and dunning
|
|
407
|
-
*, when a charge is overdue. `orgs.plan`, `orgs.currency` and
|
|
408
|
-
* `orgs.period_ends_at` stay the single source of truth for the plan itself
|
|
409
|
-
* (#103) — nothing here duplicates them.
|
|
410
|
-
*/
|
|
411
|
-
export const billingAccount = z.object({
|
|
412
|
-
payer: billingDetails.meta({ description: 'Who is paying, and the invoice address and email.' }),
|
|
413
|
-
vat_id_status: vatIdStatus.nullable().meta({ description: "The payer's VAT ID check, or `null` when no VAT ID was given." }),
|
|
414
|
-
vat: z.object({
|
|
415
|
-
treatment: vatTreatment.meta({ description: 'How the account is taxed.' }),
|
|
416
|
-
rate_percent: z.number().int().meta({ description: 'The VAT rate, in whole percent.' }),
|
|
417
|
-
}).meta({ description: 'The VAT treatment and rate this account charges at (`vatFor`).' }),
|
|
418
|
-
currency: planCurrency.meta({ description: "The org's billing currency, fixed at the first payment." }),
|
|
419
|
-
cycle: billingCycle.meta({ description: 'The current billing cycle.' }),
|
|
420
|
-
status: billingAccountStatus.meta({ description: "The account's own status." }),
|
|
421
|
-
period_starts_at: z.iso.datetime().nullable().meta({ description: "The current period's start. `null` before the first payment." }),
|
|
422
|
-
period_ends_at: z.iso.datetime().nullable().meta({ description: "The current period's end. `null` before the first payment." }),
|
|
423
|
-
next_charge: z.object({
|
|
424
|
-
at: z.iso.datetime().meta({ description: 'When the next charge is due.' }),
|
|
425
|
-
net_cents: z.number().int().meta({ description: 'The next charge, excluding VAT, in integer cents.' }),
|
|
426
|
-
vat_cents: z.number().int().meta({ description: 'VAT on the next charge, in integer cents.' }),
|
|
427
|
-
gross_cents: z.number().int().meta({ description: 'The next charge including VAT, in integer cents.' }),
|
|
428
|
-
}).nullable().meta({ description: '`null` while a cancel is pending or nothing else renews.' }),
|
|
429
|
-
scheduled: z.object({
|
|
430
|
-
cycle: billingCycle.nullable().meta({ description: "A cycle change queued for the period's end, or `null`." }),
|
|
431
|
-
addons: orgAddons.nullable().meta({ description: "Add-on counts queued for the period's end, or `null`." }),
|
|
432
|
-
}).meta({ description: "What takes effect at the period's end." }),
|
|
433
|
-
dunning: z.object({
|
|
434
|
-
invoice_id: z.uuid().meta({
|
|
435
|
-
description: 'The open invoice dunning is chasing — or, while the payer\'s VAT ID is unsettled, the due charge that becomes one: it has ' +
|
|
436
|
-
'no number yet and is not in `invoices`. `POST /api/billing/invoices/:id/pay` takes either.',
|
|
437
|
-
}),
|
|
438
|
-
gross_cents: z.number().int().meta({
|
|
439
|
-
description: 'The amount owed, in integer cents — after a partial chargeback only the charged-back part.',
|
|
440
|
-
}),
|
|
441
|
-
due_at: z.iso.datetime().meta({ description: "The charge's due date; retries and the lock count from here." }),
|
|
442
|
-
next_retry_at: z.iso.datetime().nullable().meta({
|
|
443
|
-
description: 'The next automatic retry, or `null` once retries are exhausted. Always `null` after a chargeback: a charged-back ' +
|
|
444
|
-
'payment is never charged again automatically.',
|
|
445
|
-
}),
|
|
446
|
-
lock_at: z.iso.datetime().meta({ description: 'When the org is locked if still unpaid (`BILLING_LOCK_DAY`).' }),
|
|
447
|
-
failure: z.string().nullable().meta({
|
|
448
|
-
description: "Mollie's own reason, e.g. 'card_expired'; 'vat_id_invalid' while a renewal is held because VIES does not confirm the " +
|
|
449
|
-
"VAT ID; 'charged_back' after a chargeback or a lost PayPal dispute.",
|
|
450
|
-
}),
|
|
451
|
-
}).nullable().meta({ description: '`null` while nothing is overdue. During a VAT-ID hold the charge is due but not yet invoiced.' }),
|
|
452
|
-
});
|
|
453
|
-
/** `GET /api/billing`'s answer, and what every other billing route hands back after a change. */
|
|
454
|
-
export const billingView = z.object({
|
|
455
|
-
available: z.boolean().meta({ description: 'Whether this cloud takes payments at all — `false` when no Mollie key is configured.' }),
|
|
456
|
-
account: billingAccount.nullable().meta({ description: '`null` before the org has ever checked out.' }),
|
|
457
|
-
payment_method: paymentMethod.nullable().meta({ description: 'The payment method on file, or `null`.' }),
|
|
458
|
-
payment_method_options: z.array(z.object({
|
|
459
|
-
method: paymentMethodKind.meta({ description: 'A method `POST /api/billing/payment-method` accepts now.' }),
|
|
460
|
-
pays_invoice: z.boolean().meta({ description: 'Whether changing to it also pays the open invoice — `true` only for `applepay` when a zero-amount Apple Pay payment is not available.' }),
|
|
461
|
-
})).meta({
|
|
462
|
-
description: 'What a payment-method change may offer right now, so a client offers exactly what the cloud accepts. `applepay` is absent when ' +
|
|
463
|
-
'it needs an open invoice and none is open; `[]` when the org has no billing account.',
|
|
464
|
-
}),
|
|
465
|
-
invoices: z.array(billingInvoice).meta({ description: 'Newest first, at most 24.' }),
|
|
466
|
-
});
|
|
467
|
-
/** `POST /api/billing/change`'s answer: the billing view afterwards, and what was charged right now, if anything. */
|
|
468
|
-
export const billingChangeResponse = z.object({
|
|
469
|
-
billing: billingView.meta({ description: 'The billing view after the change.' }),
|
|
470
|
-
charged: billingInvoice.nullable().meta({ description: 'The invoice charged now, or `null` when the change was only scheduled for the period\'s end.' }),
|
|
471
|
-
});
|