Skip to content

Conversation

@devin-ai-integration
Copy link

@devin-ai-integration devin-ai-integration bot commented Nov 13, 2025

Correct Linehaul Rate Calculation Order

Summary

This PR fixes the calculation order in the freight rate calculator to match the correct business logic:

Correct Order (implemented):

  1. Apply profit margin to carrier rate → ALL-IN RATE
  2. Subtract fuel surcharge from all-in rate → LINEHAUL RATE

Key Formula: ALL-IN RATE = CARRIER RATE + GROSS PROFIT %

Example: $1,000 carrier flat + 10% profit = $1,100 all-in total ✓

Changes Made:

  • Calculate allInTotal directly from carrierFlatRate × (1 + profit%) to avoid rounding drift
  • Calculate allInRate by dividing allInTotal by miles
  • Subtract fuel rate from all-in rate to get linehaul rate: linehaulRate = allInRate - fuelRate
  • Fixed invoice total to use allInTotal (includes profit) instead of avgTripTotal (excludes profit)
  • Removed unnecessary fuelSurchargePerMile variable (just use fuelRate directly)

Review & Testing Checklist for Human

  • CRITICAL: Verify math with user's example (1000 miles, $1000 carrier, 10% profit → should show $1100 all-in total, $1.10/mile all-in rate)
  • Test with multiple real-world scenarios and compare against expected pricing
  • Test edge cases: zero miles, zero profit, very high fuel rates, negative scenarios
  • Load extension in Chrome (not just sidepanel.html) and verify full workflow works
  • Compare a few quotes from before/after this change to understand pricing impact on business

Recommended Test Plan

  1. Load extension via chrome://extensions → Developer Mode → Load unpacked
  2. Test with known good values:
    • Simple: 1000 miles, $1000 carrier, 10% profit, $0.26 fuel
    • Expected: All-in total = $1100, Linehaul rate = $0.84/mile
  3. Test with default values (1786 miles, $2679 carrier, 13.5% profit)
  4. Test edge cases (0 miles, 0 profit, high fuel rates)

Notes

Testing Done:

  • Verified calculations by opening sidepanel.html directly in browser
  • Tested with user's example: 1000 miles, $1000 carrier, 10% profit → correctly shows $1100 all-in total ✓
  • Tested with default values: 1786 miles, $2679 carrier, 13.5% profit → all calculations verified ✓
  • Screenshot: Calculator Test

Important: This changes the pricing calculation significantly. The linehaul rate is now calculated AFTER profit is applied (not before), which means profit is applied to the full carrier cost before fuel is separated out.

Session Info:

…ing profit margin

- Move fuel surcharge calculation before linehaul rate calculation
- Calculate linehaul rate by subtracting fuel from carrier rate first
- Apply profit margin to linehaul rate instead of carrier rate
- Update profit total calculation to be based on linehaul total
- Maintain Math.max(0, ...) logic to prevent negative values

Co-Authored-By: Anthony Fecarotta <anthony@linehaul.ai>
@devin-ai-integration
Copy link
Author

Original prompt from Anthony
# Refactor Linehaul Rate Calculation to Subtract Fuel Surcharge Before Applying Profit Margin

## Background
@
Currently in the `freightCognition/openQuote` repository, the `calculator.js` file calculates the LINEHAUL RATE using the following logic:

1. First, the profit margin is applied to the carrier rate to get the `allInRate`:
   - `allInRate = carrierRate * (1 + profitPercentage / 100)` (around line 51-54)

2. Then, the fuel surcharge per mile is calculated:
   - `fuelSurchargePerMile = fuelTotal / miles` (around line 69)

3. Finally, the linehaul rate is calculated by subtracting fuel surcharge from the all-in rate:
   - `linehaulRate = Math.max(0, allInRate - fuelSurchargePerMile)` (around line 70-71)

4. The linehaul total is then:
   - `linehaulTotal = miles × linehaulRate` (around line 74)

## Task

Refactor the calculation logic in `calculator.js` (in the `freightCognition/openQuote` repository) so that the fuel surcharge is subtracted from the carrier rate BEFORE the profit margin is applied, rather than after.

### Required Changes

The new calculation order should be:

1. Calculate fuel surcharge per mile (same as before):
   - `fuelSurchargePerMile = fuelTotal / miles`

2. Subtract fuel surcharge from carrier rate FIRST:
   - `linehaulRate = Math.max(0, carrierRate - fuelSurchargePerMile)`

3. THEN apply profit margin to the linehaul rate:
   - `allInRate = linehaulRate * (1 + profitPercentage / 100)`

4. Calculate linehaul total:
   - `linehaulTotal = miles × linehaulRate`

### Files to Modify

- **Repository**: `freightCognition/openQuote`
- **File**: `calculator.js`
- **Lines to modify**: Approximately lines 51-54 (allInRate calculation), line 69 (fuelSurchargePerMile), lines 70-71 (linehaulRate calculation), and line 74 (linehaulTotal calculation)

### Important Notes

