← Dashboard
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. 1.STEP 1: Identify which discounts are order-level. Shopify flags these with allocation_method='across' and target_selection='all'.
  2. 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. 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. 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. 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

What Could Go Wrong