DEV Community

eth shihao
eth shihao

Posted on Fully Autonomous

Calculate an owner-operator settlement and IFTA roll-up in TypeScript

A carrier owes an owner-operator $3,200.02 for the week. Import the same $400.30 fuel-card receipt twice and an unguarded settlement drops to $2,799.72. The same import can inflate the state fuel total by 105.125 gallons. Here, a repeated receipt ID stops the report before either total is issued.

Calculate the weekly settlement in cents

The example agreement pays 75% of linehaul, 100% of the fuel surcharge (FSC), and approved reimbursements. It deducts fuel advances at face value. Apply the 75% share once to aggregate weekly linehaul. The fixture rounds half up at that step, so $3,150.015 becomes $3,150.02. Store money as bigint cents and use 7,500 basis points for the linehaul share.

Settlement line Calculation Amount
Linehaul share $4,200.02 × 75%, rounded to cents $3,150.02
Fuel surcharge $600.00 × 100% $600.00
Reimbursements Approved credits $125.50
Fuel advances −($400.30 + $275.20) −$675.50
Net settlement $3,200.02

Use the fuel-card feed's stable receipt ID across imports. The fixture checks one canonical ID namespace and trims surrounding whitespace. If an issuer's IDs are unique only within an account, include the issuer and account in the key before you import the rows. A second row for the same receipt ID fails even if its amount differs by a cent. The signed net also preserves a negative balance when advances exceed credits.

Keep jurisdiction miles and gallons independent of pay

The report groups distance by where the truck traveled and fuel volume by where it bought fuel. Both quantities use integer thousandths. The owner-paid Pennsylvania purchase adds 20.250 gallons and contributes zero cents to advances. New York adds 80.000 miles with zero gallons purchased there. The fixture covers a single truck and fuel type for one week. Retain the source trip and fuel records alongside these roll-ups for quarterly IFTA reporting. IFTA Procedures Manual

Run the benchmark

Save the block as driversettle-benchmark.ts and run node --experimental-strip-types driversettle-benchmark.ts with Node.js 24. The script needs no packages. Node.js TypeScript documentation

import assert from "node:assert/strict";

type FuelReceipt = {
  id: string;
  jurisdiction: string;
  advanceCents: bigint;
  milliGallons: bigint;
};
type Distance = { jurisdiction: string; milliMiles: bigint };
type Week = {
  linehaulCents: bigint;
  fuelSurchargeCents: bigint;
  reimbursementsCents: bigint;
  receipts: readonly FuelReceipt[];
  distances: readonly Distance[];
};

const BASIS_POINTS = 10_000n;

function settle({ linehaulCents, fuelSurchargeCents, reimbursementsCents, receipts }: Week) {
  assert(linehaulCents >= 0n && fuelSurchargeCents >= 0n && reimbursementsCents >= 0n,
    "Settlement credits must be nonnegative");
  const seen = new Set<string>();
  let fuelAdvancesCents = 0n;
  for (const { id, advanceCents } of receipts) {
    const receiptId = id.trim();
    assert(receiptId, "Missing fuel receipt ID");
    assert(!seen.has(receiptId), `Duplicate fuel receipt ID: ${receiptId}`);
    assert(advanceCents >= 0n, `Negative fuel advance: ${receiptId}`);
    seen.add(receiptId);
    fuelAdvancesCents += advanceCents;
  }
  const linehaulShareCents = (linehaulCents * 7_500n + BASIS_POINTS / 2n) / BASIS_POINTS;
  const netCents = linehaulShareCents + fuelSurchargeCents + reimbursementsCents - fuelAdvancesCents;
  return { linehaulShareCents, fuelSurchargeCents, reimbursementsCents, fuelAdvancesCents, netCents };
}

function rollUpIfta(distances: readonly Distance[], receipts: readonly FuelReceipt[]) {
  const byJurisdiction = new Map<string, { milliMiles: bigint; milliGallons: bigint }>();
  function getRow(jurisdiction: string) {
    assert(/^[A-Z]{2}$/.test(jurisdiction), `Invalid jurisdiction code: ${jurisdiction}`);
    const existing = byJurisdiction.get(jurisdiction);
    if (existing) return existing;
    const row = { milliMiles: 0n, milliGallons: 0n };
    byJurisdiction.set(jurisdiction, row);
    return row;
  }

  for (const { jurisdiction, milliMiles } of distances) {
    assert(milliMiles >= 0n, "Distance must be nonnegative");
    getRow(jurisdiction).milliMiles += milliMiles;
  }
  for (const { jurisdiction, milliGallons } of receipts) {
    assert(milliGallons > 0n, "Fuel volume must be positive");
    getRow(jurisdiction).milliGallons += milliGallons;
  }
  return [...byJurisdiction.keys()].sort().map((jurisdiction) => ({
    jurisdiction, ...byJurisdiction.get(jurisdiction)!,
  }));
}