- Make sure to update all dependent calculations that rely on `allInRate`, `linehaulRate`, or `linehaulTotal`
- Ensure the `Math.max(0, ...)` logic is still applied appropriately t... (196 chars truncated...)

@devin-ai-integration
Copy link
Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@coderabbitai
Copy link

coderabbitai bot commented Nov 13, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Comment @coderabbitai help to get the list of available commands and usage tips.

- Change invoiceTotal calculation from avgTripTotal to allInTotal
- This ensures profit margin is included in the final invoice total
- Per-mile total now correctly includes profit in the calculation

Co-Authored-By: Anthony Fecarotta <anthony@linehaul.ai>
Copy link

@llamapreview llamapreview bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Code Review by LlamaPReview

🎯 TL;DR & Recommendation

Recommendation: Request Changes

This PR refactors the freight rate calculation to apply profit margin after subtracting fuel surcharge, which reduces absolute profit dollars and changes core business logic. Manual testing is critical to verify the new calculations match business requirements.

📄 Documentation Diagram

This diagram documents the refactored freight rate calculation workflow with fuel surcharge subtracted before profit margin.

sequenceDiagram
    participant U as User
    participant C as Calculator
    U->>C: Input: miles, carrierFlatRate, profitPercentage, fuelRate
    C->>C: carrierRate = carrierFlatRate / miles
    note over C: PR #35;2: Fuel calculation moved before profit application
    C->>C: fuelTotal = miles * fuelRate
    C->>C: fuelSurchargePerMile = fuelTotal / miles
    C->>C: linehaulRate = max(0, carrierRate - fuelSurchargePerMile)
    C->>C: linehaulTotal = miles * linehaulRate
    C->>C: allInRate = linehaulRate * (1 + profitPercentage/100)
    C->>C: profitTotal = linehaulTotal * profitPercentage/100
    C->>C: allInTotal = miles * allInRate
    C->>C: avgTripTotal = linehaulTotal + fuelTotal
    C->>U: Output: various rates and totals
Loading

🌟 Strengths

  • Preserved calculation dependency graph ensuring downstream functionality
  • Maintained Math.max logic to prevent negative linehaul rates
Priority File Category Impact Summary Anchors
P1 calculator.js Architecture Changes profit calculation base, reducing absolute profit dollars
P1 calculator.js Architecture Profit now based on linehaul, not carrier rate
P2 calculator.js Correctness and Business Logic All-in rate definition changed, potential confusion
P2 calculator.js Correctness and Business Logic Avg trip total may undercharge customers
P2 calculator.js Maintainability Redundant fuel surcharge per mile calculation

🔍 Notable Themes

  • Business Logic Shift: The profit margin application has moved from gross carrier rate to net linehaul revenue, fundamentally altering financial outcomes.
  • Calculation Semantics: Several output fields now have different meanings, which could lead to user confusion or incorrect billing if not addressed.

📈 Risk Diagram

This diagram illustrates the risk of reduced profit margins and potential billing inconsistencies due to the new calculation order.

sequenceDiagram
    participant B as Broker
    participant C as Calculator
    B->>C: Input: carrierFlatRate, miles, fuelRate, profitPercentage
    C->>C: carrierRate = carrierFlatRate / miles
    C->>C: fuelTotal = miles * fuelRate
    C->>C: linehaulRate = max(0, carrierRate - fuelSurchargePerMile)
    note over C: R1(P1): Profit margin now on smaller base (linehaul vs carrier)
    C->>C: profitTotal = linehaulTotal * profitPercentage / 100
    note over C: R2(P1): Profit amount reduced for same percentage
    C->>B: Output: allInTotal, profitTotal, avgTripTotal
    note over B: Risk: Financial outcomes changed, potential underbilling
Loading

💡 Have feedback? We'd love to hear it in our GitHub Discussions.
✨ This review was generated by LlamaPReview Advanced, which is free for all open-source projects. Learn more.

calculator.js Outdated
Comment on lines 55 to 64
// Calculate Linehaul Rate (Carrier Rate - Fuel Surcharge per mile)
const linehaulRate = Math.max(0, carrierRate - fuelSurchargePerMile);
linehaulRateInput.value = linehaulRate.toFixed(2);

// Calculate Linehaul Total (miles * linehaul rate)
const linehaulTotal = miles * linehaulRate;
linehaulTotalInput.value = linehaulTotal.toFixed(2);

// Calculate All-In Rate (linehaul rate * gross profit percentage)
const grossProfitMultiplier = 1 + (profitPercentage / 100);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 | Confidence: High

The calculation order change fundamentally alters the business logic by applying profit margin to linehaul revenue only (after fuel costs) rather than total carrier revenue. This creates a direct financial impact: profit margins now apply to a smaller base amount, reducing absolute profit dollars for the same percentage margin. The change is architecturally significant as it redefines core financial calculations used throughout the freight quoting system. The Math.max(0, ...) protection prevents negative linehaul rates but may mask business logic errors where fuel costs exceed carrier rates.

