Audit freight invoices against the rate card.
Done by an agent. Checked twice.
Every freight invoice cleared or disputed for an exact amount, with the wrong part of each bill named.
Real files in
- accessorial_fees.csv
The agreed fees for four extra services. 5 lines, 202 bytes. - freight_invoices.csv
39 freight invoices from three carriers for six weeks of shipments, 16 with a problem planted in them. 40 lines, 3 KB. - rate_card.csv
The agreed rate card: price per kg, minimum charge and fuel percent for each carrier and zone. 12 lines, 485 bytes. - shipments.csv
The shipper's own record of 36 shipments: carrier, zones, weight and the extra services asked for. 37 lines, 2 KB.
Sample data written by Atris. Not a real company.
Three steps
- 1.Work out what each shipment should cost
- 2.Judge each invoice
- 3.Write the audit and the dispute list
Claude Sonnet 5.5, 52 seconds. No web. It never saw the check.
Checked twice
- Passed: 39 of 39 invoices appear once in audit.csv
- Passed: 39 of 39 statuses equal the status recomputed from the rate card
- Passed: 39 of 39 rows carry the invoice total as billed, the recomputed expected total and the variance between them
- Passed: 12 of 12 wrongly billed invoices name the exact parts of the bill that are off
- Passed: 14 of 14 disputed invoices are listed in dispute.md with the right amount
- Passed: dispute.md states the amount to dispute for 3 of 3 carriers and the total, 1,967.48
- Passed: 237 of 237 numbers in the reasons and on the invoice lines of dispute.md are that invoice's own shipment number and its billed, expected or gap figures
- Passed: 22 of 22 counts and totals on the other lines of dispute.md equal the numbers recomputed from the invoices
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 6 ways on purpose. The check caught 6.
## Dispute by carrier - Copperline Freight: 4 invoice(s), 284.60 - Fenwater Logistics: 5 invoice(s), 1431.17 - Ridgeback Haulage: 5 invoice(s), 251.71 **Total to dispute: 1967.48** (14 invoices) ## Disputed invoices ### Copperline Freight - FI-8116 (overbilled): 36.76. Billed 323.53 vs expected 286.77: linehaul billed 283.80 vs expected 251.55; fuel billed 39.73 vs expected 35.22. - FI-8122 (overbilled): 64.24. Billed 682.84 vs expected 618.60: linehaul billed 546.35 vs expected 490.00; fuel billed 76.49 vs expected 68.60; billed weight 1115 kg vs shipment record 1000 kg. - FI-8131 (overbilled): 1.20. Billed 183.65 vs expected 182.45: fuel billed 21.15 vs expected 19.95.
How this was run
An AI agent on Claude Sonnet 5.5 was given a folder with the files below and a three-step flow, and nothing else. It had no web access and never saw the check. The check was written before the run and made stricter after it. It works the answer out again from the input files. Then Claude Opus 5.5 reviewed the result against the inputs. The input files are sample data written by Atris, with the problems a real week has planted in them.
Run 1 of 1 on 1 December 2026. The agent took 52 seconds.
What the second review verified
- Recomputed all 39 invoices from the inputs. Every status, expected_total, billed_total, variance and parts_off in audit.csv matches mine. Example: FI-8105 linehaul 1777 kg × 0.34 = 604.18, fuel 11% = 66.46, accessorials liftgate+residential = 73.00, expected 743.64, variance 22.64, parts linehaul;fuel
- Special statuses are right: FI-8137 is a duplicate of SH-24024 (already billed on FI-8108 on 2026-10-17), FI-8135 is no_rate (Fenwater has no A to D rate), FI-8138 is no_shipment (SH-29911 is not on record), FI-8139 is no_shipment (blank shipment_id)
- Dispute totals by our shipment carrier check out: Copperline 4 / 284.60, Fenwater 5 / 1431.17, Ridgeback 5 / 251.71. These add up to the 1967.48 total, and all 14 disputed invoices are listed with their amounts
- Underbilled invoices are listed separately and not netted: FI-8120 -45.00 (accessorials) and FI-8127 -38.02 (linehaul;fuel, 68.00 minimum charge). Quoted invoice figures match the input, e.g. FI-8118 charges add to 1064.58 against a 1094.58 total
What this run does not show
- Amounts on an invoice line are compared with that invoice's own figures, so one true figure swapped for another would pass.
- The sample rate card has one rate for each carrier and zone pair, with no date ranges or weight breaks.
- The worker and the check follow the same rules from the flow, so a wrong rule in the flow would pass both.
Would the check catch a wrong answer?
A check that cannot fail proves nothing. After the run we took a copy of the output, broke it one small way at a time and ran the check again. It caught 6 of 6. The check was made stricter after the first try at this, and the same untouched output was graded again.
Open every file
flow.md · the three steps the agent followed
# Audit freight invoices against the rate card function: operations for: the person who approves freight bills goal: Every freight invoice is cleared or disputed for an exact amount, with the part of the bill that is wrong named. ## 1. Work out what each shipment should cost Read input/shipments.csv, input/rate_card.csv, input/accessorial_fees.csv and input/freight_invoices.csv. Our shipment record is the truth for carrier, zones, weight and accessorials. The invoice is the claim. For each shipment find the rate card row with the same carrier, origin_zone and dest_zone, then: - expected linehaul is weight_kg times rate_per_kg to two decimals. It is never below min_charge. - expected fuel is expected linehaul times fuel_pct divided by 100, two decimals. - expected accessorials is the sum of the fees for the codes listed on the shipment record. - expected_total is the sum of the three. ## 2. Judge each invoice Give every invoice one status. Check in this order and use the first that applies: - `no_shipment` when shipment_id is blank or not in shipments.csv. - `duplicate` when an earlier invoice (by invoice_date, then invoice_id) already billed the same shipment_id. The earlier one is judged on its own. - `no_rate` when the rate card has no row for the shipment's carrier and zones. - `overbilled` when the invoice total is more than 1.00 above expected_total. - `underbilled` when the invoice total is more than 1.00 below expected_total. - `ok` in every other case. variance is the invoice total minus expected_total. For `no_shipment`, `duplicate` and `no_rate` invoices expected_total is 0.00, so the variance is the whole invoice total. For `overbilled` and `underbilled` invoices fill parts_off with every part that is wrong, joined by a semicolon. Use `linehaul`, `fuel` or `accessorials` when that charge on the invoice differs from the expected one by more than 0.01. Use `total` when the invoice total is not the sum of its own three charges. Leave parts_off blank for every other status. ## 3. Write the audit and the dispute list Write output/audit.csv with columns invoice_id,status,expected_total,billed_total,variance,parts_off,reason. One row per invoice. Money has two decimals. reason is one plain sentence with the numbers that differ. Write output/dispute.md for the approver. The amount to dispute is the variance of every `overbilled`, `duplicate`, `no_shipment` and `no_rate` invoice. Group by the carrier on our shipment record. When there is no shipment record use the carrier as written on the invoice. Give one line per carrier with the number of invoices and the amount to dispute, then the total to dispute across all carriers, then one line per disputed invoice with its id, amount and reason. List `underbilled` invoices in their own section with the amount the carrier left off. Do not net them against the dispute total. ## Done looks like - Every invoice appears once in audit.csv with one status. - Every disputed invoice is named in dispute.md with its amount. - The carrier amounts in dispute.md add up to the total to dispute.
input/accessorial_fees.csv · 5 lines, 202 bytes
code,description,fee liftgate,Truck with a liftgate,45.00 residential,Delivery to a home address,28.00 appointment,Delivery at a booked time,20.00 inside_delivery,Carried inside the building,60.00
input/freight_invoices.csv · 40 lines, 3 KB
invoice_id,invoice_date,carrier,shipment_id,billed_weight_kg,linehaul,fuel,accessorial_charges,total FI-8101,2026-10-10,Copperline Freight,SH-24003,1530,596.70,83.54,0.00,680.24 FI-8103,2026-10-12,Ridgeback Haulage,SH-24009,940,488.80,61.10,60.00,609.90 FI-8102,2026-10-16,Fenwater Logistics,SH-24006,740,251.60,27.68,0.00,279.28 FI-8104,2026-10-17,Copperline Freight,SH-24012,1080,421.20,58.97,60.00,540.17 FI-8106,2026-10-17,Ridgeback Haulage,SH-24018,797,151.43,18.93,0.00,170.36 FI-8107,2026-10-18,COPPERLINE FREIGHT LTD,SH-24021,1070,224.70,31.46,0.00,256.16 FI-8105,2026-10-19,Fenwater Logistics,SH-24015,1837,624.58,68.70,73.00,766.28 FI-8109,2026-10-19,Ridgeback Haulage,SH-24027,1892,359.48,57.52,73.00,490.00 FI-8110,2026-10-20,Copperline Freight,SH-24030,187,88.00,12.32,0.00,100.32 FI-8108,2026-10-21,Fenwater Logistics,SH-24024,1055,358.70,39.46,73.00,471.16 FI-8112,2026-10-21,Ridgeback Haulage,SH-24036,1027,369.72,46.22,105.00,520.94 FI-8111,2026-10-22,Fenwater Logistics,SH-24033,500,145.00,15.95,0.00,160.95 FI-8114,2026-10-25,Fenwater Logistics,SH-24042,150,76.00,8.36,0.00,84.36 FI-8115,2026-10-25,Ridgeback Haulage,SH-24045,1267,342.09,42.76,0.00,384.85 FI-8113,2026-10-26,Copperline Freight,SH-24039,1040,218.40,30.58,0.00,248.98 FI-8116,2026-10-26,Copperline Freight,SH-24048,645,283.80,39.73,0.00,323.53 FI-8119,2026-10-28,COPPERLINE FREIGHT LTD,SH-24057,630,132.30,18.52,0.00,150.82 FI-8117,2026-10-29,Fenwater Logistics,SH-24051,770,138.60,15.25,0.00,153.85 FI-8118,2026-10-31,Ridgeback Haulage,SH-24054,1695,881.40,110.18,73.00,1094.58 FI-8120,2026-10-31,Fenwater Logistics,SH-24060,1540,277.20,30.49,0.00,307.69 FI-8123,2026-11-01,Fenwater Logistics,SH-24069,747,216.63,23.83,73.00,313.46 FI-8121,2026-11-04,Ridgeback Haulage,SH-24063,602,162.54,20.32,60.00,242.86 FI-8122,2026-11-05,Copperline Freight,SH-24066,1115,546.35,76.49,60.00,682.84 FI-8125,2026-11-06,Copperline Freight,SH-24075,665,259.35,36.31,73.00,368.66 FI-8124,2026-11-07,Ridgeback Haulage,SH-24072,827,223.29,28.76,20.00,272.05 FI-8127,2026-11-07,Ridgeback Haulage,SH-24081,180,34.20,4.28,0.00,38.48 FI-8129,2026-11-07,Fenwater Logistics,SH-24087,740,214.60,27.90,0.00,242.50 FI-8126,2026-11-09,Fenwater Logistics,SH-24078,387,131.58,14.47,55.00,201.05 FI-8131,2026-11-09,Copperline Freight,SH-24093,570,142.50,21.15,20.00,183.65 FI-8128,2026-11-10,Copperline Freight,SH-24084,447,219.03,30.66,0.00,249.69 FI-8132,2026-11-11,Fenwater Logistics,SH-24096,1200,216.00,23.76,0.00,239.76 FI-8133,2026-11-12,Ridgeback Haulage,SH-24099,525,141.75,17.72,28.00,187.47 FI-8138,2026-11-12,Copperline Freight,SH-29911,640,160.00,22.40,0.00,182.40 FI-8130,2026-11-13,Ridgeback Haulage,SH-24090,1635,850.20,106.28,60.00,1016.48 FI-8139,2026-11-14,Ridgeback Haulage,,300,81.00,10.13,45.00,136.13 FI-8134,2026-11-17,Copperline Freight,SH-24102,210,88.00,12.32,0.00,100.32 FI-8135,2026-11-17,Fenwater Logistics,SH-24105,1512,831.60,91.48,0.00,923.08 FI-8137,2026-11-17,Fenwater Logistics,SH-24024,1055,358.70,39.46,73.00,471.16 FI-8136,2026-11-19,Ridgeback Haulage,SH-24108,522,140.94,17.62,60.00,218.56
input/rate_card.csv · 12 lines, 485 bytes
carrier,origin_zone,dest_zone,rate_per_kg,min_charge,fuel_pct Ridgeback Haulage,A,A,0.19,68.00,12.5 Ridgeback Haulage,A,B,0.27,74.00,12.5 Ridgeback Haulage,A,C,0.36,85.00,12.5 Ridgeback Haulage,A,D,0.52,95.00,12.5 Copperline Freight,A,A,0.21,65.00,14 Copperline Freight,A,B,0.25,72.00,14 Copperline Freight,A,C,0.39,88.00,14 Copperline Freight,A,D,0.49,98.00,14 Fenwater Logistics,A,A,0.18,70.00,11 Fenwater Logistics,A,B,0.29,76.00,11 Fenwater Logistics,A,C,0.34,82.00,11
input/shipments.csv · 37 lines, 2 KB
shipment_id,ship_date,carrier,origin_zone,dest_zone,weight_kg,accessorials SH-24003,2026-10-06,Copperline Freight,A,C,1530, SH-24006,2026-10-07,Fenwater Logistics,A,C,740, SH-24009,2026-10-08,Ridgeback Haulage,A,D,940,inside_delivery SH-24012,2026-10-09,Copperline Freight,A,C,1080,inside_delivery SH-24015,2026-10-10,Fenwater Logistics,A,C,1777,liftgate;residential SH-24018,2026-10-11,Ridgeback Haulage,A,A,797, SH-24021,2026-10-12,Copperline Freight,A,A,1070, SH-24024,2026-10-13,Fenwater Logistics,A,C,1055,liftgate;residential SH-24027,2026-10-14,Ridgeback Haulage,A,A,1892,liftgate;residential SH-24030,2026-10-15,Copperline Freight,A,C,187, SH-24033,2026-10-16,Fenwater Logistics,A,B,500, SH-24036,2026-10-17,Ridgeback Haulage,A,C,1027,inside_delivery SH-24039,2026-10-18,Copperline Freight,A,A,1040, SH-24042,2026-10-19,Fenwater Logistics,A,B,150, SH-24045,2026-10-20,Ridgeback Haulage,A,B,1267, SH-24048,2026-10-21,Copperline Freight,A,C,645, SH-24051,2026-10-22,Fenwater Logistics,A,A,770, SH-24054,2026-10-23,Ridgeback Haulage,A,D,1695,liftgate;residential SH-24057,2026-10-24,Copperline Freight,A,A,630, SH-24060,2026-10-25,Fenwater Logistics,A,A,1540,liftgate SH-24063,2026-10-26,Ridgeback Haulage,A,B,602,inside_delivery SH-24066,2026-10-27,Copperline Freight,A,D,1000,inside_delivery SH-24069,2026-10-28,Fenwater Logistics,A,B,747,liftgate;residential SH-24072,2026-10-29,Ridgeback Haulage,A,B,827,appointment SH-24075,2026-10-30,Copperline Freight,A,C,665,liftgate;residential SH-24078,2026-10-31,Fenwater Logistics,A,C,387,liftgate SH-24081,2026-11-01,Ridgeback Haulage,A,A,180, SH-24084,2026-11-02,Copperline Freight,A,D,447, SH-24087,2026-11-03,Fenwater Logistics,A,B,740, SH-24090,2026-11-04,Ridgeback Haulage,A,D,1635,inside_delivery SH-24093,2026-11-05,Copperline Freight,A,B,570,appointment SH-24096,2026-11-06,Fenwater Logistics,A,A,1200, SH-24099,2026-11-07,Ridgeback Haulage,A,B,525, SH-24102,2026-11-08,Copperline Freight,A,C,210, SH-24105,2026-11-09,Fenwater Logistics,A,D,1512, SH-24108,2026-11-10,Ridgeback Haulage,A,B,522,inside_delivery
output/audit.csv · written by the agent, 40 lines
invoice_id,status,expected_total,billed_total,variance,parts_off,reason FI-8101,ok,680.24,680.24,0.00,,Billed 680.24 is within 1.00 of expected 680.24. FI-8102,ok,279.28,279.28,0.00,,Billed 279.28 is within 1.00 of expected 279.28. FI-8103,ok,609.90,609.90,0.00,,Billed 609.90 is within 1.00 of expected 609.90. FI-8104,ok,540.17,540.17,0.00,,Billed 540.17 is within 1.00 of expected 540.17. FI-8105,overbilled,743.64,766.28,22.64,linehaul;fuel,Billed 766.28 vs expected 743.64: linehaul billed 624.58 vs expected 604.18; fuel billed 68.70 vs expected 66.46; billed weight 1837 kg vs shipment record 1777 kg. FI-8106,ok,170.36,170.36,0.00,,Billed 170.36 is within 1.00 of expected 170.36. FI-8107,ok,256.16,256.16,0.00,,Billed 256.16 is within 1.00 of expected 256.16. FI-8108,ok,471.16,471.16,0.00,,Billed 471.16 is within 1.00 of expected 471.16. FI-8109,overbilled,477.42,490.00,12.58,fuel,Billed 490.00 vs expected 477.42: fuel billed 57.52 vs expected 44.94. FI-8110,ok,100.32,100.32,0.00,,Billed 100.32 is within 1.00 of expected 100.32. FI-8111,ok,160.95,160.95,0.00,,Billed 160.95 is within 1.00 of expected 160.95. FI-8112,overbilled,475.94,520.94,45.00,accessorials,Billed 520.94 vs expected 475.94: accessorials billed 105.00 vs expected 60.00. FI-8113,ok,248.98,248.98,0.00,,Billed 248.98 is within 1.00 of expected 248.98. FI-8114,ok,84.36,84.36,0.00,,Billed 84.36 is within 1.00 of expected 84.36. FI-8115,ok,384.85,384.85,0.00,,Billed 384.85 is within 1.00 of expected 384.85. FI-8116,overbilled,286.77,323.53,36.76,linehaul;fuel,Billed 323.53 vs expected 286.77: linehaul billed 283.80 vs expected 251.55; fuel billed 39.73 vs expected 35.22. FI-8117,ok,153.85,153.85,0.00,,Billed 153.85 is within 1.00 of expected 153.85. FI-8118,overbilled,1064.58,1094.58,30.00,total,Billed 1094.58 vs expected 1064.58: total 1094.58 is not the sum of its charges (1064.58). FI-8119,ok,150.82,150.82,0.00,,Billed 150.82 is within 1.00 of expected 150.82. FI-8120,underbilled,352.69,307.69,-45.00,accessorials,Billed 307.69 vs expected 352.69: accessorials billed 0.00 vs expected 45.00. FI-8121,ok,242.86,242.86,0.00,,Billed 242.86 is within 1.00 of expected 242.86. FI-8122,overbilled,618.60,682.84,64.24,linehaul;fuel,Billed 682.84 vs expected 618.60: linehaul billed 546.35 vs expected 490.00; fuel billed 76.49 vs expected 68.60; billed weight 1115 kg vs shipment record 1000 kg. FI-8123,ok,313.46,313.46,0.00,,Billed 313.46 is within 1.00 of expected 313.46. FI-8124,ok,271.20,272.05,0.85,,Billed 272.05 is within 1.00 of expected 271.20. FI-8125,ok,368.66,368.66,0.00,,Billed 368.66 is within 1.00 of expected 368.66. FI-8126,overbilled,191.05,201.05,10.00,accessorials,Billed 201.05 vs expected 191.05: accessorials billed 55.00 vs expected 45.00. FI-8127,underbilled,76.50,38.48,-38.02,linehaul;fuel,Billed 38.48 vs expected 76.50: linehaul billed 34.20 vs expected 68.00; fuel billed 4.28 vs expected 8.50. FI-8128,ok,249.69,249.69,0.00,,Billed 249.69 is within 1.00 of expected 249.69. FI-8129,overbilled,238.21,242.50,4.29,fuel,Billed 242.50 vs expected 238.21: fuel billed 27.90 vs expected 23.61. FI-8130,ok,1016.48,1016.48,0.00,,Billed 1016.48 is within 1.00 of expected 1016.48. FI-8131,overbilled,182.45,183.65,1.20,fuel,Billed 183.65 vs expected 182.45: fuel billed 21.15 vs expected 19.95. FI-8132,ok,239.76,239.76,0.00,,Billed 239.76 is within 1.00 of expected 239.76. FI-8133,overbilled,159.47,187.47,28.00,accessorials,Billed 187.47 vs expected 159.47: accessorials billed 28.00 vs expected 0.00. FI-8134,ok,100.32,100.32,0.00,,Billed 100.32 is within 1.00 of expected 100.32. FI-8135,no_rate,0.00,923.08,923.08,,Rate card has no row for Fenwater Logistics zone A to D; invoice total 923.08 cannot be priced. FI-8136,ok,218.56,218.56,0.00,,Billed 218.56 is within 1.00 of expected 218.56. FI-8137,duplicate,0.00,471.16,471.16,,Shipment SH-24024 was already billed on an earlier invoice; this second bill of 471.16 is a repeat. FI-8138,no_shipment,0.00,182.40,182.40,,"Shipment SH-29911 is not in our shipment records; invoice total 182.40 has nothing to match, so expected is 0.00." FI-8139,no_shipment,0.00,136.13,136.13,,"Shipment_id is blank; invoice total 136.13 has nothing to match, so expected is 0.00."
output/dispute.md · written by the agent, 44 lines
# Freight invoice dispute list Audited 39 invoices against the shipment records and rate card. ## Dispute by carrier - Copperline Freight: 4 invoice(s), 284.60 - Fenwater Logistics: 5 invoice(s), 1431.17 - Ridgeback Haulage: 5 invoice(s), 251.71 **Total to dispute: 1967.48** (14 invoices) ## Disputed invoices ### Copperline Freight - FI-8116 (overbilled): 36.76. Billed 323.53 vs expected 286.77: linehaul billed 283.80 vs expected 251.55; fuel billed 39.73 vs expected 35.22. - FI-8122 (overbilled): 64.24. Billed 682.84 vs expected 618.60: linehaul billed 546.35 vs expected 490.00; fuel billed 76.49 vs expected 68.60; billed weight 1115 kg vs shipment record 1000 kg. - FI-8131 (overbilled): 1.20. Billed 183.65 vs expected 182.45: fuel billed 21.15 vs expected 19.95. - FI-8138 (no_shipment): 182.40. Shipment SH-29911 is not in our shipment records; invoice total 182.40 has nothing to match, so expected is 0.00. ### Fenwater Logistics - FI-8105 (overbilled): 22.64. Billed 766.28 vs expected 743.64: linehaul billed 624.58 vs expected 604.18; fuel billed 68.70 vs expected 66.46; billed weight 1837 kg vs shipment record 1777 kg. - FI-8126 (overbilled): 10.00. Billed 201.05 vs expected 191.05: accessorials billed 55.00 vs expected 45.00. - FI-8129 (overbilled): 4.29. Billed 242.50 vs expected 238.21: fuel billed 27.90 vs expected 23.61. - FI-8135 (no_rate): 923.08. Rate card has no row for Fenwater Logistics zone A to D; invoice total 923.08 cannot be priced. - FI-8137 (duplicate): 471.16. Shipment SH-24024 was already billed on an earlier invoice; this second bill of 471.16 is a repeat. ### Ridgeback Haulage - FI-8109 (overbilled): 12.58. Billed 490.00 vs expected 477.42: fuel billed 57.52 vs expected 44.94. - FI-8112 (overbilled): 45.00. Billed 520.94 vs expected 475.94: accessorials billed 105.00 vs expected 60.00. - FI-8118 (overbilled): 30.00. Billed 1094.58 vs expected 1064.58: total 1094.58 is not the sum of its charges (1064.58). - FI-8133 (overbilled): 28.00. Billed 187.47 vs expected 159.47: accessorials billed 28.00 vs expected 0.00. - FI-8139 (no_shipment): 136.13. Shipment_id is blank; invoice total 136.13 has nothing to match, so expected is 0.00. ## Underbilled (not netted against the dispute total) - FI-8120 (Fenwater Logistics): carrier left off 45.00. Billed 307.69 vs expected 352.69: accessorials billed 0.00 vs expected 45.00. - FI-8127 (Ridgeback Haulage): carrier left off 38.02. Billed 38.48 vs expected 76.50: linehaul billed 34.20 vs expected 68.00; fuel billed 4.28 vs expected 8.50. Total left off: 83.02 ## Status counts duplicate: 1, no_rate: 1, no_shipment: 2, ok: 23, overbilled: 10, underbilled: 2
check.py · the check, written before the run
"""Rebuilds the expected cost of every shipment from the rate card and compares each invoice verdict with it."""
import csv, re, sys
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
root = Path(sys.argv[1]); ok = True
def say(passed, text):
global ok; ok = ok and passed; print(("PASS " if passed else "FAIL ") + text)
def c2(d): return d.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def money(s):
try: return Decimal((s or "").replace(",", "").replace("$", "").strip())
except Exception: return None
def load(name): return list(csv.DictReader((root/"input"/name).open()))
rates = {(r["carrier"], r["origin_zone"], r["dest_zone"]): r for r in load("rate_card.csv")}
fees = {r["code"]: Decimal(r["fee"]) for r in load("accessorial_fees.csv")}
ships = {r["shipment_id"]: r for r in load("shipments.csv")}
invs = load("freight_invoices.csv")
want, billed, first = {}, set(), {}
for inv in sorted(invs, key=lambda r: (r["invoice_date"], r["invoice_id"])):
total = Decimal(inv["total"]); sh = ships.get(inv["shipment_id"].strip())
w = {"st": "ok", "exp": Decimal("0.00"), "parts": set(), "carrier": (sh or inv)["carrier"].strip()}
rate = rates.get((sh["carrier"], sh["origin_zone"], sh["dest_zone"])) if sh else None
if not sh: w["st"] = "no_shipment"
elif sh["shipment_id"] in billed: w["st"] = "duplicate"
elif not rate: w["st"] = "no_rate"
else:
line = max(c2(Decimal(sh["weight_kg"]) * Decimal(rate["rate_per_kg"])), Decimal(rate["min_charge"]))
fuel = c2(line * Decimal(rate["fuel_pct"]) / 100)
acc = sum((fees[c] for c in sh["accessorials"].split(";") if c.strip()), Decimal(0))
w["exp"] = line + fuel + acc
if total - w["exp"] > 1: w["st"] = "overbilled"
elif w["exp"] - total > 1: w["st"] = "underbilled"
if w["st"] != "ok":
b = [Decimal(inv["linehaul"]), Decimal(inv["fuel"]), Decimal(inv["accessorial_charges"])]
for name, mine, theirs in zip(("linehaul", "fuel", "accessorials"), (line, fuel, acc), b):
if abs(mine - theirs) > Decimal("0.01"): w["parts"].add(name)
if sum(b) != total: w["parts"].add("total")
w["ids"] = {inv["invoice_id"], inv["shipment_id"].strip(), first.get(inv["shipment_id"].strip(), "")}
if sh: billed.add(sh["shipment_id"]); first.setdefault(sh["shipment_id"], inv["invoice_id"])
w["var"] = total - w["exp"]; w["total"] = total
# every number that belongs to this invoice: what was billed, what was expected and the gaps between them
f = {total, w["exp"], w["var"], Decimal(0), Decimal(1)}
f |= {Decimal(inv[c]) for c in ("billed_weight_kg", "linehaul", "fuel", "accessorial_charges")}
f.add(Decimal(inv["linehaul"]) + Decimal(inv["fuel"]) + Decimal(inv["accessorial_charges"]))
if sh: f |= {Decimal(sh["weight_kg"]), Decimal(inv["billed_weight_kg"]) - Decimal(sh["weight_kg"])} | {fees[c] for c in sh["accessorials"].split(";") if c.strip()}
if rate: f |= {line, fuel, acc, Decimal(rate["rate_per_kg"]), Decimal(rate["min_charge"]), Decimal(rate["fuel_pct"]), Decimal(inv["linehaul"]) - line, Decimal(inv["fuel"]) - fuel, Decimal(inv["accessorial_charges"]) - acc}
w["facts"] = {abs(x) for x in f}
want[inv["invoice_id"]] = w
path = root/"output/audit.csv"
if not path.exists():
say(False, "output/audit.csv was not written"); sys.exit(1)
rows = list(csv.DictReader(path.open()))
got = {r.get("invoice_id", ""): r for r in rows}
once = sum(1 for k in want if sum(1 for r in rows if r.get("invoice_id") == k) == 1)
say(once == len(want) and len(rows) == len(want), f"{once} of {len(want)} invoices appear once in audit.csv")
right = sum(1 for k, w in want.items() if (got.get(k, {}).get("status") or "").strip() == w["st"])
say(right == len(want), f"{right} of {len(want)} statuses equal the status recomputed from the rate card")
amt = sum(1 for k, w in want.items() if money(got.get(k, {}).get("expected_total")) == w["exp"] and money(got.get(k, {}).get("variance")) == w["var"] and money(got.get(k, {}).get("billed_total")) == w["total"])
say(amt == len(want), f"{amt} of {len(want)} rows carry the invoice total as billed, the recomputed expected total and the variance between them")
off = [k for k, w in want.items() if w["st"] in ("overbilled", "underbilled")]
def parts(s): return {p for p in re.split(r"[;,|\s]+", (s or "").strip().lower()) if p}
named = sum(1 for k in off if parts(got.get(k, {}).get("parts_off")) == want[k]["parts"])
clean = sum(1 for k, w in want.items() if k not in off and not parts(got.get(k, {}).get("parts_off")))
say(named == len(off) and clean == len(want) - len(off), f"{named} of {len(off)} wrongly billed invoices name the exact parts of the bill that are off")
text = (root/"output/dispute.md").read_text() if (root/"output/dispute.md").exists() else ""
disputed = [k for k, w in want.items() if w["st"] in ("overbilled", "duplicate", "no_shipment", "no_rate")]
def has(s, amount): return any(Decimal(n.replace(",", "")) == amount for n in re.findall(r"\d[\d,]*\.\d{2}", s))
listed = sum(1 for k in disputed if any(k in ln and has(ln, want[k]["var"]) for ln in text.splitlines()))
say(listed == len(disputed), f"{listed} of {len(disputed)} disputed invoices are listed in dispute.md with the right amount")
by = {}
for k in disputed: by[want[k]["carrier"]] = by.get(want[k]["carrier"], Decimal(0)) + want[k]["var"]
grand = sum(by.values())
car = sum(1 for c, t in by.items() if any(c.lower() in ln.lower() and has(ln, t) for ln in text.splitlines()))
say(car == len(by) and has(text, grand), f"dispute.md states the amount to dispute for {car} of {len(by)} carriers and the total, {grand:,.2f}")
def figures(s): return [Decimal(n.replace(",", "")) for n in re.findall(r"\d[\d,]*(?:\.\d+)?", re.sub(r"\b[A-Z]{2,}-\d+\b", " ", s))]
seen = wrong = 0; odd = []
for k, w in want.items():
for s in [got.get(k, {}).get("reason") or ""] + [ln for ln in text.splitlines() if k in ln and len(set(re.findall(r"FI-\d+", ln))) == 1]:
for n in figures(s):
seen += 1
if n not in w["facts"]: wrong += 1; odd.append(f"{n} for {k}")
for i in re.findall(r"\b(?:FI|SH)-\d+\b", s): # an invoice or shipment number beside this invoice must be its own
seen += 1
if i not in w["ids"]: wrong += 1; odd.append(f"{i} for {k}")
say(seen > 0 and wrong == 0, f"{seen - wrong} of {seen} numbers in the reasons and on the invoice lines of dispute.md are that invoice's own shipment number and its billed, expected or gap figures" + (": not " + ", ".join(odd[:3]) if odd else ""))
tally = {}
for w in want.values(): tally[w["st"]] = tally.get(w["st"], 0) + 1
under = [k for k, w in want.items() if w["st"] == "underbilled"]
world = {Decimal(x) for x in (len(want), len(ships), len(disputed), len(under), len(by), 1)} | {Decimal(v) for v in tally.values()} | {grand, sum((-want[k]["var"] for k in under), Decimal(0))}
seen = wrong = 0; odd = []
for ln in text.splitlines():
if re.search(r"FI-\d+", ln): continue
mine = [c for c in by if c.lower() in ln.lower()]
allowed = set(world)
for c in mine:
ks = [k for k, w in want.items() if w["carrier"] == c]
allowed = {Decimal(len(ks)), Decimal(sum(1 for k in ks if k in disputed)), Decimal(sum(1 for k in ks if k in under)), by[c], sum((-want[k]["var"] for k in ks if k in under), Decimal(0))}
for n in figures(ln):
seen += 1
if n not in allowed: wrong += 1; odd.append(str(n))
for st, c in tally.items():
for m in re.finditer(rf"(?<![a-z_]){st}\W{{1,3}}(\d+)", ln.lower()):
seen += 1
if int(m.group(1)) != c: wrong += 1; odd.append(f"{st} {m.group(1)}")
say(seen > 0 and wrong == 0, f"{seen - wrong} of {seen} counts and totals on the other lines of dispute.md equal the numbers recomputed from the invoices" + (": not " + ", ".join(odd[:3]) if odd else ""))
sys.exit(0 if ok else 1)
accessorial_fees.csv: sample data written by Atris. Fingerprint b8eddae312e2.
freight_invoices.csv: sample data written by Atris. Fingerprint 56706383acdd.
rate_card.csv: sample data written by Atris. Fingerprint 526fc4d9153d.
shipments.csv: sample data written by Atris. Fingerprint 811b9d350d9d.
audit.csv: written by the agent. Fingerprint 3e019d2c0b8d.
dispute.md: written by the agent. Fingerprint 98375c4c02a0.