DEV Community

sunny sun
sunny sun

Posted on

Build a Contribution-Margin Check That Doesn't Lie About Refunds or FX

Building e-commerce or financial calculation tools sounds straightforward until you hit the real-world edge cases: blended platform fees, return rate impact, and foreign exchange (FX) settlement slippage. Most generic calculators oversimplify these factors, leading to incorrect profit expectations.

Below is the mathematical logic and a clean JavaScript implementation for a realistic unit-economics margin check.


1. The Real Unit-Economics Formula

To calculate true contribution margin per unit, start with net revenue (excluding sales tax) and subtract all direct variable costs:

$$\text{Net Margin} = \text{Revenue} - \text{COGS} - \text{Platform Fees} - \text{Fulfillment} - \text{Estimated Return Loss} - \text{Ad Spend}$$

Where:

  • Platform Fees = $(\text{Price} \times \text{Fee Rating \%}) + \text{Fixed Per-Order Fee}$
  • Estimated Return Loss = $\text{Return Rate \%} \times (\text{COGS} + \text{Unrecoverable Shipping/Fees})$
  • FX Settlement Impact = $\text{Net Amount} \times (1 - \text{FX Slippage \%})$

2. JavaScript Implementation

Here is a pure, zero-dependency JavaScript function that processes these scenario inputs safely without rounding bugs:


javascript
function calculateTrueMargin(inputs) {
  const {
    sellingPrice,
    cogs,
    shippingCost,
    platformFeePercent,
    fixedFee,
    adSpendPerUnit,
    returnRatePercent,
    fxSlippagePercent = 0.02 // default 2% conversion buffer
  } = inputs;

  // 1. Gross Revenue after FX settlement adjustment
  const netRevenue = sellingPrice * (1 - fxSlippagePercent);

  // 2. Variable fees calculation
  const totalPlatformFee = (sellingPrice * platformFeePercent) + fixedFee;

  // 3. Expected loss per unit due to customer returns
  const unrecoverableReturnLoss = returnRatePercent * (cogs * 0.5 + shippingCost);

  // 4. Final margin calculation
  const totalVariableCost = cogs + shippingCost + totalPlatformFee + adSpendPerUnit + unrecoverableReturnLoss;
  const netProfit = netRevenue - totalVariableCost;
  const marginPercent = (netProfit / netRevenue) * 100;

  return {
    netProfit: Number(netProfit.toFixed(2)),
    marginPercent: Number(marginPercent.toFixed(2)),
    isProfitable: netProfit > 0
  };
}

// Example Scenario Test:
const scenario = calculateTrueMargin({
  sellingPrice: 49.99,
  cogs: 12.50,
  shippingCost: 6.00,
  platformFeePercent: 0.15, // 15% platform fee
  fixedFee: 0.30,
  adSpendPerUnit: 10.00,
  returnRatePercent: 0.05 // 5% return rate
});

console.log(scenario);
// Output: { netProfit: 11.23, marginPercent: 22.92, isProfitable: true }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)