Documentation menu
Documentation / Commerce engine / affiliates
Affiliates
npm install @wabbit/tome-affiliatesFirst install from our registry?
Get a registry token from your credentials page. You need a purchase that includes this package, or a Craft Library membership.
Add the registry and your token to the
.npmrcat the root of your project, with your token in place ofYOUR_TOKEN:@wabbit:registry=https://npm.wabbit.com/ //npm.wabbit.com/:_authToken=YOUR_TOKEN
Tome affiliates layer — referral attribution by link and promotion code, commission snapshots held through the refund window, refund reversal with carry-forward, and payouts through the economy payouts extension.
Overview
Tome affiliates layer — referral attribution by link and promotion code, commission snapshots held through the refund window, refund reversal with carry-forward, and payouts through the economy payouts extension. Description copied verbatim from package.json.
Layer: domain (per the repo's ARCHITECTURE.md § The Layer Model).
An approved affiliate gets a code, a share link, and optionally a Stripe promotion code. The layer attributes referred purchases and subscription renewals to that affiliate, computes a commission snapshot per sale, holds it through the refund window, reverses it on refund, and batches approved commissions into payouts via @wabbit/tome-economy's payouts extension. From 0.7.0 it can also attribute a sale to a lead your site tracks (a partner brings in a business that pays in several pieces), group partners into tiers, and take a renewal's referral from a resolver your site supplies. From 0.8.0 a program can also keep the terms of a written partner agreement: work agreed inside a lead's window finishes earning, ending or pausing a partner is a recorded operation with a policy for unpaid money, the renewal cap can count a first period paid as an order and only payments kept, part of a charge can be left out of commission, and payments made before a late confirmation can be credited (see Partner terms). All of that is opt-in. It ships no end-user UI in v1 — each consumer builds its own affiliate dashboard in its own design system.
Peer dependencies
Peer ranges, copied from package.json:
| Peer | Range |
|---|---|
payload | >=3.67.0 |
@wabbit/tome-core | >=1.17.0 <2.0.0 |
@wabbit/tome-economy | >=0.20.0 <1.0.0 |
@wabbit/tome-economy must be installed with its payouts extension enabled (createEconomyLayer({ payouts: true })) — assertEconomyPayoutsCollections (below) fails loudly from your onInit if it is not. stripe is not a peer at any level: nothing in this package imports it. syncAffiliatePromotionCode accepts a structural stripe argument shape instead, matching crowdfund's settlement-job pattern.
Quickstart
Four pieces of wiring, all required. The layer factory alone gives you collections and a click endpoint that records clicks; commissions are only computed once the economy handlers are registered, and only approved and paid out once the jobs are mounted and scheduled.
import { buildConfig } from 'payload'
import { createEconomyLayer } from '@wabbit/tome-economy'
import {
createAffiliatesLayer,
resolveAffiliatesConfig,
type AffiliatesLayerConfig,
} from '@wabbit/tome-affiliates'
import { assertEconomyPayoutsCollections, setAffiliatesPayloadResolver } from '@wabbit/tome-affiliates/server'
const affiliatesConfig: AffiliatesLayerConfig = {
program: {
currency: 'USD',
defaultRateBps: 2000, // 20%
commissionableProductTypes: ['course', 'membership'],
recurringMonths: 6,
attributionWindowDays: 30,
holdDays: 30,
minPayoutCents: 2500,
},
currentTermsVersion: '1',
// Both secrets must be at least 32 characters, or the factory throws AffiliatesConfigError.
cookieSecret: process.env.AFFILIATE_COOKIE_SECRET!,
clickHashSecret: process.env.AFFILIATE_CLICK_HASH_SECRET!,
}
const affiliates = createAffiliatesLayer(affiliatesConfig)
// 1. Economy event handlers: order completed, subscription renewed, order refunded.
// Without this call no referral is ever attributed and no commission is created. Idempotent.
affiliates.registerHandlers()
export default buildConfig({
// db, secret, editor, admin: as in any Payload config
collections: [
...createEconomyLayer({ payouts: true }), // 2. the payouts extension is required
...affiliates.collections,
// ...your other collections
],
endpoints: [
...affiliates.endpoints, // POST /api/affiliates/click
...affiliates.jobs.map((job) => job.endpoint), // 3. the four CRON_SECRET-guarded job routes
],
onInit: async (payload) => {
// 4. Fail at boot, not at the first sale, if economy's payouts collections are missing.
assertEconomyPayoutsCollections(payload, resolveAffiliatesConfig(affiliatesConfig))
// The handlers receive no Payload instance of their own. Either pass `getPayload`
// in the layer config, or hand them this one:
setAffiliatesPayloadResolver(() => payload)
},
})How the routes are reached. Payload sends /api/<collection slug>/... to that collection's own endpoints only, never to the root endpoints list. The layer's affiliates collection therefore carries forwarders for /click and /jobs/:job that hand the request, untouched, to whatever you mounted at root under the same path. A route you did not mount still answers 404, and each root handler keeps its own guard (the signature for the click, CRON_SECRET for jobs). Nothing changes for you: mount the endpoints as shown above. If you rename the affiliates slug, the root routes are reachable directly and no forwarders are added.
Scheduling the jobs. Each entry of affiliates.jobs is { slug, schedule, handler, endpoint }. The endpoint is a Payload endpoint guarded by the CRON_SECRET environment variable: set CRON_SECRET, then have your scheduler POST to it with Authorization: Bearer <CRON_SECRET>. It answers 500 when CRON_SECRET is unset and 401 on a wrong token. schedule is the suggested cron expression; nothing registers it for you. On Payload's own jobs queue, wrap handler with asPayloadTask from @wabbit/tome-core/jobs instead of mounting the endpoint.
Job (slug) | Route (under /api) | Suggested schedule | What it does |
|---|---|---|---|
approveMaturedAffiliateCommissions | /affiliates/jobs/approve-matured-commissions | 15 3 * * * | Approves pending commissions whose hold has passed; reverses those whose order was fully refunded. |
runAffiliatePayouts | /affiliates/jobs/run-payouts | 0 15 1 * * | Batches approved commissions into payouts through the registered payout rails. Holds payees without a tax form when requireTaxFormBeforePayout is on. |
expireAffiliateReferrals | /affiliates/jobs/expire-referrals | 30 3 * * * | Expires open referrals past the attribution window and, when lead referrals are on, pending leads older than pendingExpiryDays. |
purgeAffiliateClicks | /affiliates/jobs/purge-clicks | 45 3 * * * | Purges old click rows. |
The referral cookie. captureReferral sets a signed cookie named program.cookieName (default tome_ref) with a lifetime of program.attributionWindowDays days. Rotating cookieSecret invalidates every cookie already issued.
API surface
Root entry (@wabbit/tome-affiliates, . in exports) — config-graph safe, no Node-only imports:
| Export | What it is |
|---|---|
createAffiliatesLayer(config) | Canonical layer entry. Returns { collections, endpoints, jobs, registerHandlers } and registers the layer. |
resolveAffiliatesConfig(config) | Applies every default (AFFILIATES_DEFAULT_SLUGS, economy slug defaults, program defaults) — the shape every collection/handler/job factory is built against. |
AFFILIATES_DEFAULT_SLUGS | affiliates / affiliate-referrals / affiliate-clicks / affiliate-commissions. |
AFFILIATES_LEADS_DEFAULTS | The program.leads defaults (enabled: false, claimWindowDays: 90, pendingExpiryDays: 30, earningMonths: 12, maxPendingPerAffiliate: 25). |
AFFILIATES_LAYER_VERSION (also standalone at @wabbit/tome-affiliates/version) | Pinned to package.json by a test. |
AFFILIATES_PARTNER_TERMS_DEFAULTS | The defaults of the four partner-terms options: paymentWindow: 'hard-stop', terminationPolicy: 'void-pending', pausePolicy: 'stop-earning', renewalCapCounts: 'every-commission'. Each is the 0.7.0 behavior. |
AFFILIATES_REASON_MAX_LENGTH | 2000: the longest reason the lifecycle operations and withdrawLeadReferral accept, after trimming. |
AFFILIATES_TERMINATION_CONTEXT | 'affiliatesTermination', the req.context flag terminateAffiliate sets on its status write; under terminationPolicy: 'honor-earned' the collection refuses a move to terminated without it. From 0.11.0 the re-open writes of applyForAffiliate and inviteAffiliate carry it too. |
AFFILIATE_ENDING_KINDS | 0.11.0: every AffiliateEndingKind ('partner', 'inactivity', 'cause', 'without-cause', 'program-closed', 'rejected-change'); see Partner revision. |
AffiliatesConfigError | Thrown by resolveAffiliatesConfig on any missing or invalid required field, and by a renewal whose resolver returns a priorCappedPeriods or basisCents that is not valid. |
AffiliatesOperationRefusedError | Thrown by an operation when a well-formed call is not allowed in the current state or under the program's policy (code: 'affiliates-operation-refused'). Nothing is written. From 0.9.0 a refusal may carry a stable reason (AffiliatesRefusalReason; see Refusal reasons). |
AFFILIATES_ADMIN_CAPABILITY | The capability string ('affiliates:admin') checked by every admin-only access rule. |
| Types | AffiliatesLayerConfig, ResolvedAffiliatesConfig, AffiliateProgramConfig, AffiliatesSlugs, AffiliateStatus, AffiliateApplicationAnswer, ReferralChannel, ReferralStatus, ReferralRejectionReason, CommissionStatus, CommissionSource, CommissionReversalReason, CommissionBasisContext, ReferralCookiePayload, AffiliateDashboard, AffiliateDashboardCommission, AffiliateJobConfig, JobHandler, AffiliatesLayer, and, new in 0.7.0, AffiliateLeadsConfig, AffiliateTierConfig, RenewalAttributionContext, RenewalAttribution, AffiliateLead; new in 0.8.0, the option types AffiliatePaymentWindow, AffiliateTerminationPolicy, AffiliatePausePolicy, RenewalCapCounting, the refund hook types CommissionableRefundContext and UnresolvedRefund, AffiliateStanding, PausedPayoutHold, ReverseCommissionAmountOption, EarlierPayment, EarlierPaymentSkipReason, and the argument and result types of the partner-terms operations (TerminateAffiliateArgs, TerminateAffiliateResult, SettleWithheldCommissionArgs, PauseAffiliateArgs, ResumeAffiliateArgs, WithdrawLeadReferralArgs, ApproveManualPayoutRailArgs, CreditEarlierPaymentsArgs, CreditEarlierPaymentsResult), which @wabbit/tome-affiliates/server re-exports beside the operations; new in 0.9.0, AffiliatesRefusalReason and InviteApplicantArgs (also re-exported from /server); new in 0.11.0, AffiliateEndingKind and AffiliateSignedTerms (also re-exported from /server). The @wabbit/tome-affiliates/server subpath also exports the argument types of its operations (InviteAffiliateArgs, ApproveAffiliateArgs, RejectAffiliateArgs, ReleaseFirstPayoutArgs, ReverseCommissionArgs, SyncAffiliatePromotionCodeArgs, RotateAffiliatePromotionCodeArgs, ApplyForAffiliateArgs, AcceptAffiliateTermsArgs, StartPayoutOnboardingArgs, and one args type per lead operation: RegisterLeadArgs, CaptureLeadFromCookieArgs, CreateLeadReferralArgs, ConfirmLeadReferralArgs, DeclineLeadReferralArgs, ExtendLeadReferralArgs, FindLeadReferralArgs, GetAffiliateLeadsArgs), plus LeadDeclineReason, FoundLeadReferral, HeldPayout, RunAffiliatePayoutsSummary, CapCountedCommission and CreditableReferral. |
@wabbit/tome-affiliates/server subpath (@wabbit/tome-affiliates/server) — Node-only helper surface:
| Export | What it is |
|---|---|
isAffiliatesAdmin(req) | Admin-capability check (sessionHasCapabilityOrLegacyAdmin). |
assertEconomyPayoutsCollections(payload, cfg) | Throws AffiliatesConfigError from your onInit/job if economy's Orders or payouts-extension collections are missing. |
signReferralCookie / verifyReferralCookie | Signed referral cookie codec. |
hashVisitor | Daily-rotating HMAC visitor hash for affiliate-clicks. |
captureReferral / bindReferralToMember / resolveCheckoutAttribution | Middleware and checkout attribution helpers. |
createAffiliateClickEndpoint(cfg) | The POST /affiliates/click endpoint factory. A repeat from the same visitor for the same affiliate within CLICK_REPEAT_WINDOW_MS (10 seconds) is answered 204 and recorded as one click. |
createSignedClickBody(input, secret, now?) | Builds the signed JSON body a consumer's recordClick POSTs to the click endpoint. |
registerAffiliateHandlers(cfg) | Registers the order/subscription/refund economy handlers. They reach Payload through AffiliatesLayerConfig.getPayload. |
setAffiliatesPayloadResolver(resolver) | Fallback for consumers that cannot pass getPayload: call it from onInit(payload). |
createAffiliateJobs(cfg) | The four scheduled jobs (approve, payout, expire, purge) — the same array as createAffiliatesLayer(...).jobs. Their handlers return ApproveMaturedCommissionsSummary, ExpireReferralsSummary (gains expiredPendingLeads in 0.7.0) and PurgeClicksSummary. |
registerAffiliatePayoutAdapters(adapters) / getAffiliatePayoutAdapters() / runAffiliatePayouts(args) | Register economy payout rails at boot; run the monthly payout batch over approved commissions. Returns RunAffiliatePayoutsSummary, which carries heldForTaxForm when the tax-form gate is on, heldForPause under pausePolicy: 'hold-payouts', and finalBatch when a run under terminationPolicy: 'honor-earned' paid an ended partner (see Partner terms). |
getAffiliateDashboard | Affiliate-facing aggregate query — never leaks buyer identity. Returns AffiliateDashboard (code, share URL, click/referral/conversion counts, pending/approved/paid/reversed cents, payout-account status, tier when the program has tiers, and withheldCents under terminationPolicy: 'honor-earned') with recentCommissions: AffiliateDashboardCommission[] (createdAt, source, amountCents, status only). |
inviteAffiliate | Admin: creates an invited affiliate row for a member (see Tiers). |
inviteApplicant | Admin, since 0.9.0: moves an applied row to invited so the applicant can sign, stamping applicationApprovedAt and applicationApprovedBy (see Payout guards and approving applications). |
taxFormStatusPays(status) | 0.9.0: the tax-form gate's payable rule, for your own previews (see Tax-form gate). |
approveAffiliate / rejectAffiliate / releaseFirstPayout / reverseCommission / syncAffiliatePromotionCode | Admin operations. approveAffiliate takes an optional tier. reverseCommission takes an optional amountCents for a proportional reversal (see Partner terms). |
approveManualPayoutRail | Admin: allows the hand-run payout rail for one affiliate, stamping manualPayoutApprovedBy and manualPayoutApprovedAt (see Payout rails are opt-in, not fallbacks). |
registerLead / captureLeadFromCookie / createLeadReferral / confirmLeadReferral / declineLeadReferral / extendLeadReferral / findLeadReferral / getAffiliateLeads / withdrawLeadReferral | Lead referral operations (see Lead referrals). |
terminateAffiliate / releaseWithheldCommission / voidWithheldCommission / pauseAffiliate / resumeAffiliate | Ending and pausing a partner, and settling withheld commissions (see Partner terms). |
creditEarlierPayments | Admin: credits payments made before a lead's late confirmation, once each, under the live rules (see Partner terms). |
affiliateStanding(cfg, status, runOff?) / countsTowardCap(cfg, commission) / earliestCreditablePaymentAt(referral) | Pure rules for your own code: what a partner in a status may do (pass { runOffUntil, now? } from 0.11.0 to include a run-off), whether a commission's payment uses a place in the renewal cap, and the earliest payment a late credit may include. |
addCalendarMonths(date, months) | UTC calendar-month addition used for earnsUntil; clamps to the last day of a shorter month. |
rotateAffiliatePromotionCode(args) | Replaces a leaked promotion code: deactivates the current code in Stripe first, then mints one with different text (newCodeText, 3-40 letters, digits or dashes) and links it to the affiliate. Returns { deactivated, id, code }. If the mint fails, run syncAffiliatePromotionCode again. Past orders keep their commissions. |
endedReapplyEligibleAt(cfg, row) | 0.11.0: the date an ended partner may apply again under program.reapplyAfterEnding, or null for invitation only (see Partner revision). |
applyForAffiliate / acceptAffiliateTerms / startPayoutOnboarding | Plain async consumer-facing server actions — not Next.js server-action wrappers; wrap them yourself. acceptAffiliateTerms requires a signer (see Signing the agreement); startPayoutOnboarding's country is optional and read from the affiliate row. Its optional productDescription (one plain sentence on what the partner does for the program, written by you) is passed to the rail adapter with the payee the affiliate signed as (an individual's name, or a business's legal name only); an adapter uses both only when it creates the rail account. |
Lead referrals
A lead referral is an affiliate-referrals row bound to a lead your site tracks (a deal, an opportunity, a job) instead of to a member who checks out. The layer holds a label and an opaque externalRef; what the reference points at, and what stage it is in, belongs to your site. Use lead referrals when a partner brings in a business and the sale is paid in several pieces. Link and promotion-code referrals are unchanged.
The layer stores only a label (up to 120 characters) and a note (up to 1000) for a lead. A prospect's name, email and phone number stay in your own records and are never written to an affiliates collection. The label and note are exported with the affiliate's data and scrubbed on erasure by the layer's GDPR registration.
Lead referrals are off by default. Turn them on with program.leads:
import type { AffiliateProgramConfig } from '@wabbit/tome-affiliates'
const program: AffiliateProgramConfig = {
currency: 'USD',
defaultRateBps: 1000,
commissionableProductTypes: ['service'],
recurringMonths: 0,
attributionWindowDays: 30,
holdDays: 30,
minPayoutCents: 5000,
leads: {
enabled: true,
claimWindowDays: 90, // an open lead with no commission expires after this
pendingExpiryDays: 30, // an unconfirmed registration expires after this
earningMonths: 12, // orders and renewals earn this long after confirmation; 0 = no limit
maxPendingPerAffiliate: 25, // pending registrations one partner may hold
},
}The numbers shown are the defaults (AFFILIATES_LEADS_DEFAULTS at the root entry). enabled defaults to false, and every lead operation throws while it is off. Every number must be a positive integer, except earningMonths, which may be 0.
Life cycle
| Status | Meaning |
|---|---|
pending | Registered by a partner, or captured from a link, and not yet confirmed. Never earns. |
open | An admin confirmed it. expiresAt is confirmedAt + claimWindowDays; earnsUntil is confirmedAt + earningMonths calendar months, or empty when earningMonths is 0. |
converted | The first commission was written. The referral keeps earning on every order or renewal that names it until earnsUntil, and never expires. |
expired | A pending lead older than pendingExpiryDays, or an open lead past expiresAt with no commission. |
rejected | An admin declined it (existing-relationship, duplicate or admin) or removed it. |
A lead referral's channel is registered when a partner or admin registered it, and link when captureLeadFromCookie created it from a partner's link.
Operations
All are plain async functions exported from @wabbit/tome-affiliates/server, not REST endpoints (affiliate-referrals still has no public create). Authorize the caller yourself before calling the partner and consumer operations. Admin operations take the admin's req or system: true, plus actor (the admin user id).
| Operation | Who calls it | What it does | |
|---|---|---|---|
registerLead({ payload, cfg, memberId, label, note?, externalRef? }) | the partner, through your server action | Creates a pending referral for the member's active affiliate row. Throws when the member has no active affiliate row or already holds maxPendingPerAffiliate pending leads. Returns { referralId }. | |
captureLeadFromCookie({ payload, cfg, cookieValue, label, externalRef }) | your form or intake hook | Verifies the signed referral cookie and creates a pending link referral. Returns null (never throws) when the cookie is absent, invalid, past the attribution window, or names an affiliate that is not active. Idempotent on externalRef. The pending cap does not apply. | |
createLeadReferral({ payload, cfg, affiliateId, label, externalRef, actor }) | admin | Creates the referral directly in open, for a lead the admin tags by hand. | |
confirmLeadReferral({ payload, cfg, referralId, actor, externalRef? }) | admin | pending to open. Needs an externalRef, passed here or already on the row. Throws a message containing already-attributed when another open or converted referral holds the same externalRef. | |
declineLeadReferral({ payload, cfg, referralId, actor, reason }) | admin | pending to rejected. reason is a LeadDeclineReason. | |
extendLeadReferral({ payload, cfg, referralId, expiresAt }) | admin or your server code | Moves expiresAt on an open lead so a claim does not lapse mid-sale. With no actor, req or system it runs as trusted server code; with any of them it is checked as an admin call. expiresAt must be in the future. | |
findLeadReferral({ payload, cfg, externalRef }) | your server code, when it creates an order | Returns FoundLeadReferral, { referralId, affiliateId, affiliateCode, status }, for the open or converted referral holding that reference, or null (also null when its affiliate is not active). Under pausePolicy: 'hold-payouts' a paused affiliate's referral is returned too, and the result carries `affiliateStatus: 'active' \ | 'paused'`. |
withdrawLeadReferral({ payload, cfg, referralId, actor, reason }) | admin | Withdraws a confirmed claim that has earned nothing: an open lead referral moves to rejected with rejectionReason: 'admin', stamping withdrawnAt, withdrawnBy and withdrawalReason. Refused, writing nothing, for a pending lead (use declineLeadReferral), a converted one or any referral a commission row names, and an expired or rejected one. No commission, payout or other referral is touched, and the externalRef is free for another claim. | |
getAffiliateLeads({ payload, cfg, memberId, page?, limit? }) | the partner, through your server action | The partner's own leads, newest first: { leads: AffiliateLead[], page, totalPages, totalDocs }. Page size defaults to 25, at most 100. |
There is no reassign operation: to move a lead, an admin rejects the first referral and creates another, so both decisions stay on record.
Orders must name the referral
A lead referral earns only on an order that names it. The layer never guesses from the customer, because on a proposal order the customer is often not a member. When your site creates an order for a lead, look the referral up and stamp it:
import type { Payload } from 'payload'
import type { ResolvedAffiliatesConfig } from '@wabbit/tome-affiliates'
import { findLeadReferral } from '@wabbit/tome-affiliates/server'
export async function referralMetadata(
payload: Payload,
cfg: ResolvedAffiliatesConfig,
leadRef: string,
): Promise<Record<string, string>> {
const found = await findLeadReferral({ payload, cfg, externalRef: leadRef })
return found ? { referralId: found.referralId, affiliateCode: found.affiliateCode } : {}
}Put the result in metadata on every order for that lead: the deposit, the balance and each add-on. The order handler then accepts the referral when it is open or converted, it has an externalRef, and earnsUntil is empty or still in the future (an earnsUntil that does not parse as a date earns nothing). Everything after that is the normal money path: commission on what was paid, a rate snapshot, the hold, and the idempotency key order:<orderId>. A refund reverses the commission the same way it does for any order.
earnsUntil also bounds renewals on a lead referral, on both renewal paths. Under program.leads.paymentWindow: 'signed-work' it bounds when the work a payment is for may have been agreed instead; see Partner terms.
Self-referral on a lead referral
On a link or promotion-code referral, an order placed by the affiliate's own member sets the referral to rejected. On a lead referral that order earns nothing and the referral is left exactly as it was: only an admin undoes a confirmed lead. The renewal resolver path does the same when buyerMemberId is the affiliate's member.
A partner's lead list
getAffiliateLeads returns AffiliateLead rows: referralId, label, note, externalRef, status, registeredAt, confirmedAt, expiresAt, earnsUntil, and pendingCents, approvedCents, paidCents, reversedCents. It returns only referrals that carry a label, so a link or promotion-code referral bound to a member can never appear, and it returns no member, order or payment field. The stage of the deal itself (proposal sent, signed, paid) is not in this read; join it from your own records by externalRef.
Expiry
The expireAffiliateReferrals job still expires open referrals past expiresAt. When program.leads.enabled it also expires pending lead referrals whose registeredAt is older than pendingExpiryDays, and reports them as expiredPendingLeads in ExpireReferralsSummary. The field is 0 when leads are off.
The registered channel
ReferralChannel is 'link' | 'promo-code' | 'registered' | 'manual'. registered is what lead referrals created by a partner or admin carry, and the label field is required on them. manual is a legacy option, shown as "Manual (legacy)" in the admin: nothing has ever written it and nothing does now, and it stays in the select so no stored row becomes invalid.
Tiers
A program can define named tiers, each with a default rate and a renewal cap. A partner sits in one tier. The layer gates no behavior on a tier; what a tier may do in a portal is your decision, and getAffiliateDashboard returns tier so you can make it.
import type { AffiliateProgramConfig } from '@wabbit/tome-affiliates'
const tiers: Pick<AffiliateProgramConfig, 'tiers' | 'defaultTier'> = {
tiers: {
standard: { label: 'Standard', rateBps: 1000, recurringMonths: 6 },
preferred: { label: 'Preferred', rateBps: 1500, recurringMonths: 12 },
},
defaultTier: 'standard', // must be a key of `tiers`
}resolveAffiliatesConfig throws AffiliatesConfigError when defaultTier is not a key of tiers, a tier rateBps is not an integer from 0 to 10000, or a tier recurringMonths is not an integer of 0 or more.
The affiliates collection gains a tier select (options built from tiers, writable by admins only) only when `tiers` is set. A program without tiers has no schema change, and AffiliateDashboard.tier is absent.
Rate, first match wins: the affiliate's own rateBps, then the tier's rateBps, then rateBpsByProductType[type] (when every commissionable line shares one type), then defaultRateBps.
Renewal cap, first match wins: the terms the work was signed under, when you supply them (0.11.0, see Partner revision), then the affiliate's own recurringUnlimited: true or recurringMonths, then the tier's recurringUnlimited: true or recurringMonths, then program.recurringMonths.
An explicit 0 at any level is a real value and wins. No cap (0.11.0) is recurringUnlimited: true, on a tier or on the affiliate row: it is distinct from recurringMonths: 0 (no renewal commissions) and from an unset recurringMonths (use the next level). A tier may not set both. periodIndex keeps counting under no cap, so "monthly payment 14" can still be shown. A tier rate sits above the per-product-type map because a rate agreed with a person is a commitment and a product map is a default. Tier rates that vary by product type are not supported.
Setting a tier. inviteAffiliate creates an invited row for a member, admin only:
import type { Payload } from 'payload'
import type { ResolvedAffiliatesConfig } from '@wabbit/tome-affiliates'
import { approveAffiliate, inviteAffiliate } from '@wabbit/tome-affiliates/server'
export async function inviteThenApprove(
payload: Payload,
cfg: ResolvedAffiliatesConfig,
memberId: string,
adminId: string,
) {
const { affiliateId } = await inviteAffiliate({
payload,
cfg,
system: true,
memberId,
code: 'northside', // trimmed and upper-cased; 3-24 of A-Z, 0-9, dash
tier: 'preferred', // optional; falls back to `defaultTier`
// rateBps, recurringMonths and (0.11.0) recurringUnlimited are optional per-partner overrides
})
// The member then signs with `acceptAffiliateTerms`; an admin approves.
await approveAffiliate({ payload, cfg, system: true, affiliateId, actor: adminId, tier: 'preferred' })
}inviteAffiliate throws when the member already has an affiliate row (any status, except an ended one under program.reapplyAfterEnding; see Partner revision), the code is taken or malformed, the tier is not a key of tiers, or an override is out of range (including recurringUnlimited: true with recurringMonths). It works under either enrollment mode. approveAffiliate takes an optional tier, validated the same way, so an admin can set or change it when approving an application; leave it out to keep the row's tier.
Renewal attribution
By default the renewal handler finds the referral through economy's subscriptions row (providerRef, metadata.referralId, member). A site whose subscription records are not economy's has no such row. For that site, supply resolveRenewalAttribution in the layer config: the handler calls it instead of reading economy's row.
import type { AffiliatesLayerConfig } from '@wabbit/tome-affiliates'
// Your own lookup: which referral does this subscription belong to?
declare function findEngagementReferral(
subscriptionId: string,
): Promise<{ referralId: string; isFirstCharge: boolean; isInstallment: boolean } | null>
export const resolveRenewalAttribution: NonNullable<AffiliatesLayerConfig['resolveRenewalAttribution']> = async ({
event,
}) => {
const record = await findEngagementReferral(event.subscriptionId)
if (!record) return null // no commission
if (record.isFirstCharge) return null // that charge already earned as an order
return { referralId: record.referralId, capped: !record.isInstallment }
}The resolver receives { event, payload } and returns RenewalAttribution | null:
| Field | Meaning |
|---|---|
referralId | The referral this charge belongs to. Must be open or converted. |
buyerMemberId | Optional. Used for the self-referral check; omit it when the buyer is not a member. |
productType | Optional. Overrides event.productType for the commissionable check and the rate map. |
capped | Default true. Set false for an installment of a one-time price: it is neither counted toward nor stopped by the renewal cap, and its commission row carries a null periodIndex. |
workSignedAt | Optional, ISO 8601. When the work this charge pays for was agreed; read only under paymentWindow: 'signed-work'. |
priorCappedPeriods | Optional non-negative integer, default 0. Capped periods of this engagement that already earned outside the renewal path, such as a first period paid as an order. Ignored when capped is false; anything that is not a non-negative integer throws AffiliatesConfigError and writes nothing. |
basisCents | Optional integer cents: the commissionable part of the charge, floored and clamped to 0..event.amountCents. Absent means the whole charge; a value that is not a finite number throws AffiliatesConfigError and writes nothing. |
signedTerms | Optional, 0.11.0: the rate and renewal cap this charge's work was signed under (AffiliateSignedTerms); they win over the affiliate's and the tier's current values. A malformed value throws AffiliatesConfigError and writes nothing. |
workSignedAt, priorCappedPeriods and basisCents are described under Partner terms, signedTerms under Partner revision. A null result means no commission. A throwing resolver writes nothing; the error goes to economy's dispatcher, which logs it.
Idempotency key. On the resolver path the commission's key is renewal:<subscriptionId>:<periodEnd>. renewal:<paymentId> is written only when the event has no periodEnd. Before writing, the handler looks for a commission under either key. paymentId is not required. The limit that follows: two separate invoices for one subscription in one billing period share a key, so the second earns nothing. A charge that varies mid-period must go on the period's own invoice, or be raised as an order. The economy-subscriptions path keeps its own key, renewal:<paymentId>.
The cap counts by provider subscription. Each renewal commission carries subscriptionRef (the provider's subscription id) and productType. On the resolver path the cap counts earlier capped renewal commissions with the same subscriptionRef. Order commissions also carry productType when every commissionable line shares one type.
First activation. Economy dispatches the renewal event on a subscription's first activation as well as on later charges. If your site's first charge already earned a commission as an order, return null from the resolver for that first event, or the charge earns twice.
Renewal commissions on this path now save on a real database. The commission collection used to require the economy subscription relation on every renewal row, which this path never has, so on a real Payload instance the write was refused. A renewal row now needs subscription or a non-empty subscriptionRef. A carry-forward row for a reversed paid commission on this path copies subscriptionRef and productType from the original, so it saves too; order rows and economy-path rows are written exactly as before.
Partner terms (0.8.0)
These features let a program keep the terms of a written partner agreement through configuration. Every one of them is opt-in. Each new option defaults to the 0.7.0 behavior, and the new operations do nothing until you call them, so a program that sets none of the options behaves exactly as on 0.7.0. The test suite holds a recording of every database write 0.7.0 made, for a program with no lead referrals and for one with them, and checks that the code still makes exactly those writes when no option is set. The one change that applies without opting in is the renewal fix above, which only lets a write succeed that used to be refused.
| Option | Default | Other value | What it changes |
|---|---|---|---|
program.leads.paymentWindow | 'hard-stop' | 'signed-work' | Whether a payment after earnsUntil can still earn when its work was agreed before it. |
program.terminationPolicy | 'void-pending' | 'honor-earned' | What ending a partner does to unpaid money, whether a status edit may end a partner, and whether an ended partner's balance is paid below the minimum. |
program.pausePolicy | 'stop-earning' | 'hold-payouts' | Whether a paused partner's confirmed leads keep earning while payouts wait. |
program.renewalCapCounts | 'every-commission' | 'kept-payments' | Whether a payment refunded in full, or lost to a chargeback, gives its place in the renewal cap back. |
program.commissionableRefund | not set | a function | What part of an order commission's basis a partial refund took back. |
program.onRefundUnresolved | not set | a function | Told when that part could not be worked out, so your owner can act. |
resolveAffiliatesConfig throws AffiliatesConfigError on a value outside these. Read them in your own code through the same names; AFFILIATES_PARTNER_TERMS_DEFAULTS holds the four defaults.
Signed work finishes earning
Under paymentWindow: 'hard-stop' no payment after a lead referral's earnsUntil earns, as before. Under 'signed-work', earnsUntil means "new work agreed by": a payment after it still earns when you say the work it pays for was agreed on or before it. You pass that date with each payment:
- an order:
order.metadata.workSignedAt(ISO 8601); - a renewal on the resolver path:
RenewalAttribution.workSignedAt; - a renewal through economy's own subscriptions: the subscription row's
metadata.workSignedAt.
A date that is absent, does not parse, or lies in the future earns nothing past the window, and one warning is logged per payment. A commission that earned with a valid date records it as workSignedAt on the row. Inside the window nothing changes: a payment earns with or without a date.
Which date belongs to a piece of work is your rule, not the package's. The package only compares the date it is given with earnsUntil. For a monthly engagement, pass one date per engagement on every period. Two things the window does not do: it does not stop an open claim from expiring at expiresAt (the expire job is unchanged), so extend the claim with `extendLeadReferral` when work is agreed, or a first payment that lands after expiresAt earns nothing; and it does not apply to link or promotion-code referrals. Moving earnsUntil earlier leaves work agreed before the new date earning.
Ending a partner
terminateAffiliate({ payload, cfg, affiliateId, actor, reason, withCause, withholdReferralIds?, withheldDisposition?, req | system }) ends an active or paused affiliate and records terminatedAt, terminatedBy, terminationReason (admin-only), terminatedWithCause and terminationWithheldReferrals. reason is required, 1 to 2000 characters. It takes effect when called; there is no end date in the future. Nothing earns after it, on any path, unless you give a run-off (0.11.0, see Partner revision). A second call is refused, and an invited or applied row is rejected with rejectAffiliate, not terminated. It returns { withheldCommissionIds }.
What it does to unpaid money is the policy's:
- `'void-pending'` (default). The operation writes only the status and the stamps, and the collection's hook then voids every pending commission and expires every open referral, exactly as a status edit does. A
withholdReferralIdslist or awithheldDispositionis refused. A status edit toterminatedkeeps working as before and leaves the stamps empty. - `'honor-earned'`. Nothing is voided: earned commissions approve on their own hold and are paid. Every open referral is expired. With
withCause: true, the unpaid commissions (pendingorapproved, no payout, not a carry-forward debit) on the referrals you name inwithholdReferralIdsbecomewithheld, remembering the status they had inwithheldFrom; withwithheldDisposition: 'void'they are voided at once with reasonaffiliate-terminatedinstead. Without cause a non-empty list is refused. A named referral that is missing or belongs to another affiliate, or a commission that is already an item of ascheduled,awaiting-revieworprocessingpayout, refuses the whole call. The status is written last, so a failure part-way leaves the partner unterminated and a retry finishes the job. Under this policy a status edit to `terminated` is refused (with anAffiliatesOperationRefusedErrorsaying to useterminateAffiliate), and so is an edit that moves a terminated row back to another status: an edit cannot reinstate a partner. From 0.11.0,applyForAffiliateandinviteAffiliatecan re-open an ended row underprogram.reapplyAfterEnding(see Partner revision).
A withheld commission is neither payable nor lost. The approve job reads only pending and the payout run only approved, so a withheld row is never approved or paid while withheld and never appears in a run's summary. A refund still reverses it: a full refund sets reversed, and a partial one keeps it withheld with reversedCents recorded, so a later release pays the net. Nothing settles it automatically; settle each one with a reason:
releaseWithheldCommission({ payload, cfg, commissionId, actor, reason, req | system })returns it towithheldFromand returns{ status }. One withheld frompendingkeeps itsholdUntiland is approved by the next approve job once the hold has passed; one withheld fromapprovedis paid by the next run.voidWithheldCommission({ ... })voids it:status: 'void',reversalReason: 'affiliate-terminated',reversedCentsthe full amount.
Both refuse a row that is not withheld, so a replay writes nothing, and both stamp withholdResolution, withholdResolvedAt, withholdResolvedBy and withholdResolutionReason. The withheld status option exists on the commissions collection only under honor-earned. Do not switch a program away from `honor-earned` while any commission is `withheld`: release or void them first, or those rows sit on a status the collection no longer offers.
The final batches. Under honor-earned, every payout run pays an ended partner's approved balance whatever program.minPayoutCents is, in every run after the end, so commissions that mature later and withheld ones released later are paid at the first run after they become approved. The run hands those payees to economy's batch as a second batch in the same call, with no minimum and the run id <runId>-final, so economy's key is payout:<payeeId>:<runId>-final. A re-run of the same run pays nothing twice. If you run payouts twice in one month, pass your own `runId` for the second run (for example 2026-12-2); the default run id is the UTC YYYY-MM, and two runs that share it share their keys. A final net of zero or less (a carry-forward debit at least as large as what is approved) is not sent: it stays on the ledger and is reported in skipped as below-minimum. When the main batch stops on a short platform balance, the final batch is not run and its payees are listed in skipped as run-stopped-insufficient-balance. The tax-form gate and the first-payout review apply to the final batch as to the main one.
The run's summary under honor-earned, when it found an ended partner's approved commissions: created and sent are the sums of both batches, skipped and failed list the main batch's entries followed by the final batch's, and finalBatch carries the final batch's own summary. Under void-pending a run makes one batch and the summary has no finalBatch.
Pausing a partner
pauseAffiliate({ payload, cfg, affiliateId, actor, reason, req | system }) moves active to paused and stamps pausedAt, pausedBy and pauseReason (admin-only). resumeAffiliate({ payload, cfg, affiliateId, actor, req | system }) moves paused back to active and clears those three stamps; it takes no reason, and the actor is written to the log line only. Each returns { changed }, and a repeat (pausing a paused partner, resuming an active one) writes nothing. Both work under either policy, and a status edit to or from paused still works and leaves the stamps empty. The promotion code is switched off and on as for a status edit.
What a pause means is the policy's, and affiliateStanding(cfg, status) tells your code:
| Status | 'stop-earning' (default) | 'hold-payouts' |
|---|---|---|
active | earns, registers leads, tier permissions, paid | the same |
paused | nothing earns, no registration, no tier permissions, approved commissions still paid | confirmed leads earn, no registration, no tier permissions, payouts held |
terminated, invited, applied, rejected | nothing | nothing |
AffiliateStanding is { earnsOnConfirmedLeads, mayRegisterLeads, mayUseTierPermissions, payoutsHeld }. The package gates nothing on tier, so mayUseTierPermissions is for your own features to apply.
Under 'hold-payouts': payments on a paused partner's lead referrals earn on all three payment paths; their link and promotion-code referrals earn nothing; registerLead, captureLeadFromCookie and createLeadReferral still refuse a paused partner, and confirmLeadReferral still confirms a lead registered before the pause; findLeadReferral returns the referral and says affiliateStatus: 'paused'; and the payout run leaves out every approved commission of a paused partner (carry-forward debits included) and lists one PausedPayoutHold ({ affiliateId, payeeId, reason: 'affiliate-paused' }) per partner in heldForPause. The rows stay approved and the first run after resumeAffiliate pays them. heldForPause is present only under this policy; a held payee is never handed to economy's batch, so it is not in skipped. Under 'stop-earning' a pause behaves as on 0.7.0, and what was not earned during it is not made up on resume; from 0.9.0, confirmLeadReferral refuses a paused affiliate's claim under this policy (see Payout guards and approving applications).
The renewal cap
Periods earned elsewhere. A capped engagement may have earned some of its places before its first renewal event, for example a first month paid as an order. Return that number as RenewalAttribution.priorCappedPeriods; a commission's periodIndex is then its position in the cap, priorCappedPeriods + earlier capped rows + 1. Rows written without it read as before. The economy-subscriptions path ignores the field.
What the count counts. Under the default 'every-commission' the count is exactly 0.7.0's: on the resolver path, earlier subscription-renewal rows with the same subscriptionRef and a periodIndex of 1 or more; on the economy-subscriptions path, every subscription-renewal row with the same economy subscription relation, whatever its status. On the economy path that includes the carry-forward debit row a reversal of a paid renewal writes (it copies the relation), so under the default a paid renewal reversed after payout uses two places there. Under 'kept-payments' the economy path leaves carry-forward rows (basis 0) out, and the resolver path never counted them (they carry no periodIndex).
Only payments kept. Under renewalCapCounts: 'kept-payments' a payment refunded in full gives its place back, on both renewal paths, before or after payout: the next capped payment earns in its place. A reversal in full with reason refund or dispute marks the commission paymentRefunded, on any status (a paid row keeps status paid and gets its carry-forward). That covers a full order refund event, the approve job finding an Order refunded, and reverseCommission called without amountCents (or with the whole amount). A partial-refund reversal never marks, even when a series of them adds up to the whole commission, so a partly refunded payment keeps its place. dispute means a chargeback the buyer won and the money taken back, recorded by your own reversal: the package has no dispute event, so an open chargeback, or one you won, changes nothing. A reversal for admin or affiliate-terminated, a void and a withheld row all keep their places. Under the default 'every-commission' every capped row counts whatever happened to it, and the marker is never written.
Your offset from the package's rule. When the first period was paid as an order, pass priorCappedPeriods: countsTowardCap(cfg, orderCommission) ? 1 : 0, so a first period refunded in full stops counting and a partly refunded one still counts:
import type { RenewalAttribution, ResolvedAffiliatesConfig } from '@wabbit/tome-affiliates'
import { countsTowardCap } from '@wabbit/tome-affiliates/server'
export function attributionFor(
cfg: ResolvedAffiliatesConfig,
referralId: string,
firstPeriodCommission: { paymentRefunded?: boolean | null; basisCents?: number | null } | null,
): RenewalAttribution {
const priorCappedPeriods = firstPeriodCommission && countsTowardCap(cfg, firstPeriodCommission) ? 1 : 0
return { referralId, priorCappedPeriods }
}The cap is per engagement, not per lead. The count's key is the provider subscription (event.subscriptionId), so a second engagement for the same lead has its own cap, provided you send the same referral id for all of the lead's work, bill each engagement on its own provider subscription (two engagements on one subscription share one cap), and pass priorCappedPeriods for that engagement only. When an engagement moves to a replacement subscription, add the periods that already earned under the old one so the cap does not restart.
Switching an existing program to 'kept-payments': refunds reversed before the switch are not marked, so they keep their places until your own script marks them.
The renewal basis
RenewalAttribution.basisCents is the commissionable part of a recurring charge, for a charge with a part your program does not pay on. It is floored and clamped to 0..event.amountCents, and program.commissionBasis still runs after it and can only narrow it further. A basis of 0 writes no commission row and so takes no place in the cap (a zero-basis row is how the package marks a carry-forward debit). When the basis is below the charge, the row records the charge as chargedCents.
`chargedCents` and `basisCents` are admin figures. The gap between them is the part of the charge you left out, and an affiliate should not be able to work it out. The package's partner-facing reads (getAffiliateLeads, getAffiliateDashboard) return neither field, and the commissions collection stays admin-read. Any partner-facing read you build yourself must leave out `chargedCents` and `basisCents` too.
To reverse part of a reduced-basis renewal, work the amount out on the commissionable part refunded against the row's basisCents, never against chargedCents, and pass it to reverseCommission.
Proportional reversal
reverseCommission({ payload, cfg, commissionId, reason, actor, amountCents?, req | system }) takes an optional amountCents: the cumulative amount reversed after the call, an integer above what is already reversed and at most the commission's amount. Below the whole amount the reason must be partial-refund and the status is kept; a paid row carries forward only the delta over what was already carried. Without it, or with the whole amount, the reversal is in full with the reason you give.
Order refunds on a narrowed basis
Without a hook, a partial order refund reverses floor(amountCents × refundedCents / totalCents), a share of the whole Order, as before. When program.commissionBasis leaves part of an Order out of the basis, that share can take back commission on work the buyer kept. Set program.commissionableRefund to say what part of the commission's basis the refund took back:
- A number: the cumulative commissionable amount refunded so far. It is floored and clamped to
0..basisCents, and the handler reversesfloor(amountCents × result / basisCents)with reasonpartial-refund. A refund of only the left-out part reverses nothing, and a redelivery with the same cumulative amount writes nothing. - `null`: you cannot tell. Nothing is reversed, a warning is logged and
onRefundUnresolvedis called withreason: 'cannot-tell'. - Anything else, or a throw: treated as "cannot tell", reported as
invalid-resultorhook-error. It never falls back to the whole-Order share.
A refund in full is a full reversal with reason refund and never calls the hook. The hook receives CommissionableRefundContext (trigger: 'refund-event' with the commissionId, or 'late-credit' from creditEarlierPayments, with orderId, paymentKey order:<orderId>, refundedCents, totalCents, basisCents and payload); onRefundUnresolved receives UnresolvedRefund with the same identifiers. A throwing onRefundUnresolved is caught and logged and blocks nothing. When it is told, your owner can enter the amount by hand with reverseCommission.
Payments made before a late confirmation
creditEarlierPayments({ payload, cfg, referralId, actor, payments, earlierPaymentsFrom?, req | system }) credits the payments a buyer made before their lead was confirmed, each exactly once, as if it had arrived after the confirmation. Call it right after you confirm a lead whose buyer had already paid. payments is a list of EarlierPayment entries:
{ kind: 'order', orderId, workSignedAt?, signedTerms? };{ kind: 'renewal', subscriptionId, periodEnd, paidAt, amountCents, refundedCents?, refundedBasisCents?, productType, productId, buyerMemberId?, capped?, priorCappedPeriods?, basisCents?, workSignedAt?, signedTerms? }, carrying what the renewal event and your resolver would have carried for that period.
Each payment is written under the key the live handler uses (order:<orderId>, renewal:<subscriptionId>:<periodEnd>), so a credited payment and a later delivery of its event never both earn, and a re-run returns the earlier ones as already-recorded. Payments are taken oldest first, so the cap fills in the order the buyer paid; the same window, cap, basis, self-referral and standing rules as the live paths apply. Every row carries creditedLate: true and is held for the full hold from the day of the credit, and its rate is the affiliate's rate on that day (the package keeps no rate history), unless the entry, or the Order's metadata, carries signedTerms (0.11.0), which win as on the live paths. A partly refunded payment is credited and reversed in proportion, through the hook above for an Order; for a renewal whose basis is below its charge, pass refundedBasisCents, or the payment is skipped. When anything is credited an open referral becomes converted. It returns { credited: [{ key, commissionId }], skipped: [{ key, reason }] }; a skip reason is one of already-recorded, refunded, before-registration, after-confirmation, outside-window, not-commissionable, zero-basis, cap-reached, self-referral, order-not-paid and refund-share-unknown. A skipped payment writes nothing, so a re-run with the missing value credits it.
The referral must be a confirmed lead (open or converted, with confirmedAt), and the affiliate must be able to earn now: active, paused under hold-payouts (its credits are then held from payout until resume), or (0.11.0) ended with a run-off still open. Otherwise the call is refused and writes nothing.
The lower bound. Only payments made on or after the moment the partner brought the lead are credited: earlierPaymentsFrom when recorded, else the link arrival clickedAt for a referral that came by link, else registeredAt. Earlier payments are skipped before-registration. Call earliestCreditablePaymentAt(referral) to show your owner the same date. A lead an admin created with createLeadReferral is registered at its confirmation, so it credits nothing earlier unless you pass earlierPaymentsFrom, the date the partner brought it, as the admin states it. It is allowed only on an admin-created referral, may not be after confirmedAt, and is recorded once with earlierPaymentsFromBy and earlierPaymentsFromAt; a later call may leave it out but may not change it.
Which payments belong to the lead is your call, and your responsibility. The operation trusts the list you pass: it does not check that an Order names the referral, or that a renewal period belongs to the lead's work. Pass only the lead's own payments.
Ids you pass to the operations
The admin operations stamp the actor you pass into a relationship to users (approvedBy, rejectedBy, confirmedBy, terminatedBy, pausedBy, withdrawnBy, withholdResolvedBy, earlierPaymentsFromBy, manualPayoutApprovedBy, and from 0.9.0 applicationApprovedBy), and terminateAffiliate stamps the withholdReferralIds into terminationWithheldReferrals. Pass those ids in your database's own id type: a string on a string-id database such as Mongo, a number on a numeric-id database such as Postgres or SQLite with default ids. The package writes them as given and never converts them, because a numeric-id database refuses a string id in a relationship. The other id arguments (affiliateId, referralId, commissionId, orderId) are only looked up, and a string works on either kind. One limit remains from 0.7.0: createLeadReferral, registerLead, inviteAffiliate and applyForAffiliate write an affiliate or member id into a relationship as a string (the argument you pass, or the looked-up row's id converted to a string), so on a numeric-id database those four refuse to write until that is widened; create those rows with your own write there.
Other operations
withdrawLeadReferralwithdraws a confirmed claim that has earned nothing (see Lead referrals).approveManualPayoutRail({ payload, cfg, affiliateId, actor, req | system })allows the hand-run payout rail for one affiliate (see Payout rails are opt-in, not fallbacks).
Partner-facing totals
Under honor-earned, getAffiliateLeads rows and getAffiliateDashboard gain withheldCents: withheld commissions' amount less what was reversed off them. Withheld money is never counted as pending or approved. Under void-pending both reads have the 0.7.0 shape. Whether you show the bucket to an ended partner is your choice.
Upgrading to 0.8.0
- New optional fields.
affiliatesgains the termination and pause stamps;affiliate-commissionsgainsworkSignedAt,chargedCents,paymentRefunded,creditedLateand the six withhold fields;affiliate-referralsgainsearlierPaymentsFrom,earlierPaymentsFromBy,earlierPaymentsFromAt,withdrawnAt,withdrawnByandwithdrawalReason. All are read-only in the admin and written only by the operations; the reasons are admin-only. A SQL database gets nullable columns, thewithheldstatus value when you sethonor-earned, and a join table forterminationWithheldReferrals; Mongo needs nothing. - `CommissionStatus` gains `'withheld'`. An exhaustive
switchon it gets a type error to handle; no row holds the value unless you opt intohonor-earned. - Rows from before the upgrade. A terminated partner with no
terminatedAtwas ended by a status edit or before 0.8.0, and a paused one with nopausedAtlikewise; nothing is backfilled. Underhold-payouts, a partner already paused starts earning on confirmed leads from the upgrade on, and its approved balance is held from the next run. - `signed-work` with `earningMonths: 0`. A referral confirmed while
earningMonthswas 0 has noearnsUntiland earns with no limit; set itsearnsUntilwith your own script before you rely on the window. - `kept-payments` counts earlier full refunds only once they are marked (see The renewal cap).
Payout guards and approving applications (0.9.0)
0.9.0 makes four promises the package already made hold on every path, and adds one operation. It requires @wabbit/tome-economy 0.20.0 or later: install that first and follow its migration note (a unique index on payout-accounts). Two operations now refuse calls they used to accept (confirmLeadReferral and releaseFirstPayout); every other change is opt-in through the options you already set, or converges what was wrong.
A new payout account starts with its tax form required
With program.requireTaxFormBeforePayout: true, startPayoutOnboarding creates the payout account with taxFormStatus: 'required', so the gate holds the payee until a form is recorded. Before 0.9.0 the account took economy's default, not-required, and the payee was paid without a form. With the option off, the account is created exactly as before (no taxFormStatus written, economy's default applies). An account that already exists is never changed: its status may be a person's decision.
What you change: nothing. If you added your own required default to the payout-accounts collection to work around this, you may delete it. A program that turns the gate on after accounts exist must review those accounts: each one created while the gate was off is not-required and pays.
taxFormStatusPays(status) (from /server) is the gate's rule: true for collected, verified and not-required, false for required, a missing status and anything else. Call it in your own previews instead of keeping your own list.
A released first payout is held by the same checks
Under pausePolicy: 'hold-payouts' or with the tax-form gate on, a first payout an admin released with releaseFirstPayout is checked again at the run, immediately before economy would send it: a paused affiliate's payout, or one whose payout account has no payable tax status, stays scheduled, is not sent, and is tried again at the next run. It is listed in the lists you already read, with the payout's id: heldForPause gains { affiliateId, payeeId, reason: 'affiliate-paused', payoutId } and heldForTaxForm gains { affiliateId, payeeId, reason: 'tax-form-missing', taxFormStatus, payoutId }. payoutId is present only on an entry for a released payout. Each list carries one entry per affiliate, even when the same run holds both a released payout and newer commissions of that affiliate; the entry has the payout's id when a released payout is among what is held. The summary also carries economy's own held list, { payeeId, payoutId, reason } for each released payout held, present (possibly empty) whenever either option is on. It is the only place a hold whose check threw (reason: 'hold-check-failed') or a hold for a payee with no affiliate row appears, so a report of held money reads it as well. Once the pause is lifted or the form is recorded, the next run sends it under its stored key, so it is never sent twice.
releaseFirstPayout refuses, writing nothing, when the same check would hold the payout now: an AffiliatesOperationRefusedError with reason: 'affiliate-paused' or 'tax-form-missing'. It does not refuse for a missing or inactive payout account; the run already waits for one. A program with neither option set makes the same calls as before.
What you change: if you refuse a release yourself, you can take the answer from the package's reason instead. A payout preview that mirrors the run should model the hold of a released payout, and a summary or email that reads heldForPause or heldForTaxForm can show the new payoutId.
Confirming a lead requires an affiliate who may earn on it
confirmLeadReferral now reads the referral's affiliate, after the pending check and before the externalRef and already-attributed checks, and refuses unless affiliateStanding(cfg, status).earnsOnConfirmedLeads is true: active, or paused under pausePolicy: 'hold-payouts'. A confirmation grants an earning right and an exclusive hold on the lead, so a claim that could never earn must not hold the lead against every other affiliate. The refusals are AffiliatesOperationRefusedError with reason: 'affiliate-cannot-earn' (the message names the status) or 'affiliate-not-found', and nothing is written.
- Under
'hold-payouts'a paused affiliate's claim confirms, as in 0.8.0. - Behavior change under the default `'stop-earning'`: a paused affiliate's claim is now refused. In 0.8.0 it was confirmed and could not earn until a resume.
- A terminated affiliate's claim is refused under either termination policy, and so is the claim of an
invited,appliedorrejectedrow. - A refused pending claim can still be declined with
declineLeadReferral, and it expires on its own afterprogram.leads.pendingExpiryDays.
What you change: if your code writes its own records before it calls confirmLeadReferral, check the standing first with the same rule (affiliateStanding(cfg, status).earnsOnConfirmedLeads), so your site and the package refuse the same set, and map affiliate-cannot-earn to your own refusal in case the status changes between the two.
One payout account per payee per rail, and one rail account behind it
Two startPayoutOnboarding calls at the same moment (two tabs, a resend while the first is running) used to create two payout accounts and two rail accounts for one payee. Now:
- Economy's unique
(payee, rail)index refuses the second create, and the call that lost reads the row the other call made and continues with it. The re-read decides, not the wording of the database's error; an error with no row behind it is rethrown. - The rail account is created with an idempotency key built from the payout account's id (
payout-account-onboarding:<id>), so every call that converges on the row asks the provider for the same account. A row that already holds a rail account passes no key. - When the link call fails, the row is read again: if another call has stored its rail account by now, a link is made for that account. If not, and the provider refused the request because another one with the same key is still running, the call throws
AffiliatesOperationRefusedErrorwithreason: 'payout-setup-in-progress'; retry in a moment. Any other error is rethrown as it was. - Before the rail account is written back, the row is read again. A different account already stored there wins: nothing is overwritten, a fresh link is made for the stored account, and
payload.logger.warnnames the extra account so an admin can close it with the provider.
The return value, the affiliate's payoutAccount pointer and every existing error message are unchanged.
What you change: before you upgrade, look for payees with two or more payout accounts on one rail (economy's migration note); the index cannot be built while any exist. On a SQL database, generate and run a migration for the index. On MongoDB, Payload builds it at boot. A test stand-in for the provider should return the same account for a repeated idempotency key, as the real provider does.
Approving an application before the applicant signs
inviteApplicant({ payload, cfg, affiliateId, actor?, tier?, code?, req | system }) moves an applied row to invited, so the applicant can read and accept the agreement; approveAffiliate then activates it as it does any invited row. It keeps everything the applicant sent (appliedAt, application, applicationSubmittedAt) and stamps who approved the application and when, in two new fields: applicationApprovedAt and applicationApprovedBy (a relationship to users, like approvedBy). Those are separate from the activation stamps approvedAt and approvedBy, which only approveAffiliate writes. It returns { affiliateId, tier, code, applicationApprovedAt, changed }.
- Authorization and the actor. Pass the admin's
reqandactor(the approving admin's users id, in your database's own id type), orsystem: truewithactoroptional; without oneapplicationApprovedByis stored as null. Areqcall withoutactorthrows before any read. - Tier. A key of
program.tiers; omitted, the row keeps its tier, or getsprogram.defaultTierwhen it has none and the program has tiers. An unknown tier throws as inapproveAffiliate. - Code. Optional. It is trimmed and upper-cased, must match the code pattern and must be free, with the same errors as
inviteAffiliate. A code equal to the row's own is not a change. A change is refused withreason: 'code-has-promotion-code'when the row already has a provider promotion code; rotate it withrotateAffiliatePromotionCodefirst. Reserved words and naming rules are your program's to check before the call. - Replays and other statuses. A row this operation already invited returns
changed: falseand writes nothing, keeping the first stamps; a replay with a different tier or code is refused withreason: 'already-invited'. Any other status, including aninvitedrow made byinviteAffiliate, is refused withreason: 'not-applied'. A missing row is refused withreason: 'affiliate-not-found'. - The stamps afterwards.
rejectAffiliateon an approved row that has not signed keeps them, so the record reads "approved, then rejected". A later re-application throughapplyForAffiliateclears both along with the rejection stamps, because the new application has not been approved.approveAffiliatekeeps them as history, and erasure leavesapplicationApprovedByalone, as it leavesapprovedBy. - Who may write them. Only the package: both fields are read-only in the admin, and their field-level
createandupdateaccess is closed, so an admin's REST, GraphQL or admin-panel write to them is dropped. Read access matchesapprovedBy: an affiliates admin reads every row, and a member reads their own.
No email is sent and no promotion code is minted (that happens on activation).
What you change: nothing unless you approve before signing. A program that does calls inviteApplicant where it used to write status by hand, and maps the reason codes to its own refusals. A SQL database gets two nullable columns on affiliates; MongoDB needs nothing.
Refusal reasons
AffiliatesOperationRefusedError keeps its code ('affiliates-operation-refused') and gains an optional, stable reason, set by every refusal 0.9.0 adds. Refusals from earlier versions carry none. Branch on reason, never on the message text. The type is AffiliatesRefusalReason (root entry).
reason | Thrown by | Meaning |
|---|---|---|
affiliate-paused | releaseFirstPayout | the pause hold would hold this payout now |
tax-form-missing | releaseFirstPayout | the tax-form gate would hold this payout now |
affiliate-not-found | confirmLeadReferral, inviteApplicant | the referral's affiliate, or the named affiliate, does not exist |
affiliate-cannot-earn | confirmLeadReferral | the affiliate's standing does not earn on confirmed leads |
payout-setup-in-progress | startPayoutOnboarding | another setup for the same payout account is running; retry shortly |
not-applied | inviteApplicant | the row is not an applicant |
already-invited | inviteApplicant | the applicant is already invited with a different tier or code |
code-has-promotion-code | inviteApplicant; from 0.11.0 also applyForAffiliate and inviteAffiliate re-opening an ended row | a code change on a row whose provider promotion code already exists |
ended-invitation-only | applyForAffiliate (0.11.0) | the row ended in a way program.reapplyAfterEnding does not list; only an invitation re-opens it |
ended-reapply-wait | applyForAffiliate (0.11.0) | the row ended and its wait has not passed; the message names the date |
A route or server action wrapping any of these maps the class to 409, as for every refusal.
Upgrading to 0.9.0
- Economy first. Install
@wabbit/tome-economy0.20.0 or later (the peer floor was 0.12.0) and run its duplicate check onpayout-accountsbefore you upgrade; on SQL, migrate for its new index. - New optional fields.
affiliatesgainsapplicationApprovedAtandapplicationApprovedByafterapprovedBy. A SQL database gets two nullable columns; MongoDB needs nothing. Regenerate your types. - Two refusals.
confirmLeadReferralrefuses an affiliate whose standing does not earn on confirmed leads, andreleaseFirstPayoutrefuses while the pause hold or the tax-form gate would hold the payout. HandleAffiliatesOperationRefusedErrorwith itsreasonwhere you call them. - A program with neither option set sees only the unique index, the onboarding key and the confirm check; its writes are otherwise those of 0.8.0.
Partner revision (0.11.0)
Four additions for a written partner agreement whose terms outlive a rate change or an ending. Each is opt-in: a program that configures none of them, and passes none of the new arguments, gets exactly 0.10.0's results and writes.
| Addition | Turned on by | Unset |
|---|---|---|
| No renewal cap | recurringUnlimited: true on a tier, on the affiliate row (or inviteAffiliate), or in a payment's signedTerms | caps resolve as before |
| Terms locked at signing | a signedTerms object on a payment | the affiliate's and tier's current rate and cap |
| Run-off after an ending | terminateAffiliate({ runOffUntil, runOffReferralIds? }) under terminationPolicy: 'honor-earned' | nothing earns after the end |
| Applying or being invited again after an ending | program.reapplyAfterEnding | an ended member can neither apply nor be invited |
No renewal cap
null on recurringMonths already means "use the next level" and 0 means "no renewal commissions", so no cap is its own flag, recurringUnlimited: true, on AffiliateTierConfig, on the affiliates row (a new optional checkbox) and on AffiliateSignedTerms. The resolution order is under Tiers. Only true changes anything; false or empty inherits. resolveAffiliatesConfig refuses a non-boolean flag and a tier that sets the flag with recurringMonths; inviteAffiliate refuses recurringUnlimited: true with recurringMonths. Both renewal paths and creditEarlierPayments apply it, and periodIndex keeps counting.
Terms locked at signing
The package reads the rate and the renewal cap when a commission is credited. To keep work on the terms it was signed under, pass those terms with each payment on it, beside workSignedAt:
- an order:
order.metadata.signedTerms; - a renewal on the resolver path:
RenewalAttribution.signedTerms; - a renewal through economy's own subscriptions: the subscription row's
metadata.signedTerms; - a late credit:
EarlierPayment.signedTerms(for an order, it wins over the Order's metadata).
import type { AffiliateSignedTerms, RenewalAttribution } from '@wabbit/tome-affiliates'
// Snapshot at signing, stored on your own deal, returned with every charge on it.
const signedTerms: AffiliateSignedTerms = {
rateBps: 2000, // integer 0-10000; wins over every other rate
recurringMonths: 12, // integer 0 or more; or recurringUnlimited: true for no cap
signedAt: '2026-11-20T15:00:00.000Z', // your signing date, recorded as termsSignedAt
}
const attribution: RenewalAttribution = { referralId: 'ref_1', signedTerms }Each field is optional and wins over the affiliate's and the tier's current value; a field left out falls back to today's resolution, so a payment with no signedTerms earns exactly as before. A signed rate or cap below the current one applies too: a program change never reaches signed work, in either direction. The commission records the rate it used as rateBps, as always, and signedAt as termsSignedAt (a new optional, admin-only commission field). A value of the wrong shape (a rate outside 0 to 10000 or not an integer, negative or fractional months, a non-boolean flag, a signedAt that does not parse or lies in the future) throws AffiliatesConfigError and writes nothing; creditEarlierPayments checks every entry before it credits any.
What stays yours. Which terms belong to which work, when you snapshot them (at signing, or at a late confirmation), and any history of a partner's past rates are your rules and your storage. The package only applies what you pass. So are a lesser-of-signed-and-paid basis and a large-project breakpoint: express those through RenewalAttribution.basisCents and program.commissionBasis as before.
Ending kinds and the run-off
terminateAffiliate takes three more optional arguments:
endingKind: one ofAFFILIATE_ENDING_KINDS, stamped on the row asendingKind(a new optional, read-only select).'cause'requireswithCause: true, andwithCause: truerequires'cause'when a kind is given. The package attaches no rule to a kind exceptprogram.reapplyAfterEnding.runOffUntil('honor-earned'only): an ISO date after now, stamped asrunOffUntil(a new optional, read-only date). Until then, the ended affiliate's lead referrals keep earning on every payment path, andcreditEarlierPaymentsaccepts the affiliate. Link and promotion-code referrals do not. Which endings get a run-off, and how long, is your choice: the package never derives it from the kind.runOffReferralIds('honor-earned'only, withrunOffUntil): the open referrals the run-off covers (for example a lead with a proposal out). They are left open instead of expired; every other open referral is expired as before. Each must belong to the affiliate, or the call is refused.
Which payments in a run-off earn is your rule. The package only stops refusing the ended affiliate until runOffUntil. Name the referral on a payment (order metadata, the renewal resolver, the subscription row) only for work your agreement's run-off covers, such as work signed before the end date, work signed from a proposal sent before it, and later phases of a project signed before it; return null from the resolver, or leave the referral off the order, for the rest. A per-engagement end earlier than runOffUntil (for example the end of a monthly term) is the cap's job, through signedTerms.
affiliateStanding(cfg, status, { runOffUntil, now }) reports earnsOnConfirmedLeads: true (and nothing else) for an ended partner inside a run-off. The run-off holds through a re-application (applied, invited, rejected), but a paused row keeps the pause rule. From 0.11.1, affiliateMayConfirmLead(cfg, affiliate, referral, at?) (exported from /server) is the confirm rule, so your own screens refuse exactly what the package refuses, and confirmLeadReferral confirms an ended partner's pending lead inside an open run-off, when the lead's registeredAt is on or before the row's terminatedAt; a lead registered after the ending is refused (affiliate-cannot-earn). Payouts are unchanged: under 'honor-earned' an ended partner's approved commissions, run-off ones included, are paid in every run's final batch. A runOffUntil or runOffReferralIds under 'void-pending' is refused, because that policy's hook voids pending commissions and expires every open referral. A later ending of a row that came back clears the earlier endingKind and runOffUntil unless new ones are given; with none of the new arguments, the status write is 0.10.0's.
Applying or being invited again after an ending
program: {
// ...
terminationPolicy: 'honor-earned',
reapplyAfterEnding: {
partner: 90, // days after terminatedAt
inactivity: 90,
'without-cause': 0, // at once
'program-closed': 0,
'rejected-change': 0,
// 'cause' not listed: invitation only
},
}With the policy set, applyForAffiliate re-opens a terminated row whose endingKind it lists, once terminatedAt plus that many days has passed. It updates the same row to applied with the new answers, clears the rejection and application-approval stamps, and clears the acceptance stamps (termsVersion, termsHash, termsAcceptedAt, disclosureAcknowledgedAt, acceptedFromIp), so the partner signs again before approveAffiliate can activate them. The termination stamps, endingKind and runOffUntil stay on the row. Refusals carry a reason: ended-invitation-only for a kind the policy does not list (or a row ended with no kind, such as a status edit or one ended before 0.11.0), and ended-reapply-wait inside the wait (the message names the date). endedReapplyEligibleAt(cfg, row) returns the same date, or null, for your own page.
Invitation is always open to an admin under the policy: inviteAffiliate re-opens an ended member's row, whatever its kind, as invited, writes the tier and overrides you pass, clears the same stamps, and returns { affiliateId, reopened: true }. On either path a code other than the row's must be free, and a row with a provider promotion code keeps its code (code-has-promotion-code); the promotion code turns back on when the row is next active. Without the policy, both refuse an ended member as before. Rejected applications keep their own rule, reapplyAfterDays.
Upgrading to 0.11.0
- New optional fields.
affiliatesgainsrecurringUnlimited,endingKindandrunOffUntil;affiliate-commissionsgainstermsSignedAt. A SQL database gets nullable columns (and an enum forendingKind); Mongo needs nothing. No row is backfilled, and an empty value means what it meant before. - `AffiliatesRefusalReason` gains `'ended-invitation-only'` and `'ended-reapply-wait'`. An exhaustive
switchon it gets a type error to handle. - `affiliateStanding` takes an optional third argument. Calls with two arguments return what they did.
Tax-form gate
Set program.requireTaxFormBeforePayout: true to hold a payee out of a payout run until a tax form is on file. It is off by default. The gate reads taxFormStatus on the payee's active economy payout account:
taxFormStatus | Result |
|---|---|
collected, verified | Paid. |
not-required | Paid. Economy defines it to mean no form is needed for that payee. |
required | Held. |
| none set | Held. |
taxFormStatusPays(status) from /server is this table as a function (0.9.0). With the gate on, an account startPayoutOnboarding creates starts required (0.9.0; before, it started not-required and paid), and a released first payout is checked again at the run (see Payout guards and approving applications).
A payee with no active payout account is not held by the gate; economy skips that payee as it always did. Held payees are listed in the run summary as heldForTaxForm, an array of HeldPayout (affiliateId, payeeId, reason: 'tax-form-missing', taxFormStatus, and payoutId for a released payout the run held). The field is present (possibly empty) only when the gate is on. Held commissions are not touched: they stay approved, and the next run collects them once the form is on file. The layer does not collect a form or a taxpayer id; see Signing the agreement.
Applications, rejection, and re-application
Under enrollment: 'application', applyForAffiliate({ payload, cfg, memberId, code, application }) is how a member becomes an applied affiliate. application is an optional AffiliateApplicationAnswer[] ({ key, label, value }) — whatever question set your consumer asks; it is stored verbatim on the affiliate row's application array field (admin-visible, applicant-invisible after submission) and the row's applicationSubmittedAt is stamped server-side, never taken from the caller. An admin decides the outcome: approveAffiliate moves invited/applied to active; rejectAffiliate({ payload, cfg, affiliateId, actor, reason? }) moves invited/applied to rejected, stamping rejectedAt/rejectedBy and recording rejectionReason when a reason is given — it throws naming the current status when the row is not invited/applied (active, paused, terminated, or already rejected).
A rejected row is not a dead end. applyForAffiliate is also the re-application path: called again for the same member, it checks rejectedAt + cfg.program.reapplyAfterDays (default 30 days; 0 means the applicant may re-apply immediately). Inside the window it throws, naming the date re-application opens. Once the window has passed it UPDATES the same affiliate row rather than creating a second one — status back to applied, a fresh appliedAt/application/applicationSubmittedAt, and rejectedAt/rejectedBy/rejectionReason all cleared, and from 0.9.0 the application approval stamps applicationApprovedAt/applicationApprovedBy too — so one member never accumulates more than one affiliate row. The requested code is only changed if it is free; a code already held by another affiliate row throws, exactly as it would on a first-time application. rejected is also exempt from the termsVersion-required rule (affiliates collection): a rejected applicant never accepted terms, so a rejected row saves without one.
An ended (terminated) row can apply again only under program.reapplyAfterEnding (0.11.0); see Partner revision.
Signing the agreement
acceptAffiliateTerms records a signature, not a checkbox. From 0.4.0 it requires a signer:
await acceptAffiliateTerms({
payload, cfg, memberId,
termsVersion: cfg.currentTermsVersion,
termsHash: MY_AGREEMENT_SHA256, // optional; see below
ip: firstForwardedHop(headers),
signer: {
type: 'business', // or 'individual'
firstName: 'Grace', // the authorized signer — a person, always
lastName: 'Hopper',
businessLegalName: 'Hopper Systems LLC', // required when type is 'business'
country: 'US', // ISO 3166-1 alpha-2
},
})Those five values are frozen onto the affiliate row and never resolved back through member. A member can edit their own profile name; an agreement that looked its signatory up at read time would record nothing durable. That matters more on this agreement than on a confidentiality one, because money moves — US tax reporting is against a payee whose legal name has to match their tax records.
The ip is stored as acceptedFromIp (before 0.4.0 it was logged and discarded).
Content hash. Set currentTermsHash in config and pass termsHash at acceptance, and a mismatch is refused. That closes the stale-tab case: a page left open across a revision would otherwise record consent to wording that no longer exists. A version string alone can be re-pointed at edited text; a hash cannot. Consumers that do not hash their agreement leave both unset and nothing changes.
Not captured: taxpayer identification numbers. TINs belong to the payout rail, which already collects tax identity and issues the forms. Holding one here would bring encryption-at-rest duties, breach-notification exposure and a retention policy for data this layer has no need to hold. Economy's payout accounts model tax-form kind and status, which is the right shape — you can know a W-9 is on file without holding it.
Payout rails are opt-in, not fallbacks
startPayoutOnboarding reads the affiliate's declared country from their row, so the jurisdiction on the agreement and the one the payout is routed for cannot diverge. Pass country explicitly only as an admin override; a mismatch is logged.
If no registered adapter supports that country, onboarding throws. It does not quietly fall back to the manual rail, as it did before 0.4.0 — that is how an affiliate ends up costing someone real time every month because an adapter happened to be missing. To allow the hand-run rail, call approveManualPayoutRail({ payload, cfg, affiliateId, actor, req | system }), which authorizes the caller, stamps manualPayoutApprovedBy and manualPayoutApprovedAt and logs the approval; it returns { approvedAt, approvedBy, alreadyApproved }, and an affiliate already approved keeps its first stamps. Until then an affiliate in an unsupported country can hold an accepted agreement and an approved status and still not start onboarding. That is the intended state.
Access to the partner row
A partner reads their own affiliates row through the data API; an affiliates:admin holder reads every row. Six fields on that row are admin-only to read:
| Field | Written by |
|---|---|
termsHash | acceptAffiliateTerms |
acceptedFromIp | acceptAffiliateTerms |
firstPayoutReviewed | releaseFirstPayout (an admin may also toggle it in the panel) |
manualPayoutApprovedBy | approveManualPayoutRail |
manualPayoutApprovedAt | approveManualPayoutRail |
terminationWithheldReferrals | terminateAffiliate |
A partner's REST, GraphQL or Local API read with access checks on returns the rest of their row (code, status, termsVersion, termsAcceptedAt and the others) without these six. The package reads them with access off, so payouts, onboarding and termination are unchanged, and a server read with overrideAccess: true still returns all six. The five server-stamped fields (everything above except firstPayoutReviewed) are also closed to API create and update, as applicationApprovedAt is: an admin's API write to them is dropped.
What you change: if your partner dashboard shows whether the manual payout rail is allowed, or the date, read the row with access off on the server (overrideAccess: true) and pass the derived value to the page. A client that read these six fields from its own row over the API now gets nothing for them. The per-collection access override on createAffiliatesLayer still replaces any collection-level rule; the field rules live on the fields.
Server / client posture
This package ships no React surface — no .tsx, no 'use client'. Everything under the root entry is Payload configuration (plain objects and factory functions), safe anywhere a payload.config.ts is evaluated. Everything under /server is Node-only: it talks to Payload directly and to a payment provider only through the stripe-shaped structural argument callers pass in. Keep /server out of any module a browser bundle walks.
Status
All v1 surfaces ship, and 0.7.0 adds lead referrals, tiers, the renewal attribution resolver, inviteAffiliate and the tax-form gate (all opt-in; a site that sets none of the new config behaves as on 0.6.5): collections and access; attribution (signed cookie, click capture, referral binding, checkout attribution, click endpoint); and the money flow (order, renewal and refund handlers, carry-forward reversals, the four jobs, payouts over the economy payouts extension, the affiliate dashboard, admin operations, and consumer actions). 0.8.0 adds the partner terms (signed work, termination and withheld commissions, pause policies, the cap offset and kept-payments count, the renewal basis, the order-refund hook, late credit, proportional reversal, withdraw and manual-rail approval), all opt-in. 0.11.0 adds no renewal cap, terms locked at signing, the run-off after an ending, and applying or being invited again after one, all opt-in. Known deferrals: a refunded subscription invoice does not reverse its renewal commission, because economy dispatches no invoice-refund event (reverse it with reverseCommission); there is no operation to record a commission for a payment taken outside the site, beyond crediting a confirmed lead's earlier payments; a termination cannot be dated in the future, a terminated partner comes back only through applyForAffiliate or inviteAffiliate under program.reapplyAfterEnding (0.11.0), and withheld commissions are never released on a timer; a confirmed, converted claim cannot be stopped early; a payout run has no dry run; tier rates do not vary by product type; and a lead cannot be split between two partners.
Upgrading. affiliate-referrals and affiliate-commissions gain optional fields and select options (a SQL database gets new nullable columns and, depending on the adapter, new enum values), manual stays a valid channel, and affiliates changes only when you set tiers. For the 0.8.0 fields, see Upgrading to 0.8.0 under Partner terms.
Testing
pnpm --filter @wabbit/tome-affiliates testThe suite runs against resolveAffiliatesConfig, createAffiliatesLayer, and assertEconomyPayoutsCollections directly, with no network. Most suites use an in-memory Payload double, which can run the collections' own field validators. One suite, tests/partner-terms-real-db.sqlite.test.ts, boots a real Payload instance on SQLite in a temp file to prove the renewal resolver path and its reversal with Payload's own validation; it loads @payloadcms/db-sqlite from a sibling workspace package and fails, rather than skips, when the adapter cannot be loaded.
Exports
| Import path |
|---|
@wabbit/tome-affiliates |
@wabbit/tome-affiliates/server |
@wabbit/tome-affiliates/version |
Changelog
0.11.xMinor
Four opt-in additions for a written partner agreement whose terms outlive a rate change or an ending.
A program that configures none of them, and passes none of the new arguments, gets exactly 0.10.0's results and writes.
- No renewal cap.
recurringUnlimited: trueon a tier (AffiliateTierConfig), on the affiliate row (a new optional checkbox;inviteAffiliatetakes it too) or in a payment's signed terms means "no cap". It is distinct fromrecurringMonths: 0(no renewal commissions) and from an unsetrecurringMonths(use the next level). Both renewal paths andcreditEarlierPaymentsapply it, andperiodIndexkeeps counting. - Terms locked at signing. A payment may carry
signedTerms(AffiliateSignedTerms:rateBps,recurringMonths,recurringUnlimited,signedAt) onorder.metadata.signedTerms,RenewalAttribution.signedTerms, the subscription row'smetadata.signedTermsorEarlierPayment.signedTerms. Each field present wins over the affiliate's and the tier's current value; the commission records the rate asrateBpsand the date as the newtermsSignedAt. A malformed value throwsAffiliatesConfigErrorand writes nothing. - Run-off after an ending.
terminateAffiliatetakesendingKind(AffiliateEndingKind, listed inAFFILIATE_ENDING_KINDS) and, underterminationPolicy: 'honor-earned',runOffUntilandrunOffReferralIds. UntilrunOffUntilthe ended affiliate's lead referrals keep earning on every payment path and increditEarlierPayments, and the named open referrals are not expired. Which payments belong to qualifying work stays the consumer's rule.affiliateStandingtakes an optional{ runOffUntil, now }. The row gainsendingKindandrunOffUntil. - Applying or being invited again after an ending. With
program.reapplyAfterEnding(days to wait, keyed by ending kind),applyForAffiliatere-opens an ended row once its wait has passed andinviteAffiliatere-opens any ended row; both clear the acceptance stamps so the partner signs again. New refusal reasonsended-invitation-onlyandended-reapply-wait;endedReapplyEligibleAt(from/server) returns the date. Without the policy an ended member is refused as before.
New optional fields only (nullable columns on SQL, nothing on Mongo); no backfill. See the README's "Partner revision (0.11.0)" section.
- No renewal cap.
1 fix (0.11.1)
- 0.11.1
confirmLeadReferralconfirms an ended affiliate's pending lead inside an open run-off (terminationPolicy: 'honor-earned', now beforerunOffUntil) when the lead was registered on or before the row'sterminatedAt.A lead registered after the ending, a closed run-off, or a missing
registeredAtorterminatedAtis refused withreason: 'affiliate-cannot-earn'and writes nothing. Active and paused affiliates are unchanged.The rule is exported from
/serverasaffiliateMayConfirmLead(cfg, affiliate, referral, at?), so a consumer's screens refuse exactly what the package refuses.
0.10.xMinor
BREAKING: six server-stamped fields on the partner row are no longer readable by the partner through the data API; only a holder of
affiliates:adminreads them.Migration: server code that reads the
affiliatescollection withoverrideAccess: trueneeds no change, and every package function already does. If a client or an access-checked read of the partner's own row usedtermsHash,acceptedFromIp,firstPayoutReviewed,manualPayoutApprovedBy,manualPayoutApprovedAtorterminationWithheldReferrals, move that read to the server with access off and pass only the derived value (for example "the hand-run payout rail is allowed") to the page.termsVersionandtermsAcceptedAtstay readable by the partner.- The six fields now carry
affiliatesAdminFieldAccesson read, the rulenotes,rejectionReasonand the tier fields already use. The partner still reads the rest of their own row, and anaffiliates:adminholder reads all six. termsHash,acceptedFromIp,manualPayoutApprovedBy,manualPayoutApprovedAtandterminationWithheldReferralsare also closed to API create and update, the wayapplicationApprovedAtis: the package stamps them with access off, and an admin's API write to them is dropped.firstPayoutReviewedkeeps its admin toggle.- Proven through a real SQLite-backed Payload instance: the partner gets none of the six and still gets the rest of the row, an admin gets all six, and a server read with access off gets all six.
- The six fields now carry
0.9.xMinor
BREAKING: requires
@wabbit/tome-economy0.20.0 or later (the peer floor was 0.12.0), and two operations now refuse calls they used to accept.Migration: upgrade economy to 0.20.0 first and follow its migration note.
confirmLeadReferralnow refuses an affiliate whose standing does not earn on confirmed leads (a terminated affiliate under either policy, a paused one underpausePolicy: 'stop-earning');releaseFirstPayoutrefuses while the pause hold or the tax-form gate would hold the payout.Each refusal is an
AffiliatesOperationRefusedErrorwith a newreason.With
requireTaxFormBeforePayouton, a payout account created bystartPayoutOnboardingstarts with its tax formrequired; before, it startednot-requiredand was paid without a form. UnderpausePolicy: 'hold-payouts'or the tax-form gate, a released first payout is held at the run by the same checks as new items, and the hold is listed inheldForPauseorheldForTaxFormwith the payout's id.Whenever either option is on, the run summary also carries a new
heldkey (the list of released payouts held, possibly empty), which is the only place a hold whose check failed appears; code that compares a whole summary against an expected one needs the key added. Two payout setups started at the same moment now make one payout account and one connected account.New:
inviteApplicantmoves an applicant toinvitedso they can read and sign the agreement, optionally setting a tier and a code, and stamps who approved the application and when (applicationApprovedAt,applicationApprovedBy, two new optional fields; a SQL database gets two nullable columns). Also new:taxFormStatusPaysand a stablereasonon refusals (AffiliatesRefusalReason).
4 fixes (0.9.1 – 0.9.3)
- 0.9.3
A repeat visit from the same person to the same partner link within ten seconds is now counted as one click.
The click endpoint looks for an earlier click with the same affiliate and visitor hash inside
CLICK_REPEAT_WINDOW_MS(10 seconds). If one exists it writes nothing and still answers 204, so the response never shows whether a row was written.The landing path is not part of the match, so a redirect between two requests does not make two clicks.
Before this, a Chromium browser retrying after a
Critical-CHresponse, a double press or a reload each wrote a second row.If the lookup itself fails the click is still recorded. Two posts arriving at the same instant can both be recorded; the repeats this fixes are sequential.
CLICK_REPEAT_WINDOW_MSis exported from@wabbit/tome-affiliates/server. - 0.9.3
Payout setup now hands the partner's signed name or business name to the payout provider, so its setup form does not ask for it again.
startPayoutOnboardingbuilds a payee from the signer fields frozen when the partner accepted the terms and passes it to the rail adapter'screateOnboardingLink. An individual signer gives their signed first and last name.A business signer gives the business's legal name only: the signed first and last name are the authorized person, not the payee, and are never passed as an individual. With the terms not accepted, a needed field empty or an unknown signer type, no payee is passed and setup runs as before.
StartPayoutOnboardingArgsgains an optionalproductDescription, one plain sentence on what the partner does for the program, passed to the adapter when it is not blank. This package writes no description of its own.An adapter uses the payee and description only when it creates the rail account; calls for an existing account carry them and the adapter ignores them. This needs an economy release whose
createOnboardingLinkacceptspayeeandproductDescription; an older adapter ignores both. - 0.9.2
A referral click that fails to record is now reported instead of disappearing without a trace.
captureReferralused to swallow a throwing or rejectingrecordClickwith an empty catch, so a click post that failed on every visit left no sign anywhere. It now passes the error to the new optionalonRecordClickError(error)argument, or, without one, logs it withconsole.error('[tome-affiliates] captureReferral: recordClick failed:', error).The guarantee is unchanged:
captureReferralnever throws becauserecordClickfailed, a throwingonRecordClickErroris swallowed too, and the return value is the same either way. - 0.9.1
The click endpoint and the four job endpoints now answer at
/api/affiliates/...on a site that keeps the defaultaffiliatescollection slug; before, every one of them returned Payload's 404.Payload sends
/api/<collection slug>/...to that collection's own endpoints and never to the root list, so the root routes were shadowed by the collection. The affiliates collection now carries forwarders that hand those requests to the endpoints you mounted at root.Addresses, guards and consumer wiring are unchanged, and a route you did not mount still answers 404.
0.8.xMinor
A program can now keep the terms of a written partner agreement through configuration, all opt-in, and renewal commissions on the
resolveRenewalAttributionpath now save on a real database.A program can now keep a partner agreement's terms: work agreed inside a lead's window finishes earning after it (
program.leads.paymentWindow: 'signed-work', withworkSignedAton the order or the renewal result); ending a partner is an operation that records who, when and why, and underprogram.terminationPolicy: 'honor-earned'moves only what a cause termination names to a newwithheldstatus, settled later byreleaseWithheldCommissionorvoidWithheldCommission; the renewal result can say how many capped periods already earned (priorCappedPeriods) and what part of a charge is commissionable (basisCents); and underprogram.pausePolicy: 'hold-payouts'a paused partner's confirmed leads keep earning while payouts wait. Underprogram.renewalCapCounts: 'kept-payments'a payment refunded in full, or lost to a chargeback, no longer uses a place in the renewal cap.program.commissionableRefundsays what part of a commission's basis a partial order refund took back, or that it cannot tell, in which case nothing is reversed andonRefundUnresolvedis called.creditEarlierPaymentscredits payments made before a lead was confirmed, once each, under the same rules, from when the partner brought the lead (an admin may state that date,earlierPaymentsFrom, for a lead it created), withrefundedBasisCentsfor partly refunded periods.reverseCommissiontakes an optionalamountCentsfor a proportional reversal (reasonpartial-refund). New operationswithdrawLeadReferralandapproveManualPayoutRail.Under
honor-earned, a terminated partner's approved balance is paid in every run whatever the minimum. All opt-in.Also fixes renewal commissions on the
resolveRenewalAttributionpath, which a real database refused because the commission required an economy subscription the path never has.What an upgrading site notices without opting in: new optional fields.
affiliatesgains the termination and pause stamps (terminatedAt,terminatedBy,terminationReason,terminatedWithCause,terminationWithheldReferrals,pausedAt,pausedBy,pauseReason);affiliate-commissionsgainsworkSignedAt,chargedCents,paymentRefunded,creditedLateand the six withhold fields;affiliate-referralsgainsearlierPaymentsFrom,earlierPaymentsFromBy,earlierPaymentsFromAt,withdrawnAt,withdrawnByandwithdrawalReason.The commission
statusselect gainswithheldwhen a program setshonor-earned, andCommissionStatuswidens to include it, so a consumer with an exhaustiveswitchon it gets a type error to handle the new value, which no row holds unless it opts in. A SQL database gets nullable columns, an enum value and a join table forterminationWithheldReferrals; Mongo needs nothing.The renewal commission validator accepts
subscriptionRefin place of the economysubscriptionrelation, and a carry-forward row on that path copiessubscriptionRefandproductType. New exports from the root entry: the option typesAffiliatePaymentWindow,AffiliateTerminationPolicy,AffiliatePausePolicyandRenewalCapCounting,CommissionableRefundContext,UnresolvedRefund,AffiliateStanding,PausedPayoutHold,ReverseCommissionAmountOption,EarlierPayment,EarlierPaymentSkipReason, the argument and result types of the new operations,AffiliatesOperationRefusedError, and the constantsAFFILIATES_PARTNER_TERMS_DEFAULTS,AFFILIATES_REASON_MAX_LENGTHandAFFILIATES_TERMINATION_CONTEXT.New exports from
@wabbit/tome-affiliates/server:terminateAffiliate,releaseWithheldCommission,voidWithheldCommission,pauseAffiliate,resumeAffiliate,creditEarlierPayments,withdrawLeadReferral,approveManualPayoutRail,affiliateStanding,countsTowardCap,earliestCreditablePaymentAtand their types, plusFoundLeadReferral;findLeadReferral's result gainsaffiliateStatusonly underhold-payouts, andRunAffiliatePayoutsSummarygainsheldForPause(only underhold-payouts) andfinalBatch(only underhonor-earned). The economy and Payload peer ranges are unchanged.BREAKING: the
@wabbit/tome-corepeer floor rises to>=1.17.0 <2.0.0(was>=1.16.0), because the numeric-id fix below uses core'srelationIdRaw, first published in 1.17.0. A site on core 1.16.x must update core first; a site on 1.17.0 or later changes nothing.Two more fixes for numeric-id databases (Postgres, or SQLite with default ids). The carry-forward row a reversal of a paid commission writes now keeps each relationship id in the type the original row holds it, so it saves on a numeric-id database; on a string-id database it writes exactly what it wrote before.
And the
actorof every admin operation that stamps it into a relationship (approveAffiliate,rejectAffiliate,createLeadReferral,confirmLeadReferraland the new operations), andterminateAffiliate'swithholdReferralIds, now acceptstring | number: pass ids in your database's own id type. Underkept-paymentsthe economy-subscriptions cap count leaves out carry-forward debit rows, so a renewal refunded in full after payout gives its place back there too; under the default the count is unchanged.
0.7.xMinor
A program can now pay partners for a sale that arrives as a lead and is paid in several pieces.
Everything below is opt-in; a site that sets none of the new config behaves exactly as on 0.6.5.
Lead referrals: set
program.leads.enabledand a partner can register a lead (registerLead), orcaptureLeadFromCookierecords one from the partner's link. An admin confirms it (confirmLeadReferral), declines it (declineLeadReferral) or tags one by hand (createLeadReferral).Your site stamps
metadata.referralId, found withfindLeadReferral, on every order for the lead, and each of those orders earns commission untilearnsUntil(12 months after confirmation by default).extendLeadReferralmoves the claim deadline, andgetAffiliateLeadsreturns a partner's own leads with what each has earned.The layer stores only a label and a note for a lead, never a prospect's contact details.
Tiers:
program.tiersdefines named tiers with a default rate and renewal cap, anddefaultTiernames the one given to new partners. A partner's own rate and cap still win, then the tier's, then the program's.The new
inviteAffiliatecreates an invited partner, andapproveAffiliatetakes an optionaltier.Renewal attribution:
resolveRenewalAttributionlets a site whose subscription records are not economy's say which referral a recurring charge belongs to. Renewal commissions now carrysubscriptionRefandproductType.The README explains the idempotency key and the first-activation case.
Payouts:
program.requireTaxFormBeforePayoutholds a payee whose payout account has no tax form on file (required, or no status) out of a payout run;collected,verifiedandnot-requiredare paid. Held payees are listed inheldForTaxForm, and their commissions stay approved for the next run.Two things an upgrading site will notice without opting in. The referral and commission collections gain optional fields and select options (
registeredchannel,pendingstatus, two rejection reasons, lead fields on referrals,subscriptionRefandproductTypeon commissions), so a SQL database gets new nullable columns;manualstays a valid channel.And
ExpireReferralsSummarygainsexpiredPendingLeads, which is 0 while lead referrals are off.New exports: types
AffiliateLeadsConfig,AffiliateTierConfig,RenewalAttributionContext,RenewalAttributionandAffiliateLead, and the constantAFFILIATES_LEADS_DEFAULTSfrom the root entry; the lead operations and their argument types,inviteAffiliate,addCalendarMonths,HeldPayoutandRunAffiliatePayoutsSummaryfrom@wabbit/tome-affiliates/server.
0.6.xMinor
BREAKING: the admin operations
approveAffiliate,rejectAffiliate,releaseFirstPayout,reverseCommission,syncAffiliatePromotionCodeandrotateAffiliatePromotionCodenow authorize in-function.Each args object takes the admin's
req(checked by the newassertAffiliatesAdmin(req)—affiliates:admincapability, super-admin, or a legacy admin role) or an explicitsystem: truefor trusted server code with no session; without either, or for a non-admin session, the call throws the newAffiliatesAuthorizationError(codeaffiliates-not-authorized) before any write. Previously the contract was "callers are responsible for checkingisAffiliatesAdmin", and every write runs withoverrideAccess: true, so a consumer that wrapped one of these as a server action without its own gate shipped an open money-moving endpoint.Migration: pass
req(orsystem: true) in each call.Logging goes through
payload.logger, not stdout.Terms acceptance logs at info WITHOUT the accepting IP (the IP is still stored on the row as consent evidence, never logged); admin payout release / commission reversal notices use
payload.logger.info; a failed affiliate lookup during checkout attribution now logs a warning instead of silently dropping the order's commission attribution.Jobs and handlers no longer silently truncate at 1000 (or 5000) rows.
approveMaturedAffiliateCommissions,expireAffiliateReferrals,purgeAffiliateClicks, the payout run's approved-commission scan, the velocity review, the refund handler's order-commission scan and the carry-forward sum now page with core'sfindPaged; the renewal period index usespayload.count. Independent per-row writes (approve/expire/purge, velocity flag, mark-paid) run through core's bounded-concurrencybatchWrite; in the three jobs a failing row is logged and counted instead of aborting the run.Job summaries gain optional
failedandtruncatedfields (a truncated scan converges on the next run). Refund reversals stay sequential on purpose (money movement).The package-local
relationIdinserver/commissions(same name as core's, but returning''instead ofnull) is removed.Every call site now uses core's
relationIdwith an explicit?? '', so behavior is unchanged. The two attribution helpers' privaterelationshipIdcopies also use core's reader.
6 fixes (0.6.1 – 0.6.5)
- 0.6.5
Admin labels, field descriptions, demo content and messages now use American spellings.
- 0.6.4
README: subpath and file mentions are written package-qualified (for example
@wabbit/tome-x/render) or as code text, so crawlers no longer resolve them as site URLs. - 0.6.3
Order commissions no longer include shipping: the basis is now the paid total less tax and less the Order's
shippingCents.Orders without
shippingCents(every single-item checkout, and Orders from economy releases before the field) read it as 0, so their commission basis is unchanged. - 0.6.2
Published packages now contain compiled JavaScript and type declarations under a one-line license banner, and no longer include source maps.
What you install: one compiled
.js(ESM) and.cjs(CommonJS) file per source module, its.d.ts/.d.ctsdeclarations, and the stylesheets, fonts and other assets a package already shipped. Every JavaScript module opens with a comment naming the package and its license:/*! @wabbit/<package> — © Wabbit, LLC. Wabbit Tome Commercial License (see LICENSE.md). Not for redistribution. */.The
.mapfiles and thesourceMappingURLcomments that pointed at them are gone, which roughly halves the size of each tarball.Debugging: the code is still unbundled and unminified, one readable file per module, so a stack trace points at real code with real names. Line numbers in a stack trace are one higher than before, because of the banner line.
A
'use client'directive stays the first statement of its module (the banner is a comment above it), so React Server Component boundaries are unchanged.No API change, no runtime behavior change, and nothing to do on upgrade.
In
@wabbit/tome-blocks-gallery, the source snapshotsextractGallerySourcewrites from an installed pack leave out the license banner line, so a component or config snapshot starts at the code and a paid block's preview shows its first 15 lines of real code. - 0.6.1
Internal refactor: collection slugs are now typed through the shared
typedSlug()helper instead of inline casts.No API or behavior change.
- 0.6.1
customer-facing wording: internal references removed from admin descriptions, error messages and block metadata.
0.5.xMinor
Promotion codes now follow the affiliate's status, and a leaked code can be rotated.
- New optional
setPromotionCodeActive({ promotionCodeRef, active })config callback. The affiliates collection calls it whenever an affiliate crosses into or out ofactive. Pausing or terminating an affiliate deactivates their code in the payment provider, and reinstating them reactivates it. Before this change, a stopped affiliate's code kept giving buyers the discount while crediting nobody. The hook never throws: a provider failure is logged loudly and the status change stands. A missing callback produces a warning. - New
rotateAffiliatePromotionCode(server entry). It deactivates the current code first, then mints a replacement with different text on the same coupon and links it to the affiliate. Reusing the old text is refused, because it would put the leaked code back into circulation. - Compile-time contract extended: a real Stripe client must fit rotation's structural
promotionCodes.update/.createshape.
- New optional
0.4.xMinor
Signer identity, a stored acceptance IP, a terms content hash, and an opt-in manual payout rail.
Why: the receipt for an agreement that authorizes payouts was weaker than the one a consumer keeps for a confidentiality agreement.
acceptAffiliateTermswrote three fields — version and two timestamps — and took anipit logged and threw away.There was no record of _who_ signed (a member relationship, whose profile name the member can edit), _from where_, or _what exactly_ they agreed to (a version string can be re-pointed at edited wording).
`acceptAffiliateTerms` now requires a `signer` —
{ type: 'individual' | 'business', firstName, lastName, businessLegalName?, country }— and freezes it onto the affiliate row assignerType/signedFirstName/signedLastName/businessLegalName/country. Copied, never joined: a record resolving its signatory through a mutable profile field records nothing durable, and it matters more here than on an NDA because US tax reporting is against a payee whose legal name has to match their tax records.businessLegalNameis required for a business signer and discarded for an individual;countrymust be ISO 3166-1 alpha-2 and is uppercased.The IP is stored as
acceptedFromIpinstead of only logged.`termsHash` is optional on both sides. Pass
currentTermsHashin config andtermsHashat acceptance and a mismatch is refused — the stale-tab case, where a page left open across a revision would otherwise record consent to text that no longer exists. Consumers that do not hash their agreement are unaffected.Deliberately not captured: any taxpayer identification number. TINs belong to the payout rail, which already collects tax identity and issues the forms. Holding one here would bring encryption-at-rest duties, breach-notification exposure and a retention policy for data this layer has no need to hold.
BEHAVIOR REMOVED — `startPayoutOnboarding` no longer falls back to the manual rail silently. It previously resolved
connectAdapter ?? manualAdapter, so an affiliate in a country no Connect adapter supported landed on a hand-run rail because an adapter happened to be missing. The manual rail is now opt-in: it requiresmanualPayoutApprovedBy/manualPayoutApprovedAton the affiliate row, set by an admin.Without that approval an unsupported country throws, naming the country. An affiliate in that state holds an accepted agreement and an approved status but cannot start onboarding — that is the intended state, not a bug.
startPayoutOnboarding'scountryargument is now optional and sources from the affiliate row's declared country, so the jurisdiction on the agreement and the jurisdiction the payout is routed for cannot diverge. Passing it explicitly still works as an admin override and logs a warning on mismatch.Migration: a single production consumer exists today. Callers of
acceptAffiliateTermsmust addsigner; callers ofstartPayoutOnboardingmay dropcountry.Rows signed before this release keep working —
termsHashand the signer fields are simply absent on them.
2 fixes (0.4.1 – 0.4.2)
- 0.4.2
Fix
syncAffiliatePromotionCodefor current Stripe API versions, and make it idempotent.Stripe API
2025-09-30.cloverremoved the top-levelcouponparameter from promotion-code creation in favor ofpromotion: { type: 'coupon', coupon }. ThestripeNode SDK v22 pins2026-04-22.dahlia.This function still sent the removed parameter, so it would have failed the first time a consumer called it — it had never been called, and its only test used a mock that accepted the old shape. The structural
stripeargument type changes to match.It is now also idempotent: an affiliate that already has a
promotionCodeRefis returned without calling Stripe (Stripe rejects a second active code with the same text), and the result carriescreated: boolean.A compile-time contract (
src/server/stripe-promotion-code.contract.ts, excluded from the build) asserts a realStripeclient satisfies the structural shape, so the next SDK change of this kind failstypecheckhere instead of an approval in production.stripeis added as a devDependency for that file only. - 0.4.1
Fix
AFFILIATES_LAYER_VERSIONreporting'0.3.0'in the 0.4.0 release.0.4.0 was versioned with a bare
changeset versioninstead of the repo'spnpm version-packages, which also runssync-layer-versions. So the published package'spackage.jsonsaid 0.4.0 while the exported layer-version constant — the valuecreateAffiliatesLayerregisters the layer under — still said 0.3.0.All 0.4.0 behavior (signer identity, stored IP, terms hash, opt-in manual rail) shipped intact; only the self-reported version was wrong. This release re-syncs the constant.
Consumers should take 0.4.1 rather than 0.4.0.
0.3.xMinor
applyForAffiliatestores an applicant's own answers andrejectAffiliategives admins a way to turn one down; a rejected applicant can try again after a configurable window.The
affiliatescollection gains five fields:application(an admin-visible, read-only array of{ key, label, value }answers),applicationSubmittedAt,rejectedAt,rejectedBy, andrejectionReason(admin-only, likenotes).statusgainsrejected, and thetermsVersion-required rule now exemptsrejectedalongsideinvited/applied— a rejected applicant never accepted terms, so the row was wrongly unsavable before this change.applyForAffiliatetakes an optionalapplication?: AffiliateApplicationAnswer[]argument and stampsapplicationSubmittedAtserver-side. Its re-application rule replaces the old blanket "member already has an affiliate row" throw for the one case that used to dead-end permanently: arejectedrow.Once
rejectedAt + program.reapplyAfterDayshas passed (newAffiliateProgramConfig.reapplyAfterDays, default 30;0means immediately), callingapplyForAffiliateagain for that member UPDATES the same row instead of creating a second one —applied, a freshappliedAt/answers, and the rejection fields cleared — with the requested code changed only if it is free. Inside the window it throws, naming the date re-application opens.Every other existing-row status still throws as before.
rejectAffiliate({ payload, cfg, affiliateId, actor, reason? })mirrorsapproveAffiliate: only frominvited/applied(throws otherwise, naming the status), setsstatus: 'rejected', stampsrejectedAt/rejectedBy, and recordsrejectionReasonwhen given.No breaking change to any existing export's signature —
applicationandreasonare both optional, andreapplyAfterDaysdefaults. Consumers onenrollment: 'invite-only'are unaffected.
0.2.xMinor
registerAffiliateHandlersuses economy's keyed registration instead of its own globalThis bookkeeping.The hand-rolled registry entry (a
Symbol.for('@wabbit/tome-affiliates/handlers')slot holding a bundled unsubscribe, plus an early return on the second call) is replaced by passing a stablekeyto each of the three economy registrations. Same guarantee — a repeat call never leaves a second copy of any handler registered — with the bookkeeping now living in the registry that owns the problem.One semantic shift is deliberate: a repeat call now RE-registers with the config it was handed and returns a fresh unsubscribe, where before it ignored the new config and returned the first call's unsubscribe. Last config wins, which is what you want under HMR and when a later caller passes updated settings.
An unsubscribe returned by a superseded call is inert rather than destructive, because economy releases a key only if the handler holding it is still the live one.
RELEASE COUPLING — read before publishing. This now calls a two-argument registration API that only exists in the
@wabbit/tome-economyrelease carrying keyed registration.The peer floor is currently
>=0.11.0 <1.0.0and MUST be raised to that release's version. JavaScript does not throw when a second argument is passed to a one-argument function, so an affiliates build resolved against an older economy would ignore{ key }and silently fall back to append-every-time — losing the dedupe with no error, which is the exact failure class this pair of changes exists to remove.The floor is intentionally left unbumped here because version numbers belong to the release train, not to this changeset.
0.1.xMinor
Initial release.
A referral attribution and commissions layer built on
@wabbit/tome-economy0.11.0's seams and payouts extension (layer spec 2026-09-14).Collections.
affiliates,affiliate-referrals,affiliate-clicks, andaffiliate-commissions, all slug-overridable. Admin access uses theaffiliates:admincapability; an affiliate reads only their own row.GDPR registration: affiliates soft-anonymize, referrals null the referred member, commissions are retained. Terminating an affiliate voids their pending commissions and expires their open referrals.
Attribution. A signed referral cookie (Web Crypto HMAC, safe on the Edge runtime) that is only set with marketing consent when
requireMarketingConsentis on, a daily-rotating visitor hash,captureReferralfor middleware,bindReferralToMemberat signup (last click wins, self-referral rejected),resolveCheckoutAttributionfor checkout metadata, and a signedPOST /affiliates/clickendpoint. Promotion codes attribute without a cookie and win over links by default.Money flow. Order, subscription-renewal, and order-refund handlers on economy's dispatchers. Commissions snapshot the rate and pay on the amount actually paid before tax, optionally narrowed by
commissionBasis.Partial refunds reverse proportionally; a refund after payout becomes a negative carry-forward row netted against the next payout. A velocity control flags bursts of conversions from one visitor for review.
Four jobs: approve matured commissions, run payouts, expire referrals, purge clicks. Payouts run through economy's
runPayoutBatch, and each affiliate's first payout waits for admin review.Wiring.
createAffiliatesLayer(config)returns collections, endpoints, jobs, andregisterHandlers. Handlers reach Payload throughconfig.getPayload.Consumers call
assertEconomyPayoutsCollectionsandregisterAffiliatePayoutAdaptersfromonInit. Requires@wabbit/tome-core>=1.16.0 and@wabbit/tome-economy>=0.11.0.Known deferral: a refunded subscription invoice does not reverse its renewal commission, because economy dispatches no invoice-refund event yet.