Section 06 of 14
The Math
What This Does
This is the heart of the app — the discount calculator. It takes Shopify's discount information, calculates a ratio (like 0.20 for a 20% discount), and applies that ratio to every customs item in ShipStation. Each customs item's declared value is multiplied by (1 - ratio) to get the corrected value.
Why It Matters
If the math is wrong, customs forms will show incorrect values. Too high = customer overpays duties. Too low = could be flagged for under-declaration (a legal issue). The math must handle percentage discounts, fixed-amount discounts, mixed discounts, and rounding to the penny — correctly.
How It Works
- 1.STEP 1: Identify which discounts are order-level. Shopify flags these with allocation_method='across' and target_selection='all'.
- 2.STEP 2: Calculate the discount ratio. For percentage discounts (like '20% off'), the ratio is simply the percentage value / 100 = 0.20. For fixed-amount discounts (like '$15 off'), the ratio is calculated as: discount_amount / (subtotal_after_all_discounts + discount_amount).
- 3.STEP 3: Apply the ratio to every ShipStation customs item. Each item's value is multiplied by (1 - ratio). For 20% off: new_value = old_value × 0.80.
- 4.STEP 4: Handle rounding. Each item is rounded to 2 decimal places. But rounding can cause the total to drift by a few cents. The 'remainder adjustment' distributes this rounding error to the last item so the total matches Shopify's expected total exactly.
- 5.STEP 5: Cross-validate. Compare our corrected total against Shopify's reported discounted total. If they differ by more than $0.02, flag it as a price discrepancy for manual review.
The Code
Key Decisions
- ●We use decimal.js for ALL calculations. JavaScript's native floating point would give us errors like 0.1 + 0.2 = 0.30000000000000004. For money, every cent matters.
- ●For multiple percentage discounts, they're combined multiplicatively: 10% then 20% = 1 - (0.9 × 0.8) = 28% total, not 30%.
- ●The $0.02 tolerance for price discrepancy detection handles normal rounding differences without false positives.
- ●Minimum customs value is $0.01 — customs forms cannot declare a $0.00 value.
- ●The remainder adjustment is a 'largest remainder method' — a standard technique from accounting for distributing rounding errors.
What Could Go Wrong
- ●If we used floating point instead of decimal.js, compound rounding errors on orders with many items could produce significantly wrong totals.
- ●If the ratio formula were wrong for fixed-amount discounts, the correction would be consistently too high or too low.
- ●If we didn't clamp the ratio to [0, 1], a data anomaly could produce negative customs values.