calculator.js Outdated
Comment on lines 68 to 70
// Calculate Gross Profit Total (linehaul total * profit percentage / 100)
const profitTotal = linehaulTotal * (profitPercentage / 100);
profitTotalInput.value = profitTotal.toFixed(2);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 | Confidence: High

The profit calculation now uses linehaulTotal instead of carrierFlatRate, creating a direct financial impact where profit amounts will be lower for the same percentage margin. This changes the fundamental profit model from markup on total carrier cost to markup on net linehaul revenue. The related_context shows this profitTotal feeds into downstream calculations including invoice totals and per-mile rates, creating a ripple effect throughout the financial reporting.

const linehaulTotal = miles * linehaulRate;
linehaulTotalInput.value = linehaulTotal.toFixed(2);

// Calculate average trip total (linehaul total + fuel total)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 | Confidence: High

The avgTripTotal calculation now sums linehaulTotal (which excludes profit) with fuelTotal, whereas previously it summed linehaulTotal (which included profit) with fuelTotal. This creates an inconsistency where avgTripTotal no longer represents the total customer charge but rather the carrier cost plus fuel. The related_context shows this value feeds into invoiceTotal, potentially undercharging customers if this represents the final invoice amount.

Suggested change
// Calculate average trip total (linehaul total + fuel total)
// Calculate average trip total (linehaul total + fuel total + profit)
const avgTripTotal = linehaulTotal + fuelTotal + profitTotal;
if (!allInTotalInput) {
avgTripTotalInput.value = avgTripTotal.toFixed(2);
}

calculator.js Outdated
Comment on lines 48 to 52
// Calculate Fuel Surcharge total (miles * fuel rate)
const fuelTotal = miles * fuelRate;
fuelTotalInput.value = fuelTotal.toFixed(2);

// Calculate All-In Rate (carrier rate * gross profit percentage)
// Calculate Fuel Surcharge per mile
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 | Confidence: High

The fuel surcharge calculation now occurs earlier in the flow, improving logical sequencing. However, fuelSurchargePerMile is calculated by dividing fuelTotal by miles, which simplifies to fuelRate. This creates redundant calculations that could be simplified for better maintainability and performance.

Suggested change
// Calculate Fuel Surcharge total (miles * fuel rate)
const fuelTotal = miles * fuelRate;
fuelTotalInput.value = fuelTotal.toFixed(2);
// Calculate All-In Rate (carrier rate * gross profit percentage)
// Calculate Fuel Surcharge per mile
// Calculate Fuel Surcharge total (miles * fuel rate)
const fuelTotal = miles * fuelRate;
fuelTotalInput.value = fuelTotal.toFixed(2);
// Fuel Surcharge per mile equals fuelRate
const fuelSurchargePerMile = fuelRate;

calculator.js Outdated
Comment on lines 72 to 78
// Calculate All-In Total (miles * all-in rate)
const allInTotal = miles * allInRate;
if (allInTotalInput) {
allInTotalInput.value = allInTotal.toFixed(2);
} else {
avgTripTotalInput.value = allInTotal.toFixed(2);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 | Confidence: Medium

The allInTotal calculation remains unchanged but now uses a different allInRate definition. This creates potential confusion as the same field name represents different underlying calculations. The related_context shows this value is used in conditional UI logic (allInTotalInput vs avgTripTotalInput), suggesting this field serves multiple purposes. The calculation dependency chain is preserved, but the semantic meaning of "all-in" has shifted from carrier-rate-plus-profit to linehaul-plus-profit.

@fakebizprez fakebizprez linked an issue Nov 13, 2025 that may be closed by this pull request
@fakebizprez fakebizprez added the enhancement New feature or request label Nov 13, 2025
…ubtract fuel

BREAKING CHANGE: Reverses previous refactor to match correct business logic

The correct calculation order is:
1. Apply profit margin to carrier rate to get ALL-IN RATE
   - ALL-IN TOTAL = CARRIER FLAT × (1 + profit%)
   - ALL-IN RATE = ALL-IN TOTAL ÷ miles
2. Subtract fuel surcharge from all-in rate to get LINEHAUL RATE
   - LINEHAUL RATE = ALL-IN RATE - FUEL RATE
   - LINEHAUL TOTAL = LINEHAUL RATE × miles

This ensures:
- ALL-IN RATE = CARRIER RATE + GROSS PROFIT % (as specified)
- Profit is applied to carrier cost BEFORE fuel separation
- LINEHAUL RATE is calculated AFTER profit is applied (not inflated)

Example verification (1000 miles, $1000 carrier, 10% profit):
- Carrier Rate: $1.00/mile
- Profit: $100 (10% of $1000)
- All-In Total: $1100 ✓
- All-In Rate: $1.10/mile ✓
- Fuel: $0.26/mile
- Linehaul Rate: $0.84/mile ($1.10 - $0.26) ✓

Co-Authored-By: Anthony Fecarotta <anthony@linehaul.ai>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Revise Formula

2 participants