Cart Discount Coordination Engine

Unifying independent discount systems into a single, trustworthy cart interface.

Role: Lead Developer Reported: deployed to 8 storefronts Stack: JS · Shopify Ajax Cart · Rebuy Smart Cart · Event-Driven Architecture

The Problem

Three independent systems (platform, third-party cart, user input) apply discounts in isolation. When systems don't communicate cleanly, users see inconsistent prices and lose trust. Example: cart displays €100, checkout shows €85—no explanation of where the €15 went.

The result? High support volume from pricing confusion, abandoned carts, and eroded customer confidence.

Before: Customer Experience Breakdown

Cart shows: €100 - 10% discount = €90
Checkout charges: €76.50 (15% auto + 10% manual applied)
Customer reaction: "Why did the price change? This feels like a bait-and-switch."

Result: Weekly support tickets, cart abandonment, lost trust

After: Transparent Pricing

Cart preview: €76.50 (automatic 15% + manual 10% = €23.50 savings)
Checkout shows: €76.50 (matches exactly)
Customer reaction: "Clear pricing, I know what I'm paying."

Result: Zero pricing discrepancy complaints, completed purchases, retained trust

The Solution

Built a unified coordination layer around Rebuy events and Shopify cart state: detect active discount mode, calculate line-level impact with mathematical precision, and render truthful prices in real-time. Cart totals now match checkout in the critical scenarios this system handles.

Key Technical Decisions

State Signature Tracking
Instead of reprocessing on every cart change, I track a "signature" of the current discount + items. If nothing has changed, skip recalculation. This prevents unnecessary DOM thrashing on high-traffic carts.

Proportional Allocation with Rounding Reconciliation
When applying a discount across multiple items, naive rounding causes €0.01 discrepancies. Implemented a two-pass algorithm: first allocate proportionally, then reconcile remainders to ensure the total always matches expectations exactly.

Platform-Aware Mode Detection
Discovered that automatic discounts and URL-based discounts are managed differently by the platform. Rather than fight this, I built the system to detect which mode is active and defer to the platform when appropriate—only applying custom logic for manual codes. This means working with platform constraints rather than against them.

Multi-Mode Combination Handling
Recently added dynamic multiples support (3-for-2, 4-for-3 patterns). The tricky part: when customers combine a multiples code with a percentage discount, we need to calculate which items are free vs. discounted, then allocate the percentage across only the paid items. System now detects this scenario and handles it correctly.

Architecture (High Level)

Each handler is modular, but coordination is centralized through RebuyEventManager (event flow) and RebuyUtils (shared discount/cart utility layer).

What Changed Since the Previous Version

Multiples handling is now generalized beyond only 3-for-2. The active implementation supports both 3-for-2 and 4-for-3 patterns, including combination handling with percentage/fixed discounts and checkout-level discount states.

Technical Challenges

Mathematical Precision: Ensuring proportional discount allocation across mixed cart items (percentage vs. fixed amounts) while maintaining subtotal accuracy. When distributing a 15% discount across items with different prices, simple proportional math creates rounding errors. Solved with a two-pass algorithm that reconciles remainders.

Complex Combinations: When multiples (3-for-2, 4-for-3) combine with percentage discounts, the system must identify which items are free, allocate the percentage discount only to paid items, and display both discount types clearly. This is difficult to represent natively in the cart. Automatic and URL-driven discounts rely on Shopify cart/checkout state, while manual discount input originates in Rebuy Smart Cart UI. That creates a gap: customers can see one price in cart and another at checkout unless the system reconciles source-of-truth rules per mode. The coordinator detects which mode is active (manual preview vs checkout-level/automatic), then applies the correct UI strategy so the cart preview stays aligned with checkout behavior.

Debugging at Scale: The implementation includes module-level debug toggles for cart callbacks, free gifts, multiples, URL input behavior, bundle updates, and automated discount handling. Reported production usage spans multiple storefront configurations, so visibility into timing and state transitions was essential.

Impact

What I Learned

1. Work With Constraints, Not Against Them
Discovering that certain discount types are managed at checkout level was a turning point. Instead of fighting the platform, I focused on providing accurate preview prices for scenarios it doesn't handle natively. This shifted the architecture from "force everything to match" to "coordinate smartly where gaps exist."

2. Incremental Refactoring Beats Big Bang Rewrites
The system evolved through phased improvements (M0-M7 milestones) rather than a risky full rewrite. This allowed continuous production deployment across 8 storefronts without customer-facing disruptions. Each phase added one improvement—state signatures, then allocation precision, then mode detection—building confidence incrementally.

3. Debug Visibility Is Critical at Scale
Module-level debug toggles (RebuyCartCallbacks.debug(true), FreeGiftHandler.debug(true), etc.) saved hours of troubleshooting when edge cases appeared across different storefronts. Being able to trace event flow and state transitions in production (via browser console) was invaluable for diagnosing timing issues and discount mode conflicts.

4. Mathematical Precision Matters in Production
Early versions had €0.01 rounding errors when allocating percentage discounts across items. These tiny discrepancies eroded customer trust. The two-pass allocation algorithm (proportional distribution + remainder reconciliation) eliminated these errors. Lesson: in e-commerce, cent-level accuracy isn't optional—it's the foundation of trust.

Future Improvements