Skip to main content
Samrat Dutta Roy
Back to selected work
[01]·Enterprise Workflow Architecture

Stadium — Corporate Pre-Approval State Machine & Contact Selection Engine

Pure functional state machine managing multi-step corporate gift recipient selection, enterprise pre-approval workflows, and O(changes) mutation payloads across 10,000+ contacts.

Role

Enterprise Workflow Architecture · Vinsol | Stadium

Status

Shipped to Production

Domain

Systems & Architecture

Deployment

Production Application
ReactTypeScriptApollo GraphQLDynamic ImportsContext APIState MachinesSCSS ModulesLaunchDarkly

Key Outcomes & Verified Highlights

  • Structured the ordering wizard with code-split lazy loading so heavy enterprise forms only load when needed, keeping initial page load fast.
  • Built a credit pre-approval system that lets corporate managers approve spending allowances for hundreds of gift recipients.
  • Created a responsive recipient directory featuring live search, sorting, and mobile-friendly drawer views.
  • Added permission checks to ensure only authorized account owners can approve company funds or modify orders.

01 — Context & Enterprise Setting

Stadium enables enterprise companies to orchestrate corporate gift and reward campaigns for distributed workforces — ranging from 25-person team rewards to 10,000+ recipient holiday distributions across international offices.

A critical enterprise requirement is pre-approval: an administrator or department lead pre-approves spending allowances for specific recipients so gifts dispatch automatically upon recipient address confirmation without requiring manual per-order redemption approvals.

For a small team of 10 people, pre-approval is simple boolean state. But for an enterprise campaign featuring a paginated directory of 10,000+ contacts, complex active search filters, multi-select bulk operations, and CSV imports, managing pre-approval state is an intricate distributed state coordination challenge.


02 — The Architectural Problem

Why Standard Checkbox State Breaks at Scale

In an enterprise campaign, contact directories frequently exceed 10,000 records. Administrators interact with this dataset through a paginated interface (25–50 contacts per page) with real-time server-side search and multi-facet filtering. A user can:

  1. Select All contacts matching the current filter query (not just the currently loaded page).
  2. Uncheck specific individual recipients from that bulk selection.
  3. Refine search criteria to locate and toggle approvals for specific departments.
  4. Import contacts via CSV, introducing new contacts outside the active filter query.
  5. Finalize Checkout, at which point the client must serialize an exact, deduplicated payload specifying which recipients are pre-approved.

Failure Modes of Naive Array State

A naive array implementation (preApprovedIds: string[]) fails under enterprise constraints:

  • Memory Overhead: Storing 10,000+ IDs in client memory creates high heap allocation, garbage collection pauses, and sluggish UI responses.
  • Filter Leakage: If a user filters by "Finance", selects all, then clears the search filter, unconstrained state would silently retain approvals for hidden contacts that were never explicitly verified.
  • CSV Inconsistency: CSV-imported contacts exist outside the server query pagination state, causing ID collisions or dropped approvals upon table re-renders.

The Solution: Dual-Mode Inverted Exclusion Model

Rather than tracking every individual approved contact, the architecture employs an inclusion/exclusion state model with two mutually exclusive operating modes:

  • Individual Mode: Tracks only explicit, positively selected approvals (includeIds).
  • Select-All Mode: Inverts state tracking by assuming global approval while recording only explicit opt-outs (excludeIds).

This reduces state complexity from (where is 10,000+ contacts) to (tracking only user-initiated changes).


03 — Architecture: Component & State Topology

Architectural Blueprint · System Topology
[ Paginated Table / Contacts Drawer ]         [ Search & Filter Context ]
                  │                                        │
                  ▼                                        ▼
┌────────────────────────────────────────────────────────────────────────┐
│                        Recipient Selection Layer                       │
│        (Coordinates global selection state and active viewport pages)  │
└───────────────────────────────────┬────────────────────────────────────┘
                                    │
                       Sync on toggle / select-all
                                    │
                                    ▼
