Skip to content

PromoCodeRegistry

Global singleton Durable Object (id: "global") for unified promo and referral code management with atomic validation.

Purpose

PromoCodeRegistry is the single source of truth for all discount codes in the system. It unifies campaign codes (admin-created) and referral codes (user-generated) into one table, providing atomic validate-and-record operations that prevent race conditions.

  • Single global instance (id: "global")
  • Atomic validate + record eliminates TOCTOU races (single-threaded DO guarantee)
  • Snapshot system freezes discount terms at first use — renewals are immune to code changes
  • Calculated status at read-time — no stale state

High-Level Design

Core Responsibilities

┌─────────────────────────────────────────────────────┐
│                 PromoCodeRegistry                   │
│                                                     │
│  ┌─────────────────────┐  ┌──────────────────────┐  │
│  │ PromoCodeStorage    │  │ PromoCodeValidation  │  │
│  │ Manager             │  │ Manager              │  │
│  │                     │  │                      │  │
│  │ • CRUD operations   │  │ • 11 validation      │  │
│  │ • Snapshot system   │  │   rules              │  │
│  │ • Referral code gen │  │ • Atomic validate +  │  │
│  │ • Usage tracking    │  │   record             │  │
│  │ • Renewal cycles    │  │ • Referrer           │  │
│  └─────────────────────┘  │   eligibility        │  │
│                           └──────────────────────┘  │
│  ┌─────────────────────┐  ┌──────────────────────┐  │
│  │ SystemSubscription  │  │ RebateProgram        │  │
│  │ DiscountManager     │  │ Manager              │  │
│  │                     │  │                      │  │
│  │ • Admin-granted     │  │ • Tiered rebate      │  │
│  │   one-off discounts │  │   programs           │  │
│  │ • Per-subscription  │  │ • Global + Custom    │  │
│  │   lifecycle         │  │   KOL tiers          │  │
│  └─────────────────────┘  │ • Monthly referral   │  │
│                           │   count → rebate $   │  │
│                           └──────────────────────┘  │
└─────────────────────────────────────────────────────┘

Managers

ManagerRole
PromoCodeStorageManagerCRUD, snapshot creation, referral code generation, usage tracking, renewal cycles
PromoCodeValidationManager11-rule validation pipeline, atomic validate-and-record, referrer eligibility check
SystemSubscriptionDiscountManagerAdmin-granted per-subscription discounts with race-safe lifecycle
RebateProgramManagerTiered rebate programs (Global + Custom KOL), monthly referral count resolution

Unified Code Model

Campaign and referral codes share the same promo_codes table, distinguished by referralWalletUserId:

TypereferralWalletUserIdisSystemGeneratedCreated By
Campaign codenullnot setAdmin
System referralsettrueAuto from wallet (ACE-{FIRST5}-{LAST3})
Custom referralsetfalseUser-chosen

All codes are uppercase, case-insensitive (3-30 chars, [A-Z0-9-]).

Atomic Validate-and-Record

The central operation is validateAndRecordUsage() — a single-threaded DO method that validates and records in one call, eliminating TOCTOU races:

validateAndRecordUsage(code, userId, plan, ...)

  ├─ "subscription" flow (first use)
  │   ├─ Run 11 validation rules
  │   ├─ transactionSync {
  │   │     Create snapshot (freeze discount config at point-in-time)
  │   │     Increment usage count
  │   │     Insert usage record (UNIQUE constraint = second defense)
  │   │   }
  │   └─ Return discount amount + final price

  └─ "renewal" flow (subsequent billing cycles)
      ├─ Look up existing usage → snapshot
      ├─ Validate discountCycles not exhausted
      ├─ Increment totalBillingCyclesApplied
      └─ Return discount from snapshot (not current code)

Snapshot system: On first use, a snapshot captures the code's discount configuration (discount type, value, applicable plans, cycles). All future renewals use this snapshot, so admin changes to the code don't retroactively affect existing subscriptions.

A separate read-only verifyPromoCode() method runs the same validation without recording — used for UI discount preview before payment.

Validation Rules (in order)

  1. Code exists
  2. Code is active (not disabled)
  3. Not before validFrom (CODE_NOT_YET_VALID)
  4. Not after validUntil (CODE_EXPIRED)
  5. Global usage limit not exceeded
  6. Cannot use own referral code (wallet match)
  7. User hasn't already used this code
  8. Per-user usage limit (enforced by UNIQUE index on (user_id, promo_code_id))
  9. Plan applicability (empty = all plans)
  10. User type applicability (new vs returning)
  11. Payment method applicability

Referral Code Flow

User wallet → generateReferralCode()

  ├─ Check existing (idempotent)
  ├─ Generate ACE-0X12345-ABC format
  ├─ Handle collision (append -1, -2, ...)
  └─ Create with defaults:
       10% off, 1 cycle, STANDARD/PRO only, new users only

Referee subscribes with code

  ├─ validateAndRecordUsage() in PromoCodeRegistry
  └─ recordReferral() in referrer's ReferralManager
       ├─ Check referrer eligibility (active subscription — verified upstream by caller)
       ├─ Calculate rebate via PromoCodeRegistry.calculateRebateAmounts()
       └─ Record with status eligible/ineligible

Rebate Priority Resolution

When calculating referral rebates, the system resolves which program applies:

Custom KOL program (per-user)  →  highest priority
        ↓ (if none)
Global tiered program          →  mid priority
        ↓ (if none)
Legacy defaults ($4/$40/$68)   →  fallback

Tier selection is based on last calendar month's referral count. Tiers must be contiguous (no gaps), and only the last tier may be unbounded.

System Subscription Discounts

Separate from promo codes — admin-granted one-off discounts attached to a specific subscription:

  • One active discount per subscription (UNIQUE partial index)
  • Lifecycle: activeexhausted (auto when cycles hit limit) or cancelled (manual)
  • Race-safe mutations via WHERE status = 'active' + rowsWritten check
  • Not idempotent: incrementCyclesApplied has no dedup guard — caller must ensure single invocation per renewal

Edge Cases & Design Decisions

  • Status is calculated, not stored: calculatePromoCodeStatus() derives status at read-time from isActive, usage limits, and time window — avoids stale status data.
  • Delete restriction: Only "scheduled" codes (future validFrom) can be hard-deleted; active/expired codes persist for audit.
  • Custom-to-system discount sync: Updating a custom referral code's discountValue syncs to the system-generated code for the same wallet, keeping discount offers consistent. Only discountValue is synced — other fields are independent.
  • Renewal idempotency: incrementRenewalCycle guards with WHERE last_discounted_renewal_at < ? to prevent double-counting the same renewal.
  • Self-referral prevention: CANNOT_USE_OWN_CODE error if referral code's wallet matches the user (case-insensitive).

See Also

  • UserPaperTradePortfolioSubscriptionManager calls validate/record; ReferralManager calls generate/lookup/rebate