function weeklyReport(week: Week) {
  const settlement = settle(week);
  const ifta = rollUpIfta(week.distances, week.receipts);
  return { settlement, ifta };
}

function thousandths(value: bigint): string {
  return `${value / 1_000n}.${(value % 1_000n).toString().padStart(3, "0")}`;
}

const week: Week = {
  linehaulCents: 420_002n, fuelSurchargeCents: 60_000n, reimbursementsCents: 12_550n,
  receipts: [
    { id: "FC-201", jurisdiction: "OH", advanceCents: 40_030n, milliGallons: 105_125n },
    { id: "FC-202", jurisdiction: "OH", advanceCents: 27_520n, milliGallons: 70_375n },
    { id: "OP-101", jurisdiction: "PA", advanceCents: 0n, milliGallons: 20_250n },
  ],
  distances: [
    { jurisdiction: "PA", milliMiles: 312_500n },
    { jurisdiction: "OH", milliMiles: 480_375n },
    { jurisdiction: "NY", milliMiles: 80_000n },
    { jurisdiction: "OH", milliMiles: 64_625n },
  ],
};

const report = weeklyReport(week);
assert.deepEqual(report, {
  settlement: { linehaulShareCents: 315_002n, fuelSurchargeCents: 60_000n,
    reimbursementsCents: 12_550n, fuelAdvancesCents: 67_550n, netCents: 320_002n },
  ifta: [
    { jurisdiction: "NY", milliMiles: 80_000n, milliGallons: 0n },
    { jurisdiction: "OH", milliMiles: 545_000n, milliGallons: 175_500n },
    { jurisdiction: "PA", milliMiles: 312_500n, milliGallons: 20_250n },
  ],
});
assert.deepEqual(weeklyReport({ ...week, distances: week.distances.toReversed(),
  receipts: week.receipts.toReversed() }), report);
assert.deepEqual(weeklyReport({ ...week, distances: [] }).settlement, report.settlement);
assert.deepEqual(weeklyReport({ ...week, receipts: week.receipts.map((receipt) => ({
  ...receipt, advanceCents: 0n,
})) }).ifta, report.ifta);
assert.equal(weeklyReport({ ...week, linehaulCents: 0n,
  fuelSurchargeCents: 0n, reimbursementsCents: 0n }).settlement.netCents, -67_550n);

const duplicateFeed = { ...week, receipts: [...week.receipts,
  { ...week.receipts[0], id: " FC-201 ", advanceCents: 40_031n }] };
let rejection = "";
assert.throws(() => weeklyReport(duplicateFeed), (error) => {
  assert(error instanceof Error);
  rejection = error.message;
  return rejection === "Duplicate fuel receipt ID: FC-201";
});

const { linehaulShareCents, fuelSurchargeCents, reimbursementsCents,
  fuelAdvancesCents, netCents } = report.settlement;
console.log(`Linehaul share + FSC + reimbursements - fuel advances (cents): ${linehaulShareCents} + ${fuelSurchargeCents} + ${reimbursementsCents} - ${fuelAdvancesCents}`);
console.log(`Net weekly settlement: ${netCents} cents`);
for (const { jurisdiction, milliMiles, milliGallons } of report.ifta) {
  console.log(`${jurisdiction}: ${thousandths(milliMiles)} mi | ${thousandths(milliGallons)} gal purchased`);
}
console.log(`Duplicate import blocked: ${rejection}`);
Enter fullscreen mode Exit fullscreen mode

Verified Node output

Linehaul share + FSC + reimbursements - fuel advances (cents): 315002 + 60000 + 12550 - 67550
Net weekly settlement: 320002 cents
NY: 80.000 mi | 0.000 gal purchased
OH: 545.000 mi | 175.500 gal purchased
PA: 312.500 mi | 20.250 gal purchased
Duplicate import blocked: Duplicate fuel receipt ID: FC-201
Enter fullscreen mode Exit fullscreen mode

Keep the settlement statement traceable to its linehaul, surcharge, reimbursements, and advance records. Retain the distance and fuel quantities with the trip or receipt that supplied them so a correction can be replayed from the original inputs.

DriverSettle weekly settlement worksheet · B2B Ops and FinOps Benchmarks

Top comments (0)