┌────────────────────────────────────────────────────────────────────────┐
│                   PRE-APPROVAL STATE MACHINE ENGINE                    │
│                                                                        │
│  ┌─────────────────────────────┐      ┌─────────────────────────────┐  │
│  │    Individual Mode State    │      │    Select-All Mode State    │  │
│  │  • isSelectAll: false       │      │  • isSelectAll: true        │  │
│  │  • includeIds: Set<string>  │      │  • excludeIds: Set<string>  │  │
│  └──────────────┬──────────────┘      └──────────────┬──────────────┘  │
│                 │                                    │                 │
│                 └─────────────────┬──────────────────┘                 │
│                                   │                                    │
│                 Deterministic Transition Handlers:                     │
│                 (currentState, actionPayload) => nextState             │
│                 • syncOnRecipientDeselect                              │
│                 • syncOnEnterSelectAll (Constraint-Aware)              │
│                 • resetSelectAllPreApprove                             │
│                 • confirmModalBatchApply                               │
│                 • reconcileWithCsvImport                               │
└───────────────────────────────────┬────────────────────────────────────┘
                                    │
                        Checkout Trigger
                                    │
                                    ▼
┌────────────────────────────────────────────────────────────────────────┐
│                  O(Δ) Payload Serializer & Mutation                    │
│     (Transmits only state differentials: minimal network payload)      │
└────────────────────────────────────────────────────────────────────────┘
Monorepo Architecture Flow

04 — State Machine Specification

Core State Contract

typescript
interface PreApproveState {
  /** When true, all query-matching contacts are pre-approved except those in excludeIds */
  isSelectAll: boolean;
  /** Explicit approvals when in Individual Mode */
  includeIds: string[];
  /** Explicit opt-outs when in Select-All Mode */
  excludeIds: string[];
}

Deterministic State Transitions

User TriggerIndividual Mode BehaviorSelect-All Mode BehaviorInvariant Guaranteed
Recipient UncheckedRemove ID from includeIds.Add ID to excludeIds only if previously approved.Unchecked recipients can never enter the pre-approval batch.
Enter Select-AllKeep prior approvals, but intersect with active filter query.Invert state: clear includeIds, initialize empty excludeIds.Contacts outside active filter scope are never silently approved.
Exit Select-AllPrune unselected IDs from includeIds.Materialize selectedIds minus excludeIds into includeIds.State stays mathematically identical to user intent upon mode switch.
Search Filter ChangePreserve explicit session approvals.Reset excludeIds to prevent cross-filter exclusion leakage.Search transitions do not contaminate pre-approval sets.
CSV Bulk IngestionMerge CSV contact IDs into includeIds.Exclude list remains intact; CSV batch tagged for inclusion.External contacts seamlessly integrate without UI re-fetching.

05 — Key Technical Highlights

1. Constraint-Aware Intersection Logic

When an administrator applies a search filter (e.g. searching "Finance"), selects all, and later alters their search, a critical vulnerability in naive state machines is approval leakage—approvals persisting for contacts that are no longer part of the visible or intended campaign segment.

The transition engine enforces strict constraint-aware intersection: whenever select-all mode is entered under active filter constraints, existing session approvals are intersected with the query results. Out-of-scope contacts are safely discarded before state mutation.

2. Payload Serialization

Upon order submission, the backend API does not require a monolithic array of 10,000 IDs. The serializer translates the internal state into an operational differential:

  • If in Select-All Mode, it transmits a single boolean flag with an array of explicit opt-outs.
  • If in Individual Mode, it transmits only explicit positive selections.

This reduces the JSON payload size from ~350 KB down to < 2 KB, ensuring lightning-fast checkout submissions even on low-bandwidth mobile connections.

3. Pure Functional Transitions & Testing

Every state mutation is implemented as a pure mathematical reducer: (state, action) => nextState. Because functions perform zero DOM side-effects and rely on immutable data structures, the state machine was tested with 100% test coverage across complex sequence edges:

  • Approve ➔ Deselect ➔ Re-approve round-trip equivalence.
  • Rapid pagination and filter switching during active selection.
  • Concurrent CSV file parsing and manual table selections.

06 — Measurable Engineering Impact

  • Zero Approval Leakage: Verified elimination of accidental auto-approvals across 10,000+ contact enterprise campaigns.
  • Network & Memory Scale: Client-side state allocation reduced from to , maintaining consistent 60fps UI performance regardless of recipient list size.
  • Sub-Millisecond State Transitions: Pure functional transition logic executes in under 2ms, providing zero-lag feedback on select-all and deselect operations.
  • Round-Trip Mathematical Determinism: Full test suite verifying that arbitrary sequences of selecting, unselecting, and mode-switching always settle on the exact expected state.