Unifying independent discount systems into a single, trustworthy cart interface.
Three independent systems — the Shopify platform, the Rebuy Smart Cart, and manual customer input — apply discounts in isolation. When they don't reconcile cleanly, a customer sees one price in the cart and a different one at checkout, and loses trust.
Before
Cart shows €100 − 10% = €90; checkout charges €76.50, because a 15% automatic discount stacks with the 10% manual code.
"Why did the price change? This feels like a bait-and-switch."
After
Cart preview shows €76.50 (15% automatic + 10% manual = €23.50 saved); checkout matches exactly.
"Clear pricing, I know what I'm paying."
The result was recurring weekly support tickets, cart abandonment, and eroded customer confidence.
A coordination layer built around Rebuy events and Shopify cart state: detect the active discount mode, reconcile the authoritative line-level impact, and render truthful prices in real time. Cart totals now match checkout in the critical scenarios the system handles — including stacked URL and automatic promotions.
State signature tracking. Rather than reprocessing on every cart change, the system tracks a signature of the current discount plus cart-line identities. If nothing has changed, recalculation is skipped — preventing DOM thrashing on high-traffic carts while still responding correctly when duplicate variant lines change independently.
Proportional allocation with rounding reconciliation. Distributing a percentage discount across mixed-price items with naive rounding produces €0.01 discrepancies. A two-pass algorithm allocates proportionally, then reconciles the remainder so line items always sum to the expected subtotal.
Mode-aware handling. Discount sources behave differently, and the system treats them differently rather than forcing everything through one path:
The point is a deliberate split: defer where the platform is authoritative, run custom preview logic where it isn't, and keep the two consistent.
Multi-mode combination handling. When a multiples code (3-for-2, 4-for-3) combines with a percentage discount, the system identifies which items are free versus paid, keeps Shopify's split free line at €0.00, allocates the order-level discount across paid lines only, and presents both discount types clearly.
Key-first line matching. A product or variant ID is not always a unique cart row: the same variant can appear more than once with different properties or selling plans. The renderer therefore matches a cart line by its Shopify cart key first, with a compatibility fallback where needed. That keeps snapshots, DOM updates, and discount allocations attached to the right row.
Bounded resilience, not endless polling. Rebuy and Shopify can expose cart data, discount messages, and Smart Cart DOM at different moments. The coordinator uses short, capped retries, resets them on cart lifecycle events, and rechecks restored or newly visible pages. This protects delayed connections and in-app browsers without changing Shopify's discount calculation.
RABATTCODE ANGEWENDET!, and keeps the
applied tag and amount visible.
The module names below are the actual modules in the codebase.
RebuyEventManager — the event hub. Normalizes rebuy:* events,
holds and refreshes current cart state, and republishes normalized
cart:* and discount:* events that the rest of the system
subscribes to.
RebuyUtils — the shared utility layer. Owns cart reads and Ajax cart
mutations, discount-source resolution (getActiveDiscount() resolves by
precedence: manual Rebuy → checkout-level → automatic Buy-X-Get-Y → none), and the
proportional allocation math. It also provides key-first cart-line identity and detects
Shopify's automatic free lines.
RebuyCartCallbacks — the renderer. Owns price DOM snapshotting,
sale/compare-at rendering, proportional discount display, revert behavior when discount
state changes, subtotal reconciliation, and the bounded recovery path for delayed URL
discount rendering.
FreeGiftHandler — manages code-based free gifts, kept separate from
Rebuy's own gifts by a _free_gift_source line-item marker, and enforces
gift quantity.
MultiplesPromoHandler — manages 3-for-2 / 4-for-3 patterns and their
combination with percentage and fixed discounts, including late-arriving cart UI and
discount messages.
URLDiscountManager — detects cookie-backed URL codes, coordinates their
native Rebuy summary state, preserves the applied tag, and restores normal code entry
when that tag is removed.
Coordination is centralized through RebuyEventManager (event flow) and
RebuyUtils (shared discount/cart utilities), while each handler stays
modular.
Mathematical precision. Proportional allocation across mixed-price items while keeping the subtotal exact — solved with the two-pass reconciliation above. In e-commerce, cent-level accuracy is the foundation of trust, not a nicety.
Cross-source reconciliation. Automatic and URL-driven discounts rely on Shopify cart/checkout state; manual input originates in the Rebuy Smart Cart UI. That gap is exactly where "one price in cart, another at checkout" bugs live. The coordinator detects which source is active and applies the correct strategy per mode.
Debugging at scale. Module-level debug toggles — cart callbacks, free gifts, multiples, URL input, bundle updates, automatic discount handling — make event flow and state transitions traceable in production across 6 storefront configurations, which was essential for diagnosing timing and mode-conflict issues.
Cart-row identity and delayed rendering. The difficult failures were not only mathematical: a Smart Cart redraw can arrive after the cart state, and two visually similar lines can be different Shopify rows. Key-first matching plus capped lifecycle-aware retries keeps each display update attached to the correct row without turning the cart into a polling loop.
Work with platform constraints, not against them. The turning point was recognizing that some discount types are authoritative at checkout level. Rather than forcing everything through custom logic, the system defers where the platform is correct and provides accurate previews only where gaps exist.
Incremental refactoring beats big-bang rewrites. The system evolved through phased, incremental improvements — signature-based change detection, then allocation precision, then mode-aware handling and resilience improvements — deployed continuously across all storefronts without customer-facing disruption. Each phase added one capability and built confidence before the next.
Debug visibility is critical at scale. Module-level toggles saved hours when edge cases surfaced across different storefronts. Being able to trace event flow and state transitions in a live environment was invaluable for diagnosing timing issues, discount-mode conflicts, and late Smart Cart redraws.
Mathematical precision matters in production. Early versions had €0.01 rounding errors when allocating discounts across items. Small as they were, they eroded trust. Two-pass allocation eliminated them.
Client code is private; the technical docs above cover architecture and decisions in full.