Vouchers (redeemable codes) API
A voucher is an admin-managed redeemable code. Redeeming one grants the tenant a one-time promotional spend credit ("try it with real usage on us"), credited to the tenant's prepaid wallet (a non-refundable promotional wallet_transaction) with an expiry at its first billing period end. Two code types:
unique— single redemption (max_redemptionsforced to1); invite / referral style.generic— many redemptions, capped bymax_redemptions; campaign style.
Grant mechanism (why the credit is durable but one-time)
The credit lands as a non-refundable promotional credit in the single tenant_wallet.balance_micro (the folded money model — the former tenant.bonus_credit_usd / bonus_credit_expires_at columns were dropped, migrations 0441/0442). It is spendable immediately: all wallet money is spendable, and promo / cash only classify refundability, which is derived from the typed wallet_transaction log — never spendability. Spend is enforced against that one wallet balance (a turn is admitted while the wallet holds money and is not frozen), not a budget cap — so the former budget-cap-plus-bonus effective-cap formula, once shared by enforcement and the allowance displays, has been retired and there is no separate cap figure to drift. The grant carries an expiry (unix seconds, snapshotted at grant to the funnel's horizon — the tenant's first-period end); after it, the promotional portion is no longer counted as spendable (the sweep that expires it reads the typed log). It is a one-time grant, not a recurring monthly re-grant. The promotional credit a client shows (promo_usd on GET /admin/auth/me) is the sum of these voucher grants that are still valid and unspent, and nothing else: the opening credit and customer-success grants are non-refundable too but are not vouchers, so they never count toward it.
Redemption is atomic and fail-closed: it locks the voucher row (FOR UPDATE), re-checks eligibility under the lock, bumps a conditional counter that can never exceed max_redemptions, dedups per account (a canonicalised email may redeem a given code at most once — the address is trimmed and lower-cased, +tag subaddressing is stripped for every provider, every trailing dot is removed from the domain (a domain of nothing but dots is refused), and dots are removed from the local part for dot-insensitive providers such as Gmail, so u.ser+promo@gmail.com, user@gmail.com. and user@gmail.com are one account. A leading + is part of the address rather than a tag separator, so +41791234567@sms.corp.de keeps its whole local part and remains redeemable. An address that is not canonicalisable at all — no single @ with non-empty sides, a non-ASCII or control byte, inner whitespace, a domain of nothing but dots or over 254 bytes — is refused at redemption, never redeemed. (The retired advisory checker applied the same rule and was deliberately never sent an address, so it could not be used to test whether a given person had already redeemed a code; it no longer exists at all — see below.) and posts the credit — all in one transaction. A concurrent double-redeem can neither double-grant nor exceed the cap. Redemption runs after the paid tenant is committed, best-effort: a bad / exhausted / contended code never blocks or delays the paid signup. On that funnel the outcome then reaches the customer in the welcome email, which is the only surface that can carry it (the sign-up form's check ran before payment, and the grant happens after): a redeemed code is confirmed with its amount and the date the credit expires, and a code that turned out not to be redeemable is reported as such. An errored redemption is the exception — a failed commit may still have landed server-side, so the email says nothing about the voucher and an operator alert (voucher_redeem_error, subject "Voucher redemption needs diagnosis and PO escalation") is raised and escalated to the PO for diagnosis instead of risking a false "no credit" to a customer who may have one.
Two funnels, one wallet balance
Since the folded money model (migrations 0441/0442 dropped the separate tenant.bonus_credit_usd and tenant_wallet.promo_micro buckets), both destinations grant the same money: a non-refundable promotional credit into the single tenant_wallet.balance_micro, written as one wallet_transaction row. A redemption still records a dest so per-funnel campaign cost stays answerable, but it no longer selects a different column or a different spendability — only the attribution and the expiry source:
dest |
Funnel | Lands in | Refundable | Expiry source |
|---|---|---|---|---|
bonus |
pay-first signup and the trial→paid conversion | tenant_wallet.balance_micro (non-refundable promotional wallet_transaction) |
no — a marketing grant is never convertible to a cash refund | the funnel's bonus_expires_at |
promo |
redemption at trial start for an opted-in code (below) | tenant_wallet.balance_micro (non-refundable promotional wallet_transaction) |
no | the funnel's promo_expires_at |
Both are spendable immediately. The grant is non-refundable because balance_micro is the one spendable balance and refundability is derived from the typed wallet_transaction log (storage.wallet_refundable): a promotional row counts toward the spendable balance but never toward the refundable cash a refund may draw, so promotional money is neither refundable nor unaccountable — the log is the per-grant evidence. The credit is written through the one wallet primitive (credit_promo_on_conn) on the redemption's own connection and transaction, so a failure rolls back the counter bump and the redemption row with it.
The grant's wallet_transaction row carries no Stripe charge (paid_minor / credit_minor 0, paid_currency USD, no fx_rate, no granted_by), and its idempotency token is a vg:-prefixed digest of tenant + voucher + account, because the ledger's uniqueness is global rather than tenant-scoped.
Expiry is a property of the grant row, derived from the log (not a promo_expires_at column — that column is dropped). After a promotional grant's expiry the money is no longer counted as spendable, and the promo-expiry sweep reads the typed log to retire it; on conversion to paid the live promo horizon is extended to the first paid period's end, and an extension never shortens a live expiry.
voucher_redemption.dest (bonus | promo, default bonus) snapshots the funnel per row, for the same reason credit_usd is snapshotted: the opt-in flag is mutable, so without the snapshot, flipping one flag would silently rewrite the attribution of every historical redemption and per-destination campaign cost would become unanswerable.
One granted code per campaign per tenant
Codes of a campaign (voucher_series) share one rule: at most one granted code per series per tenant. It is fixed, not
configurable. A second code of a series the tenant already holds a grant from is refused with the settled detail
campaign_already_redeemed (counter not bumped, nothing credited; on the trial path the pending code is cleared and the SPA shows
its own copy for the reason; emails keep the generic sentence). The check runs before eligibility, so a tenant that holds a
grant from the series gets this answer even for an expired, inactive or already-redeemed code. Codes of different series, and codes without a series,
are independent.
Enforcement: every redemption first takes a per-tenant row lock (SELECT … FROM tenant … FOR UPDATE, lock order tenant →
voucher → wallet), so two codes of one series racing for one tenant are serialized and the second sees the first's committed row.
voucher_redemption.series_id snapshots voucher.series_id at grant, and UNIQUE(tenant_id, series_id) (NULL never collides) is
the backstop. A redemption for an unknown or soft-deleted tenant is error / tenant_missing before any counter bump. The rule
assumes a single database primary.
Attribution: tenant, campaign and code
Every code that reaches provisioning at signup (pay-first, trial, and Google / Microsoft sign-up) is recorded in voucher_claim,
one row per (tenant, code), including codes that are later refused or still pending. The row holds the entry facts only:
user_id (the owner provisioned with the signup), the normalized code, voucher_id / series_id (what the code resolved to
at provisioning; NULL = unknown code at that time — immutable, so deleting an unused voucher and re-minting its code never
re-attributes the claim), source (signup_paid | signup_trial | signup_oauth), created_at, and the informational
last_refusal_reason / last_refusal_at (detail of the latest non-granted decision).
The claim's status is derived, never stored:
| Status | Meaning |
|---|---|
granted |
a voucher_redemption of the tenant exists for a voucher with this code (campaign = that redemption's series_id) |
pending |
not granted, tenant not soft-deleted, and tenant.pending_voucher_code still holds the code — merely "still held": retried at conversion while on trial, awaiting PO escalation once the tenant has a subscription. It does not by itself mean the grant is owed: a holder who was told the code is not applied is still held (see "Redemption checks" below) |
rejected |
otherwise (settled refusal, unknown code, soft-deleted tenant, code cleared by erasure) |
storage.list_voucher_claims_for_tenant is the single implementation of this derivation. Readers of last_refusal_reason must
filter on derived rejected (a reason noted at trial start stays set when the conversion later grants). Historical grants are not
backfilled into voucher_claim. A tenant purge removes its claims; a user erasure sets voucher_claim.user_id to NULL and leaves
voucher_redemption.account_email untouched.
Redemption at trial start — redeem_at_trial
What POST /signup/trial answers
A trial-start redemption settles while the account is being provisioned, so its outcome rides the
provisioning response as an optional voucher object:
status |
tenant.pending_voucher_code |
What the customer is told |
|---|---|---|
granted |
cleared (the claim committed) | the amount that was added, plus the same statement in the trial-started email |
deferred |
left set | the code is on file and will be applied at the first paid period — the conversion can still redeem it |
not_applied |
left set, except for invalid / already_redeemed / campaign_already_redeemed |
a reason from the closed set below, or generic copy when the server withholds it |
| key absent | left set | nothing at all |
The pending column is kept unless the answer cannot change for that account. The test is not "is
this answer definite" but "could a later redemption still succeed", because the two mistakes cost wildly
different amounts: clearing the column destroys the grant permanently (the conversion webhook only looks
at vouchers while it is non-NULL), while keeping it costs one retry that either succeeds or refuses
again. Only invalid (no such code), already_redeemed (this account has consumed it, and
UNIQUE(voucher_id, account_email) means no later attempt by it can succeed) and campaign_already_redeemed
(the tenant already holds a grant from this code's campaign, which never changes) are settled. inactive is
an operator toggle, and expires_at / max_redemptions are both editable, so expired and
exhausted are routinely undone by the operator who notices — those keep the code while still telling
the customer the true reason for now.
A promise made at trial sign-up is honoured at conversion. A holder is owed the credit when it was never told
anything that contradicts a grant: it has no claim row (an older tenant), no recorded refusal, or a deferral reason
(not_trial_redeemable, wrong_type — "saved, applied when you subscribe"). For an owed holder the conversion redeems the
code even if an operator has since deactivated it or it has expired. exhausted (the campaign's spend cap),
already_redeemed and campaign_already_redeemed are never waived. A holder who was told inactive, expired or
exhausted was not promised anything and gets the normal checks. This is exactly the set the admin Pending count shows,
so deactivating a code never voids credit the console says is outstanding. A transient error never replaces a deferral
reason, so a retried delivery cannot turn an owed holder into a refused one.
reason is one of invalid · inactive · expired · exhausted · already_redeemed · campaign_already_redeemed. It is
deliberately omitted when the cause was our own defect (a stored credit_usd outside the allowed
band, or an address our canonicaliser refuses): those page an operator and the customer gets generic
copy, because naming our bug to them is both unhelpful and a hint about the campaign.
Redemption checks eligibility first (inactive, expired, exhausted, already_redeemed) and only then the policy gates (trial opt-in, type). A deactivated, expired or used-up code therefore reports its own reason and not_applied on the trial funnel, never deferred ("saved"). Only not_trial_redeemable and wrong_type are deferral reasons. The one exception is the conversion redemption of an owed holder (above), which skips the inactive and expired checks.
wrong_type is not in that set: it reports deferred, not not_applied. A generic campaign
code submitted on the trial funnel is not a bad code, it is a code for the other funnel — the conversion
redeems with require_type: "any", so it would grant it into bonus. Reporting it as a settled refusal
cleared the pending column and made the promised credit unreachable, with no alert and no evidence.
Redemption now evaluates the trial-opt-in gate before the type gate, so the common case answers
not_trial_redeemable and both land on deferred.
An ABSENT voucher key is not "no voucher" — it is "say nothing". It covers both "no code was
submitted" and "the redemption errored", and the two are deliberately indistinguishable to the client: on
an errored redemption a failed COMMIT may still have posted the credit, so claiming "your code was not
applied" could be a lie about money that moved. The server pages an operator instead, keeps the pending
code as reconciliation evidence, and the trial-started email renders no voucher paragraph at all.
Consuming clients must fail closed on this object too: it is untrusted input to the SPA. A present
but unrecognised shape must render neutral copy that makes no claim either way — distinct from an absent
key, which renders nothing — and a granted outcome whose credit_usd is unreadable is still a GRANT
(the money moved) and must state the grant without naming a figure, never degrade to "unknown".
By default a code is redeemed when the customer starts paying (below). redeem_at_trial opts a code out of that (a unique or a generic code; per-mailbox dedup and the max_redemptions cap still apply): it is redeemed at trial start as a non-refundable promotional credit in the wallet (dest: "promo"), i.e. it becomes spendable during the trial. The flag defaults to 0, so the behaviour is dark until an operator sets it per code.
Because such a code grants spendable money with no payment and no human in the loop, it is bounded on every path that can set it — in POST/PATCH (below), and in the database as the last fail-closed boundary:
- the code must be
generic(any cap) oruniquewithmax_redemptionsexactly1, with the type compared byte-exact. The DBCHECKcompares the type as a binary string, soUNIQUE,uniquéand'unique 'are all refused: the column's collation is case- and accent-insensitive, and a hand-writtenUPDATEmust not be able to smuggle a multi-useuniquecode in. A generic code is bounded by itsmax_redemptionscap and the per-mailbox dedup instead. - the code must be at least 11 characters. The per-IP rate limit is not a defence here (the client controls the leftmost
X-Forwarded-For), so the real bound is the global limiter — roughly 48,000 probes a day platform-wide, which is nothing against 11 random characters (27¹¹ ≈ 5.6 × 10¹⁵ codes for a series mask; even against a full 10,000-code series that is about 32,000 years of the whole platform budget per hit) and useless against aMYRA2026-NNNNserial. The length counts characters, not randomness: a hand-typed single code is only as hard to guess as the operator made it. credit_usdmust be in[1, 100]— a floor as well as a ceiling. Migration 0553'sCHECKbinds the amount to1..100in the database as well, and redemption still re-asserts this ceiling against the stored row; a row outside the band is refused asbad_creditand pages an operator rather than blaming the customer.
A redemption requested for the trial destination against a code that is not opted in is answered not_trial_redeemable: nothing is consumed, no redemption row is written, and the code stays pending so the conversion can still redeem it later. That is deliberately distinct from exhausted — one is deferred, the other settled.
When a code is redeemed — two moments, one implementation
The sign-up form offers the voucher field on the paid (pay-first) funnel's checkout step, and now also on the trial funnel's email step when the entry URL carries ?voucher= (a campaign link; the default trial funnel is still email-only and collects no voucher). On the paid funnel the code is redeemed at the moment the tenant starts paying:
| Funnel | Redeemed | Bounded to |
|---|---|---|
| Pay-first | at provisioning, immediately after the paid tenant is committed | the tenant's first billing period |
| Free trial | a code an operator opted in (redeem_at_trial: true) is redeemed at trial start, as a non-refundable promotional credit in the wallet; every other code stays deferred and is redeemed at conversion |
at trial start for an opted-in code; otherwise the first paid period |
Whether a trial start consumes a campaign slot depends on the code. For an ordinary code it does not: the counter bump, the single-use decrement and the per-account dedup row all happen inside the one atomic redemption, which a deferred code only reaches at conversion. N trials may hold the same single-use code; whichever converts first redeems it, the rest are told it could not be redeemed.
This changed for an opted-in code (redeem_at_trial: true), and deliberately so: such a code IS redeemed at trial start, so the counter bump and the dedup row happen there. That is not a loosening — it is what bounds the faucet the old wording worried about. A trial-redeemable code must be either unique with max_redemptions = 1 or generic (any cap) — CHECK-backed (migration 0553, which replaces 0359's unique-only rule), re-validated on create and on update. A unique code is single-use by construction; a generic code is bounded by its max_redemptions cap, which is consumed atomically at trial start. In both cases the per-account dedup row stops the same address taking it twice. The faucet the old paragraph described — sign up, take the credit, never convert, repeat — is closed by those controls rather than by refusing to redeem. A series follows the same rule: a trial-redeemable series may be unique (forced to max_redemptions = 1) or generic (any cap), with the same credit bounds and random-position minimum. Whatever the type, each organisation can redeem only one code of a campaign: a second code from the same series, or the same code again under another mailbox, is refused with campaign_already_redeemed and consumes no slot and grants no credit.
Between trial start and conversion the code is held on the tenant as pending_voucher_code, together with pending_voucher_email — the OTP-verified sign-up address, frozen at trial start, which is the per-account dedup key when the redemption finally runs. The address is frozen rather than re-read from the tenant's current owner because the owner's email is tenant-mutable: with a mutable key an owner could set it to someone else's address just before converting and, through the per-account uniqueness rule, permanently burn that address's eligibility for the campaign. Freezing it also keeps the redemption record — which is the campaign's measurement — attributed to the account that actually signed up. The canonicalisation above is shared with the one-trial-per-email gate so the two cannot disagree; it was tightened to match that gate, which previously did not fold dots here. Because the stored dedup key is a persisted value, tightening it also means a key computed today no longer matches a row written under the older form — so redemption deliberately checks the stored rows under both the current and the previous key. That second check recovers the ordinary case — someone presenting the same address again — but it is not a complete guarantee: it is derived from the address submitted, not from the stored rows, so a person who had already redeemed under a dotted Gmail address and presents the dotless form instead is not matched, and regains one redemption on that code. The campaign's own max_redemptions ceiling is unaffected, so this bounds the cost; what it does not preserve is the per-account rule for that historical group. Existing rows are not rewritten, and the complete fix is to migrate them, after which the second check is removed.
Two mailboxes are still counted separately that arguably should not be: @gmail.com and @googlemail.com are aliases for the same Google inbox but yield two dedup keys, so one inbox can redeem a given code twice. Unifying them changes both the dedup key and the per-domain signup throttle bucket for existing records, so it is tracked as a migration rather than applied silently.
The deferred redemption is claimed atomically (compare-and-set on pending_voucher_code) in the same transaction as the grant, so a Stripe redelivery, a concurrent delivery, or a retry after a crash between the conversion and the grant all converge on exactly one redemption. A code still pending after a conversion means the grant has not happened yet and the next delivery completes it.
Nothing reserves the code in the meantime. Between trial start and conversion it can be deactivated, expire, or be exhausted by other redeemers. A holder who was told the code is saved is still honoured if it was deactivated or expired meanwhile (see "A promise made at trial sign-up" above), but not if other redeemers used up the campaign, so the trial funnel's copy stays conditional ("applied when you subscribe, if still redeemable then"). An abandoned trial keeps its pending code indefinitely — a trial tenant has no subscription row and is therefore never purged by the billing reaper — so a much later conversion still redeems it: an owed holder (deferred, legacy no-row or unnoted claim) is honoured even after the voucher's expires_at or a deactivation, bounded only by max_redemptions and the already_redeemed / campaign rules, while a holder who was told "not applied" gets the normal gates.
The customer is told the outcome on both funnels: the pay-first welcome email, the trial-start email (which states that the code is on file and applied at subscription), and the trial-conversion email (which reports the redemption exactly as the welcome email does). An errored redemption is the one case that says nothing and pages an operator instead — see above.
redemptions_used is a monotonic lifetime counter (measurement + cap guard); it is never decremented, and a GDPR tenant purge deletes that tenant's redemption rows but leaves the counter (the grant still happened).
Campaign series — bulk generation for printed material
POST /admin/v1/voucher-series (platform admin, VOUCHERS_MANAGE)
A series mints up to 10,000 individually unique codes in one action, all sharing one amount and one set of terms. Before this, creating a 3,500-code campaign meant 3,500 calls to POST /admin/v1/vouchers with nothing recording that they belonged together.
Accepted body:
| Field | Rules |
|---|---|
name |
Required. 1–128 characters, the operator-facing label ("Web Summit 2026"). Absent or empty: name_required; null or not a string: invalid_name; over 128: name_too_long. The text must be valid UTF-8 and contain no control character and no invisible format character (zero-width space or joiner, bidi override, BOM, ...): invalid_name. An emoji with a variation selector is accepted; a zero-width-joiner emoji sequence is refused. |
mask |
Required. A code pattern of 1–64 characters, upper-cased, from the allow-list A-Z 0-9 _ - ! ? . plus #. Every # is replaced by one random character; every other character is printed verbatim — so SCCON_!##### yields SCCON_!7WB4Q. It must contain at least one # (a mask with no random position would mint one identical code N times); otherwise 400 mask_needs_random. The mask is validated fail-closed and is not a caller-supplied regex, so there is no ReDoS surface; the literal characters share voucher.code's charset so a generated code is normalisable by the same rule that stores it. (Supersedes the earlier prefix + allow-listed format pair.) Absent or empty: mask_required; null, not a string, or a character outside the allow-list: invalid_mask; over 64 characters: mask_too_long. |
count |
Required. 1–10,000, rejected, never clamped — a clamp would print 10,000 cards for an operator who asked for 50,000 and tell them nothing. Also refused above 10% of the mask's code space (code: "count_exceeds_space"): the space is 27 ^ (number of #), and past a 10% load factor the per-row collision retries climb and the last rows grind against a nearly-full space. A mask with more # holds more codes. Absent: count_required; null, not a number or not an integer: invalid_count; outside 1–10,000: count_range. |
credit_usd |
Required. A JSON number in [0.01, 10000] (absent: credit_usd_required; null, a string or a non-finite number: invalid_credit_usd; outside the range: credit_usd_range). One amount for the whole series. A numeric string such as "5" is refused: the rule is the one single-voucher create uses, and it is number-only. The admin UI parses the amount strictly (plain digits with one decimal point or comma; no exponent, hexadecimal or thousands separator) and sends it as a JSON number. Accepted shape: 12.5 or 12,5, at most 6 decimal places and 15 significant digits. Rejected before anything is sent: empty, 1e3, 0x10, 1.500 and 10,000 (ambiguous grouping; write 1.5 or 10000). |
type |
Required. unique or generic, as on a single voucher. Absent or empty: type_required; anything else: invalid_type. |
max_redemptions |
Forced to 1 for unique (absent or null there means 1); required for generic, 1–1,000,000. An explicit value other than 1 on a unique series is a contradiction, refused rather than silently corrected. On a generic series: absent: max_redemptions_required; null, not a number or fractional: invalid_max_redemptions; outside the range: max_redemptions_range. On a unique series: not a number (a string, a boolean): invalid_max_redemptions; any number other than 1, a fractional one included: max_redemptions_unique. The same rule applies to a single POST /admin/v1/vouchers of type unique: absent, null or 1 is accepted (stored as 1), a non-number is invalid_max_redemptions, any other number is max_redemptions_unique. |
redeem_at_trial |
Optional boolean, default false (the feature's dark switch). Absent and malformed are different answers: a present-but-non-boolean value is its own refusal (invalid_redeem_at_trial), because silently reading "1" as absent would answer 201 while leaving the campaign not trial-redeemable — so an operator prints 3,500 cards believing a flag is set that is not. A trial-redeemable series may be unique (with max_redemptions = 1) or generic (with its cap), requires credit_usd in [1, 100] and at least 11 # positions in the mask (trial_redeem_credit_range, trial_redeem_entropy), and is backed by a DB CHECK. Each organisation can redeem only one code of the series (campaign_already_redeemed), and a generic code's cap is consumed atomically at trial start. |
expires_at |
Optional unix seconds; omit or null = never. Must be an integer at least 24 hours from now: not an integer or not positive → invalid_expires_at, in the past → expires_past, less than 24 h ahead → expires_too_soon. |
idem_key |
Required, 8–128 bytes (absent or empty: idem_key_required; not a string or under 8: invalid_idem_key; over 128: idem_key_too_long). The key is compared byte for byte: ABC and abc, or a key and the same key plus a trailing space, are two different keys. It must be valid UTF-8 without control or format characters, otherwise invalid_idem_key. Generating 10,000 rows takes long enough that a client timeout and retry is the expected case, not the exotic one — and without a key that retry mints a second 10,000-code series. A retried create with the same key and the same terms (mask, count, credit_usd, type, max_redemptions, expires_at, redeem_at_trial; name is compared after normalisation) resolves to the same series (200, replayed: true, requested is the count stored with the series) and resumes it. The same key with different terms answers 409 idem_key_conflict and writes nothing (no series, no codes, no audit row); the admin UI asks the operator and, on confirmation, retries under a fresh key. A legacy series created before the terms were recorded (no mask) never replays and answers 409 as well. A replay after the series' expires_at has passed answers 400 expires_past, because that check runs before the idempotency lookup. |
Response 201 (created) or 200 (replayed: true): { id, generated, requested, status: "ready", replayed }.
Response 202 — generation stopped short: { id, generated, requested, status: "generating", replayed, error, code: "generation_incomplete" }. This is a real, actionable state, not a hidden failure. The rows that exist are committed and generated says how many; POST /admin/v1/voucher-series/{id}/resume continues from there. Resuming a series that does not exist (or was deleted) answers 404 not_found and writes no audit row (see the resume call below). Generation deliberately is not one transaction: 10,000 rows in a single write would hold a long lock on voucher — the table redemption locks per row — so a campaign generation would stall live redemptions. Batches of 500 commit, each advancing the counter in the same transaction as its rows, so a crash can never leave the counter claiming codes that do not exist.
The random positions (#) are cryptographically random, not sequential: a printed voucher is a bearer instrument, and a predictable series is a free money faucet for anyone who buys one card and extrapolates. The bytes are rejection-sampled onto the charset so the distribution is uniform (a modulo would bias the low characters, which is exactly the structure a guesser exploits). The random alphabet excludes I, O, S, Z, 0, 1, 2, 5 and 8 — the pairs a human reliably mistypes off a card (I/1, O/0, S/5, Z/2, B/8) — leaving 27 symbols, so a mask's code space is 27 ^ (number of #). A code collision is errno 1062 on voucher.code's unique index and is retried with a fresh code, bounded at 12 attempts per row; the load-factor refusal above is what keeps that a rounding error rather than the common path. A trial-redeemable series additionally requires at least 11 random positions — entropy counted as #, not total length, so a literal-heavy mask cannot grant spendable trial credit off a handful of guesses.
Decision 9 — one amount for the whole series. credit_usd, type, max_redemptions, expires_at and redeem_at_trial are copied onto each voucher row at generation rather than read through at redemption. That copy is deliberate: redemption already reads the voucher row under a lock, and joining to the series would either add a join to the money path or let a later edit of the series silently rewrite the terms of codes already in a customer's hand. The series carries the order; the voucher carries the promise.
A validation rejection is 400 { error, code } (for example mask_needs_random, count_exceeds_space, credit_usd_range). A refusal the validator ever makes without a code of its own answers code invalid_request. If the series row cannot be created, the answer is 503 { "error": "temporarily unavailable; retry later" } with a Retry-After header when the storage layer proved that nothing was written (a lock wait, deadlock or lost connection before the series row existed), otherwise 500 { "error": "could not create the voucher series", "code": "admin_handler_failed" } (the outcome is not known; list the series before repeating). Because idem_key is required, repeating the request with the same idem_key after a 503 is safe: it creates the series once, or replays the stored one. A failed series list answers 503 with Retry-After for a transient database fault (a read; retry), and 500 { "error": "could not list voucher series", "code": "admin_handler_failed" } for any other fault.
POST /admin/v1/voucher-series/{id}/resume
VOUCHERS_MANAGE. Continues the generation of a series that stopped short. Idempotent: a series that is already ready returns its count unchanged, so you can call it without checking first.
200 { id, generated, status: "ready" }— generation is complete.202 { id, generated, status: "generating", error, code: "generation_incomplete" }— generation stopped short again; call resume again.404 { "code": "not_found" }— no such series (or it was deleted). No audit row is written.
The series list: live counts
GET /admin/v1/voucher-series reports, per series, the live numbers computed from the voucher rows at read time: codes_live (codes that exist), codes_active (of those, active = 1) and codes_redeemed (redemptions_used > 0). They stay true when single codes are deleted or deactivated, unlike the generated counter, which records only what generation wrote. The list no longer carries a series-level active field: a series has no switch of its own, so the field was never written and always read 1. Deactivation is a property of the codes (below). The answer is a bare array; if the list cannot be read, the answer is 500 { "error": "could not list voucher series" }.
POST /admin/v1/voucher-series/{id}/deactivate
VOUCHERS_MANAGE. Sets active = 0 on every code of the series in one transaction, with the series row locked. Answers 200 { "ok": true, "deactivated": n } where n is the number of codes actually switched off (the call is idempotent: repeating it is a success that changes nothing and reports 0). 404 not_found for an unknown id. 409 series_not_ready while the series is still generating, so a half-generated series is never half-deactivated and then completed active. Audited as voucher_series.deactivate with { deactivated: n }; the audit row is written after the commit, and if that write fails the failure is logged and the response still reports the success that happened.
DELETE /admin/v1/voucher-series/{id}
VOUCHERS_MANAGE. Deletes the series and all its codes, in any status (including a stuck generating one). Refused when it would destroy a record or break a customer:
| Code | HTTP | When |
|---|---|---|
has_redemptions |
409 | any code of the series was redeemed (redemptions_used > 0 or a voucher_redemption row exists) |
has_pending_claims |
409 | a tenant is holding one of the series' codes as a pending trial claim (pending_voucher_code) |
not_found |
404 | no such series |
Success is 200 { "ok": true, "deleted": n } with the number of codes removed. The series row is locked first, then the voucher rows (the same order generation uses; redemption locks tenant → voucher and never the series row, so a delete serialises with redemptions on the voucher rows), so a redemption cannot slip in between the check and the delete; a generation batch that runs after the delete finds no series and writes nothing. Audited as voucher_series.delete with { deleted: n }, after the commit.
GET /admin/v1/voucher-series/{id}/export
The code list, as text/csv with one code column (CRLF line endings, nothing after the last line), Content-Disposition: attachment; filename="voucher-series-{id}.csv" and Cache-Control: no-store. The answer carries the same credentialed CORS headers as the other admin API answers, because the admin console fetches it cross-origin.
Platform admins only (VOUCHERS_MANAGE, a platform permission that custom roles cannot be granted). Any other signed-in user gets 403, and no codes are read and no audit row is written.
In the admin console (Pricing → Vouchers → Campaign series → Download codes), the button first asks for confirmation. It then requests the file from the admin API, using the same address and sign-in as every other admin call, and saves it as voucher-series-{id}.csv. If the answer is not a CSV (for example, an HTML page), or the request fails (any 4xx/5xx or a network error), the console shows an error message and saves nothing. An HTML page is never saved as the code list.
The server exports any existing series, including a deactivated one (its codes are dead and harmless); the console hides Download codes for a deactivated series, for one whose codes were all deleted, and while it is still generating.
Every download is audited (voucher_series.export, naming the admin and the row count) because this is a bulk bearer secret — anyone holding a code can redeem it. The audit row is written before the body, so a response that dies mid-stream is still recorded; the download may well have reached the client. If the audit row cannot be written, no codes are sent: the export is refused with a retryable 503, so no download ever goes unrecorded. A storage fault while reading the series or its codes also answers 503.
An unknown series id answers 404 { "error": "voucher series not found", "code": "not_found" }.
Refuses a series that is not ready with 409 series_not_ready and the generated/requested pair. Handing an operator 1,800 of 3,500 codes is how a campaign ships with 1,700 cards that were never printed.
Refuses a series with no codes (for example after its codes were deleted individually) with 409 series_empty, before any audit row is written: an empty file is not a download worth recording.
The shared terms are deliberately not repeated per row: they live on the series and are already in the audit record, and an amount next to every code invites an editor to change one.
There is no public checker — and that is deliberate
POST /admin/auth/signup/voucher no longer exists. It was a public, advisory, display-only check that answered valid:true, credit_usd:50 for a live campaign code and expires_before_redemption for one that would lapse inside the trial window.
That is an unauthenticated enumeration oracle. It let anyone sort guesses into "real campaign code" and "noise" without an account, bounded only by a per-IP limit over an address the gateway cannot trust (the leftmost X-Forwarded-For is client-controlled) and a coarse global ceiling of 2000/hour — roughly 48,000 probes a day, platform-wide. Against a printed serial like MYRA2026-NNNN that is not a bound at all, and with 3500 codes in a campaign series the "is this a real code" distinction is the entire prize.
What the funnel does instead. No judgement about a code is made before the one-time passcode. The sign-up form keeps a format-only check — trimmed, upper-cased, 4–64 characters of A-Z 0-9 _ - ! ? ., the same shape the server stores — which runs locally and contacts nothing. It can only ever say "that cannot be a code at all", which is a real service to someone who mistyped a printed card; it never implies the code exists, is live, or is worth anything.
Every real answer comes from redemption, which happens under a row lock after the passcode — so after a verified mailbox and an audited account. One consequence is a feature rather than a cost: the post-provision screen is the first place an amount is ever stated, which is what makes that statement honest. It reports what actually landed in the wallet, not what the voucher advertised.
Do not reintroduce a pre-authentication validity probe, under any verb or name. If an operator needs to check a code, that belongs behind VOUCHERS_MANAGE on the admin surface, where the caller is known and the call is audited.
The paid checkout step (signup/checkout) accepts an optional voucher_code (same shape). The no-card trial now collects one too, but only from a campaign link — the trial's email step shows a voucher field solely when ?voucher= is present in the URL, and the code rides signup/request onto the intent. signup/trial itself still takes no body, so the funnel entry is signup/request, not the trial call. A malformed value is dropped (the checkout still proceeds); a well-formed code is stored on the signup intent and redeemed authoritatively post-provision. See Authentication → Self-serve sign-up.
Admin management — /admin/v1/vouchers
Base URL: https://<your-gateway-host>/admin/v1. Every route is platform-admin only (vouchers are global campaign resources, not tenant-scoped) — a non-admin session is rejected 403. Every mutating route writes an audit_log row (entity_type: "voucher", the voucher id as the entity), including the redeem_at_trial transition: on a surface where one field decides whether a code grants spendable money, "who turned it on, and when" has to be answerable from the trail alone.
| Method | Path | Description |
|---|---|---|
GET |
/admin/v1/vouchers |
List all vouchers (newest first), each with redemptions_used / max_redemptions for measurement. |
GET |
/admin/v1/vouchers/{id}/redemptions |
Per-code redemption rows (top-of-funnel measurement). |
POST |
/admin/v1/vouchers |
Create a voucher. |
PATCH |
/admin/v1/vouchers/{id} |
Deactivate / reactivate ({ "active": boolean }), or edit credit_usd / max_redemptions / expires_at / redeem_at_trial — one or the other, never both. |
Each row of GET /admin/v1/vouchers also carries pending_claims: the number of trial tenants currently holding this code whose redemption is still deferred to conversion. It is the campaign's outstanding liability — a code reading "3 / 50 redeemed" may have another 900 trials able to claim it — and is counted live from the tenant table rather than stored, so it cannot drift. A client that does not receive the field should treat it as unknown, not as zero.
pending_claims counts the holders who are owed the credit at conversion (a deactivated code with pending_claims > 0 is still honoured for them; the console says so when you deactivate): holders with no recorded refusal, or whose refusal was a deferral reason (not_trial_redeemable, wrong_type). Holders whose held code was refused for a settled reason (for example the code was deactivated or expired) are reported separately as held_refused_claims. The two add up to all live holders. Holding a refused code is unchanged: it is still retried at the first paid period. The console shows the second number in the redemptions summary only when it is greater than zero. A client that does not receive held_refused_claims should treat it as unknown, not as zero.
Each voucher row also carries redeem_at_trial (0/1), so the console's edit form can round-trip it — a flag a client cannot read would load as an unchecked box and be cleared on the next save.
GET /admin/v1/vouchers/{id}/redemptions returns the per-code redemption rows (id, voucher_id, account_email, tenant_id, credit_usd, dest, redeemed_at) that the admin console's redemptions view renders. account_email is personal data on a platform-admin-only surface, gated by the same VOUCHERS_MANAGE permission as the rest of this API. When an organisation is purged, its redemption rows are kept for 730 days as billing evidence with the account_email replaced by a non-reversible placeholder; they are not listed here, because the organisation they belong to no longer exists.
The admin console's voucher pages (/platform/vouchers/{id} with the redemptions, /platform/vouchers/{id}/edit) take the id from their address. There is no single-voucher read, so the page reads GET /admin/v1/vouchers and uses the row whose id equals the address exactly; any other value (unknown, differently cased, encoded path characters) shows "does not exist" and sends no further request. The redemptions are then read with the id of the row found, never with the raw address value.
POST /admin/v1/vouchers
Accepted body: { "code": string, "type": "unique"|"generic", "credit_usd": number, "max_redemptions"?: integer, "expires_at"?: integer|null, "redeem_at_trial"?: boolean }.
code— normalized to trimmed-uppercase^[A-Z0-9_!?.-]{4,64}$.type— exactly"unique"or"generic".credit_usd— a finite number in[0.01, 10000](absent:credit_usd_required; a string,nullor other non-number:invalid_credit_usd; an out-of-range number:credit_usd_range; aNaN/Infinity/1e999literal is refused earlier by the body parser withcode: "malformed_body"— a non-finite cap would disable the spend hard-stop). The admin UI sends the number it parsed strictly from the field:12.5and12,5are accepted; empty,1e3,1.500and10,000are refused in the form before any request.max_redemptions— integer in[1, 1000000]; ignored fortype:"unique"(forced to1).expires_at— optional unix-seconds integer at least 24 hours in the future (expires_too_soonotherwise), ornull/ omitted for never. PATCH applies the same rule to a suppliedexpires_at; an edit of only the credit does not re-check the stored expiry.redeem_at_trial— optional boolean, defaultfalse.trueopts the code into redemption at trial start (thepromodestination above) and requirestype:"generic"(any cap) ortype:"unique"withmax_redemptions1, a code of at least 11 characters, andcredit_usdin[1, 100]. A value that is present but not a boolean ("1",1,0,null, an object) is rejected, never read as absent: treating it as absent would ship the campaign not opted in while answering201, so an operator would believe a flag is set that is not.created_byis taken from the authenticated admin session, never the request body.
Response (201): { "id": string }.
Rejected (400 / 409): every validation rejection carries a stable machine-readable code next to the prose error — the sibling top-level convention in Error codes. The code is the consumer contract; the error string is the operator/log text and must not be parsed or shown to a user (the admin console keys its own localised, per-field message off the code).
The field codes follow the naming rule: an absent or empty field answers <field>_required, null or a wrong type invalid_<field>, a value over a length bound <field>_too_long and a number outside its bound <field>_range. Older servers answered code_format, type_invalid, credit_range, expires_not_integer, redeem_at_trial_invalid and, on a series, name_invalid, mask_invalid, count_invalid, credit_invalid, max_redemptions_invalid, expires_invalid, idem_key_invalid; a client should accept both spellings. The HTTP status, the error text and the accepted input are unchanged.
code |
status | meaning | field |
|---|---|---|---|
code_required |
400 | code is absent, empty or only whitespace |
code |
invalid_code |
400 | code is null, not a string, or not 4-64 chars of A-Z 0-9 _ - ! ? . after trim + uppercase |
code |
code_too_long |
400 | code is longer than 64 characters after trimming, or longer than 256 bytes before trimming (rejected outright, never trimmed) |
code |
type_required |
400 | type is absent or empty |
type |
invalid_type |
400 | type is not unique or generic |
type |
credit_usd_required |
400 | credit_usd is absent |
credit_usd |
invalid_credit_usd |
400 | credit_usd is null, not a number, or not finite |
credit_usd |
credit_usd_range |
400 | credit_usd is below 0.01 or above 10000 (a non-finite literal never reaches the route: malformed_body) |
credit_usd |
max_redemptions_required |
400 | max_redemptions is absent on a generic code |
max_redemptions |
invalid_max_redemptions |
400 | max_redemptions is null (generic), not a number, or fractional |
max_redemptions |
max_redemptions_range |
400 | max_redemptions is outside [1, 1000000] (for type:"generic") |
max_redemptions |
invalid_expires_at |
400 | expires_at is not a unix-seconds integer |
expires_at |
expires_past |
400 | expires_at is not in the future |
expires_at |
expires_too_soon |
400 | expires_at is less than 24 hours from now |
expires_at |
duplicate_code |
409 | a voucher with this code already exists |
code |
idem_key_conflict |
409 | series create: the idem_key already belongs to a series with different terms; nothing was written |
idem_key |
invalid_redeem_at_trial |
400 | redeem_at_trial is present but not a boolean |
redeem_at_trial |
trial_redeem_requires_unique |
400 | reserved on create: a unique code's cap is always forced to 1 and a generic code may opt in at any cap, so create never answers it today (PATCH answers it for a stored row whose type is neither generic nor unique with cap 1; the name is kept for compatibility) |
redeem_at_trial |
trial_redeem_entropy |
400 | redeem_at_trial with a code shorter than 11 characters |
code |
trial_redeem_credit_range |
400 | redeem_at_trial with credit_usd outside [1, 100] |
credit_usd |
A body that is not valid JSON never reaches the route (malformed_body); valid JSON that is not an object ([], "x", 7, null) is rejected 400 { "error": "request body must be a JSON object", "code": "malformed_body" }. A storage-fault 500 carries no code and the generic body 500 { "error": "internal error", "request_id": "…" }: an infrastructure failure is not the caller's input, and the driver detail is logged server-side under the request_id rather than returned. A storage fault on the voucher list or the redemption list (a read) answers 503 { "error": "temporarily unavailable; retry later" } (retry) instead.
Rejected (403): not a platform admin.
The admin console additionally refuses an expiry of today before it sends anything: such a voucher stops working at 23:59:59 the same evening and a voucher cannot be edited afterwards. That is a console rule, not an API one — this endpoint still accepts any future instant.
Audit. Creating, activating / deactivating, editing and deleting a voucher each commit together with their audit entry in one transaction: both are stored or neither is. A repeated toggle to the state the voucher already has, or an identical re-save, succeeds and writes exactly one audit entry. If the audit entry cannot be written, nothing is changed: the answer is 503 when nothing was written or the failure was transient (repeat the call), otherwise the sanitised 500 { "error": "internal error", "request_id": "…" }. The cause is logged, never returned.
PATCH /admin/v1/vouchers/{id}
PATCH does two jobs, and a request does one or the other.
Activation toggle — accepted body: { "active": boolean }. Deactivating a code makes it non-redeemable immediately (re-checked under the redemption lock, so it serializes correctly against an in-flight redeem).
Edit — accepted body: any of { "credit_usd": number, "max_redemptions": integer, "expires_at": integer|null, "redeem_at_trial": boolean }. Partial: only the keys present are written, so a campaign's cap can be raised without restating its credit. expires_at accepts an explicit null to clear the expiry (never expires), which is distinct from omitting the key (leave it untouched). redeem_at_trial takes a boolean only — a present-but-malformed value is rejected invalid_redeem_at_trial rather than silently ignored, and an explicit null is malformed here (the column is NOT NULL, so there is nothing to clear). credit_usd and max_redemptions are NOT NULL columns too, so an explicit null on either is refused (invalid_credit_usd / invalid_max_redemptions) rather than read as absent; the one exception is a unique voucher, where max_redemptions null or 1 is accepted as a no-op write of 1 (a unique voucher has exactly one legal value); null clears only expires_at. Any key outside active, credit_usd, max_redemptions, expires_at and redeem_at_trial (including code and type) is refused with 400 unsupported_field; the offending key is not echoed. A body that is not a JSON object (an array, a string, a number, a boolean, null) is refused 400 malformed_body when the handler reads the body (after the session check).
An activation toggle and a field edit in one body is rejected mixed_update: they are two separate storage writes whose partial-failure state no response shape could describe honestly.
The trial bounds are validated against the row the edit produces, under the row lock — not against the body. Editing any one of credit_usd, max_redemptions or redeem_at_trial therefore re-asserts all of them, which is what closes the bypass in both directions: flipping redeem_at_trial on a 1,000,000-redemption $10,000 generic code, and raising credit_usd on a code that is already opted in (a body that does not mention the flag at all), are the same defect. Turning the flag off is always allowed — it is the kill switch for a leaking campaign, so it must work even on a row that could never have been created through these validators.
code and type are not editable. The code is the identity a customer is already holding — the value printed on campaign material and the thing redemption records are about — and type drives the max_redemptions forcing rule, which has no coherent meaning to flip once redemptions exist. Both are create-time identity.
Editing money is safe on the past: voucher_redemption.credit_usd is snapshotted per row at redemption, so a later credit change affects only future redemptions.
The edit reuses the create endpoint's field validators, so the two cannot drift on what a legal voucher is. Rejected (400) with the same stable code values as create — invalid_credit_usd, credit_usd_range, invalid_max_redemptions, max_redemptions_range, invalid_expires_at, expires_past — plus these, which the edit path can produce on its own:
code |
Meaning |
|---|---|
max_redemptions_below_used |
the new cap is below the number of redemptions already granted — the row would read as over-redeemed and no counter could repair it |
max_redemptions_unique |
a unique voucher is always limited to one redemption; raising its cap would silently turn an invite code into a campaign one under the same name. Any number other than 1 answers this (0, a fraction, 2); only a non-number answers invalid_max_redemptions; null and 1 are accepted as a no-op |
unsupported_field |
the body carries a key that PATCH does not accept (for example code or type); nothing is written |
no_fields |
neither active nor any editable field was supplied |
invalid_active |
active is present but not a boolean (for example "false", 0 or null) — never read as "absent" |
mixed_update |
the body carries both active and a field edit |
invalid_redeem_at_trial |
the same code on create and on PATCH: one rule, one wire name. The route refuses the SHAPE before any DB work (as it does for active); storage re-asserts it, so a direct storage caller cannot bypass it. |
trial_redeem_requires_unique |
the resulting row would be trial-redeemable while unique with a cap other than 1 (or of an unknown type); generic is allowed at any cap |
trial_redeem_entropy |
the resulting row would be trial-redeemable with a code shorter than 11 characters |
trial_redeem_credit_range |
the resulting row would be trial-redeemable with credit_usd outside [1, 100] |
max_redemptions is validated against redemptions_used under a row lock, because that counter moves under concurrent redeemers — an unlocked read could let an edit slip the cap below what was already granted.
Success is 200 { "ok": true } for both jobs. Rejected (404): no such voucher — carries code not_found. Rejected (400): valid JSON that is not an object answers code malformed_body. Rejected (403): not a platform admin. A 500 returns a generic body — as on create, the driver detail is logged rather than returned, so it cannot end up in an operator's toast; a nil internal code is the hinge that separates an infrastructure 500 from a client-fixable 400.
DELETE /admin/v1/vouchers/{id}
Deletes a voucher that has never granted anything. voucher_redemption rows are money records, so a voucher with any redemption is deactivated (PATCH active=false), never deleted — tidying the campaign list must not be able to destroy an audit trail. This covers the real need: a typo'd or test code cluttering the catalogue. Success is 200 { "ok": true }.
The precondition is enforced server-side inside a transaction with the voucher row locked (FOR UPDATE), never trusted from the client and never read unlocked — a redemption landing between a check and the DELETE would otherwise orphan a redemption row against a deleted voucher. Both the counter and the presence of an actual redemption row are checked, so a counter that disagrees with the rows still refuses.
Rejected (409): { "error": …, "code": "has_pending_claims" } when a tenant holds the code as a pending trial claim (pending_voucher_code) — deleting it would break that customer's conversion; deactivate the voucher instead (PATCH active=false). Rejected (409): { "error": …, "code": "has_redemptions" } — the console keys its localised "deactivate it instead" message off this stable code, never the prose. Rejected (404): no such voucher — carries code not_found. Rejected (403): not a platform admin.
The console offers Delete on a row only when its redemption count, pending-claim count and held-refused-claim count are all known to be zero. A code that trial tenants still hold is never deletable here, even when the Pending column reads 0 because the holder's claim was refused (it is counted as held-refused); such a code is deactivated instead. If a claim lands after the list loaded, the 409 has_pending_claims above is shown as a localised message.