@krizaka/coupons
Discount and credit coupons the admin manages: reserved under a lock, confirmed once, released when unpaid, refunded; partners for attribution.
Install
npm install @krizaka/couponsAlso published as subpath exports: @krizaka/coupons/settings, @krizaka/coupons/testkit.
Discount and credit coupons the admin manages, for every Krizaka product (decision: ADR-002, design: coupons.md). The product's database is the source of truth; the payment provider applies a discount from immutable terms this module hands it; a credit coupon grants capped credits in @krizaka/credits. It evolves what exists: it does not start a second billing system.
A free offer is always a capped credit coupon, never a 100 % discount. A discount stops at 99.99 % and at the admin's
coupons.maxPercentOff; a fixed amount never runs forever and never exceeds that share of the price; a credit coupon always carries credits, an expiry and what happens when they run out.
Two kinds, one code (letters and digits, read without case, spaces or hyphens: « summer-2026 » is SUMMER2026):
- Discount: a percentage (basis points) or a fixed amount with its currency, a duration (
once,repeatingN months,forever), a plan scope and a minimum. Applied at checkout. - Credit:
creditsgranted, optionalcapPerDay/capPerMonth,creditsValidDays,onExhausted(stoporfallback_paid). Redeemed where the product redeems credits.
Both: startsAt / endsAt, maxRedemptions overall and maxPerAccount, newCustomersOnly, a purpose (partner, promo, demo, support) and, for a partner, the partner who sells with it.
import { createCoupons } from "@krizaka/coupons";
import { readCouponSettings } from "@krizaka/coupons/settings";
const coupons = createCoupons({ clock, settings: () => readCouponSettings((key) => settings.get(key)), audit, rateLimit: limiter, credits, outbox });
// 1. the person types the code in « Code promo » (read-only; counts one attempt on the limiter, before any lookup)
const v = await coupons.validate(query, typed, { mode: "checkout", accountId, plan: "pro", amountMinor: 3900, currency: "cad", hasPaidBefore });
// v = { ok: true, effect: { discountMinor, payableMinor, … } } or { ok: false, code: "COUPON_EXPIRED" }
// 2. « Pay »: three steps, NO network call inside a transaction or under the coupon's row lock
const applied = await transaction(connect, (tx) => coupons.apply(tx, { code: typed, accountId, plan: "pro", amountMinor: 3900, currency: "cad", idempotencyKey: attemptId })); // reserves a use
const session = await payments.checkout({ …, discount: applied.discount, idempotencyKey: applied.redemptionId, metadata: { redemption_id: applied.redemptionId }, expiresAt }); // @krizaka/payments
await transaction(connect, (tx) => coupons.attachCheckout(tx, applied.redemptionId, session.checkoutRef, session.expiresAt));
// if the session fails: coupons.release(tx, { redemptionId })
// 3. the payment webhook, in the event's transaction (applyOnceInTransaction of @krizaka/payments)
payment_paid: (e, tx) => coupons.redeem(tx, { redemptionId: e.metadata.redemption_id, checkoutRef: e.checkoutRef, paymentRef: e.paymentRef ?? e.invoiceRef, amountPaidMinor: e.amountTotal, amountDiscountMinor: e.amountDiscount, currency: e.currency })
checkout_expired: (e, tx) => coupons.release(tx, { checkoutRef: e.checkoutRef })
payment_refunded: (e, tx) => coupons.refund(tx, { paymentRef: e.paymentRef, invoiceRef: e.invoiceRef, amountRefunded: e.amountRefunded })
// a credit code: the same rules, then a capped grant in the same transaction
await transaction(connect, (tx) => coupons.redeemCredit(tx, { code: typed, accountId, idempotencyKey: attemptId }));The rules
- A use is counted by one rule: a redemption is a use when it is
confirmedorrevokedand notuse_restored, orreservedand not past its deadline. Areleasedone never counts. The overall and the per-account limits both apply it. « Expired », « exhausted » and « not started » are computed, so no cron is needed. - Reserve, confirm, release.
applylocks the coupon row (SELECT … FOR UPDATE), re-checks everything, inserts areservedredemption with a deadline (coupons.reservationMinutes) and commits: two requests for the last use give it to one (tested on PostgreSQL, 50 rounds).redeemruns in the payment event's transaction; its guarded transition (UPDATE … WHERE status IN ('reserved', 'released')) and the uniquepayment_refmean a use is confirmed once whatever the number of deliveries. The webhook finds the reservation bymetadata.redemption_ideven ifattachCheckoutnever ran. - A late payment is honoured. A payment for a released or lapsed reservation is confirmed anyway and flagged
over_limit: the customer paid the discounted price in good faith. It is audited and shown in the admin. - Refunds add up (the amount is cumulative) and never change the status. A partial refund keeps the use; a full one gives it back only when
coupons.refundRestoresUseis on (default off), so a refund cannot reset a single-use code. - Terms are immutable once anyone has used the coupon (
COUPON_TERMS_LOCKED): the provider's object is made from them, pertermsVersion. Dates, limits, plans, status and partner stay editable. When a plan's price changes,admin.checkPrices(prices)pauses the fixed-amount coupons that would now exceed the bound. - Taxes are the provider's. The terms go to
@krizaka/payments, whose adapter sends the discount together withautomatic_tax: Stripe Tax computes GST and QST on the discounted amount. The numbers ineffectare informational. No tax is written here. - Abuse.
validate,applyandredeemCrediteach count one attempt on the limiter (COUPON_ATTEMPT_ACTION, limitscoupons.attemptsPerAccountPerHour/attemptsPerIpPerHour) before any lookup; past the limit they answerCOUPON_RATE_LIMITEDwithretryAfterSeconds. - Refusals are typed (
COUPON_CODE):UNKNOWN,NOT_STARTED,EXPIRED,PAUSED,EXHAUSTED,ACCOUNT_LIMIT,NEW_CUSTOMERS_ONLY,NOT_FOR_PLAN,MINIMUM,CURRENCY,TOO_LARGE,KIND,PROVIDER,RATE_LIMITED,DISABLED.CouponErrorcarries the code and the HTTPstatus(404, 422, 429…).
Partners (Loi 25)
A partner is a person who sells for us: a display name and an optional e-mail, for one purpose (attributing sales), visible to the admin only. admin.partners.report gives, per coupon and currency, the redemptions, the discount given, the revenue (paid minus refunded) and the credits granted, never a customer's identity; every read is audited. export returns the record and its aggregates; erase blanks the name and the e-mail and keeps the aggregates (the redemptions are accounting records). Commission is out of scope: the hook is evt.coupon.redeemed.v1, which carries partnerId, the amounts and the credits, for a later module to consume from the outbox.
What you provide, what it gives
- Dependencies are structural ports, so this package imports none of them:
audit(createAuditof@krizaka/audit),rateLimit(createLimiterof@krizaka/rate-limit),credits(createCreditsof@krizaka/credits),outbox(createOutboxof@krizaka/outbox). - Events through the outbox, in the caller's transaction, ids derived from the fact:
evt.coupon.redeemed.v1,evt.coupon.released.v1,evt.coupon.refunded.v1,evt.coupon.exhausted.v1, with a JSON Schema each (COUPON_EVENT_SCHEMAS). - Settings (
@krizaka/coupons/settings, every change audited by the settings service):coupons.enabled(off),reservationMinutes(60, 40–1440: the provider's session window),attemptsPerAccountPerHour(10),attemptsPerIpPerHour(30),minCodeLength(8),generatedCodeLength(10),maxPercentOff(50, 1–99: the default is Oussama's call, krizaka-ts#61),refundRestoresUse(off).credits.timeZoneis@krizaka/credits'. Nothing new in the environment: the provider keys stayPAYMENTS_*. - Tables (
couponsSchema, Postgres schemacoupons):partner,coupon,redemption, with CHECKs that repeat the rules (a free discount cannot be stored). A deleted account leaves its redemptions (ON DELETE SET NULL). couponsContract(@krizaka/coupons/testkit) is the contract every store runs;memoryCouponStore()is for unit tests (it locks nothing: concurrency is proved on PostgreSQL).
Going live
The code runs against the provider's test mode only. Turning coupons on in live mode, product by product, is the owner's call (krizaka-ts#61), and so are the retention of the redemption records and the tax status of free credits (krizaka-ts#62, for the accountant): nothing here assumes either.
Exports
The 69 names the package exports, read from its types.
| Name | Kind | What it is |
|---|---|---|
Actor | type | Who acts (for the audit trail). |
Applied | type | |
ApplyInput | type | |
AuditPort | type | The trail (@krizaka/audit's Audit), structurally. |
CheckoutContext | type | What the person typed and where they are: a checkout (discount codes) or a place that redeems credits (credit codes). |
Clock | type | |
countsAsUse | function | Whether a redemption consumes a use at now: confirmed or revoked and not restored, or reserved and not yet past its deadline. |
Coupon | type | |
COUPON_ATTEMPT_ACTION | constant | The action name of the limiter for attempts with a code: each validate, apply and redeemCredit counts one hit. |
COUPON_BOUNDS | constant | [min, max] of each numeric setting. |
COUPON_CODE | constant | The refusals of validation and redemption (typed, as const). |
COUPON_DEFAULTS | constant | Defaults and bounds of the settings (the admin changes them without a redeploy). |
COUPON_ERROR | constant | The errors of the admin and of the flows (not refusals of a customer's code). |
COUPON_EVENT | constant | |
COUPON_EVENT_SCHEMAS | constant | The JSON Schema of each event's payload. |
COUPON_STATUS | constant | Stored states. |
COUPON_STATUS_CODE | constant | The HTTP status a route may answer for each refusal or error. |
CouponAdmin | type | |
CouponError | class | A refusal thrown by a flow (apply, redeemCredit): a stable code, the HTTP status, and retryAfterSeconds for a rate limit. |
CouponErrorCode | type | |
CouponFilter | type | |
CouponPatch | type | What a coupon's terms and rules may be changed to (the admin's update). |
CouponRefusal | type | |
Coupons | type | The coupons of a product (ADR-002 §5.1). |
COUPONS_TOPIC | constant | The topic the coupons' events are appended to on the outbox. |
CouponsDeps | type | |
CouponSettings | type | The knobs of the module, read from the admin's settings (@krizaka/coupons/settings). |
couponsSchema | constant | The tables of « coupons » (ADR-002), in their own Postgres schema: partner (a person who sells for us: a name and an optional e-mail, erasable), coupon (… |
CouponStatus | type | |
CouponStore | type | Where coupons live. |
CouponView | type | The coupon as a checkout shows it. |
createCoupons | function | The coupons of a product. |
CreditEffect | type | |
CreditRedemption | type | |
CreditsPort | type | The credits ledger (@krizaka/credits' Credits), structurally. |
dbCouponStore | function | The PostgreSQL store of coupons, in schema coupons (see couponsSchema), over the Query it is given: the caller's transaction, so the work commits or ro… |
DiscountEffect | type | |
DiscountTerms | type | The terms a provider adapter needs to apply a discount: vendor-free, IMMUTABLE per (couponId, termsVersion) (@krizaka/payments' DiscountTerms). |
Duration | type | |
DURATION | constant | |
effectOf | function | What a code gives, in numbers. |
generateCode | function | A random code of length characters from an alphabet without I, L, O, U (about 5 bits each). |
Kind | type | |
KIND | constant | |
memoryCouponStore | function | An in-memory store, for unit tests and demos: the same behaviour as the database's (the contract kit runs on both) except that forUpdate locks nothing, bec… |
NewCoupon | type | What the admin gives to create a coupon (the kind decides which terms are required). |
normalizeCode | function | The lookup key of a code: upper case, without spaces, hyphens or underscores, so « summer-2026 », « SUMMER 2026 » and « Summer2026 » are one code. |
ON_EXHAUSTED | constant | |
OnExhausted | type | |
OutboxPort | type | The outbox (@krizaka/outbox's Outbox), structurally. |
Partner | type | |
PartnerInput | type | |
PartnerRow | type | One row of the partner view: a coupon's uses in a period, in one currency. |
Purpose | type | |
PURPOSE | constant | Why the coupon exists: a person who sells for us, a public promotion, a demo, a support gesture. |
Query | type | |
RateLimitPort | type | The limiter (@krizaka/rate-limit's Limiter), structurally. |
RedeemInput | type | |
Redemption | type | |
REDEMPTION_STATUS | constant | |
RedemptionFilter | type | |
RedemptionPatch | type | What a guarded update may change. |
RedemptionStatus | type | |
refusalOf | function | The first rule a code breaks for a context at now, or none. |
SYSTEM | constant | The system as an actor (a webhook, a sweeper). |
termsOf | function | The immutable terms a provider adapter turns into its object. |
Usage | type | |
uuidOf | function | A stable UUID (version 5 shaped) from a seed: the same fact announced twice is one outbox message. |
Validation | type |
@krizaka/coupons/settings
| Name | Kind | What it is |
|---|---|---|
COUPON_ATTEMPT_ACTION | constant | The action name of the limiter for attempts with a code: each validate, apply and redeemCredit counts one hit. |
couponAttemptLimit | function | |
couponSettings | constant | The settings of « coupons », a fragment the product adds to its registry (@krizaka/coupons/settings): the admin changes them without a redeploy, every chan… |
readCouponSettings | function | The module's settings as createCoupons takes them, from the product's accessor ((key) => service.get(key, ctx)). |
@krizaka/coupons/testkit
| Name | Kind | What it is |
|---|---|---|
COUPON_DEFAULTS | constant | Defaults and bounds of the settings (the admin changes them without a redeploy). |
couponsContract | function | What every coupons store must do, behind the same module: the window and the refusals, the counting rule of the uses, reservation, confirmation and release,… |
CouponsHarness | type | What a store (through the module) is run against: the module on that store, a clock the test moves, and fakes for its neighbours. |
credit | function | 20 free audits, at most 5 a day, valid 30 days. |
discount | function | A discount of 20 % for three months on a monthly plan. |
T0 | constant | Midday on 26 October 2026 in Toronto: the day the scenarios start on. |
Package
| Version on npm | 0.1.3 (npm) |
| Licence | Apache-2.0 |
| Node.js | >=22 |
| Dependencies | @krizaka/db workspace:^, @krizaka/settings workspace:^, @krizaka/time workspace:^ |
| Peer dependencies | vitest >=4, zod >=3.23 |
| Source | coupons |
Changelog
0.1.3
Patch changes
- Updated dependencies [2a7898c]
- Updated dependencies [2272b57]
- @krizaka/[email protected]
- @krizaka/[email protected]
0.1.2
Patch changes
- Updated dependencies [0d19b64]
- @krizaka/[email protected]
- @krizaka/[email protected]
0.1.1
Patch changes
- Updated dependencies [8210a9a]
- @krizaka/[email protected]
0.1.0
Minor changes
- New package (#46, ADR-002):
@krizaka/coupons, discount and credit coupons the admin manages.createCoupons(validate,applyreserving a use under the coupon's row lock,attachCheckout,redeemin the payment event's transaction,release,releaseExpired,refund,redeemCreditgranting capped credits in@krizaka/credits,revoke, andadmin: coupons, partners and their view,checkPrices,generateCode),couponsSchema(coupons.partner,coupons.coupon,coupons.redemption),dbCouponStore,memoryCouponStore,@krizaka/coupons/settings(coupons.enabled,reservationMinutes,attemptsPerAccountPerHour,attemptsPerIpPerHour,minCodeLength,generatedCodeLength,maxPercentOff,refundRestoresUse),evt.coupon.redeemed.v1,released,refunded,exhaustedthrough the outbox, andcouponsContract. Going live, the retention of the records and the tax status of free credits are the owner's and the accountant's calls (#61, #62).