Build the month-end accruals list.
Done by an agent. Checked twice.
One list of every cost received but not yet billed, with the sums shown and a journal entry ready to post.
Real files in
- goods_received.csv
Thirty goods received rows, with a repeated receipt, three dated after month end and one for an order that does not exist. 31 lines, 1 KB. - period.md
The month being closed and the account that accrued costs go to. 7 lines, 189 bytes. - purchase_orders.csv
Twenty-two purchase orders, one cancelled and one with no price. 23 lines, 2 KB. - supplier_invoices.csv
Sixteen supplier invoices, some posted after month end and one not posted at all. 17 lines, 1 KB. - unbilled_work.csv
Twenty contractor time entries, some already invoiced, some not approved and one with no rate. 21 lines, 1 KB.
Sample data written by Atris. Not a real company.
Three steps
- 1.Read the month and the records
- 2.Work out what is owed but unbilled
- 3.Write the result
Claude Sonnet 5.5, 37 seconds. No web. It never saw the check.
Checked twice
- Passed: 18 of 18 orders and contractors with an unbilled cost are in accruals.csv and 0 are there that should not be
- Passed: 18 of 18 accrual amounts equal the amount recomputed from receipts, invoices and time entries
- Passed: 6 of 6 items that cannot be costed are in review.csv once with the right issue
- Passed: accruals_summary.md states the total accrual, 25,650.25
- Passed: 9 of 9 account totals in accruals_summary.md sit beside their account and equal the sums recomputed from the input files
- Passed: the journal entry credits account 2150 with 25,650.25 and 9 of 9 debit lines carry the total of their account
- Passed: 18 of 18 rows of accruals.csv carry the type, supplier and account of their order or contractor
- Passed: 18 of 18 basis sums show the received, billed and price figures or the hours and rate recomputed from the input files
- Passed: 56 of 56 figures in accruals_summary.md and 8 of 8 in the review notes equal a figure of the account, order or entry they sit beside or a recomputed total
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 8 ways on purpose. The check caught 8.
ref,type,supplier,account,amount,basis PO-2101,goods,Halvorsen Supply,5100 Materials,322.50,400 received less 250 billed at 2.15 PO-2102,goods,Marrow Lane Logistics,5200 Freight,1240.00,8 received less 4 billed at 310.00 PO-2104,goods,Thornbury Cleaning,6300 Facilities,1850.00,2 received less 1 billed at 1850.00 PO-2105,goods,Quillfeather Print,6400 Marketing,1710.00,6 received less 0 billed at 285.00 PO-2106,goods,Dovecote Stationery,6100 Office supplies,1540.00,40 received less 0 billed at 38.50 PO-2107,goods,Castlereach Telecom,6200 IT and software,1230.00,4 received less 2 billed at 615.00 PO-2109,goods,Halvorsen Supply,5100 Materials,620.00,1000 received less 0 billed at 0.62 PO-2111,goods,Fernhill Media,6400 Marketing,1140.00,12 received less 0 billed at 95.00 PO-2114,goods,Wexcombe Legal,6600 Professional fees,3600.00,1 received less 0 billed at 3600.00 PO-2116,goods,Sorrel Catering,6700 Staff welfare,1480.00,80 received less 0 billed at 18.50 PO-2118,goods,Tiverton Pallets,5100 Materials,228.00,200 received less 180 billed at 11.40 PO-2120,goods,Marrow Lane Logistics,5200 Freight,378.00,27 received less 18 billed at 42.00 PO-2122,goods,Dovecote Stationery,6100 Office supplies,435.00,60 received less 0 billed at 7.25
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 2 of 2 on 1 December 2026. The agent took 37 seconds. Run 1 passed both checks and the job was run again later. Each run starts clean. Between runs the written flow was made clearer, or a check was corrected or made stricter. Nobody edits the output.
What the second review verified
- PO-2101: 250 (GR-5006) + 150 (GR-5018) received less 250 billed (SI-9106) = 150 x 2.15 = 322.50. PO-2118: 200 received less 180 billed (SI-9103 + SI-9113, both posted by 2026-11-30) = 20 x 11.40 = 228.00. PO-2117: GR-5027, dated 2026-12-01, is left out, so 100 received matches 100 billed and there is correctly no accrual.
- Invoices not yet in the books are excluded: SI-9114 (posted 2026-12-03), SI-9115 (no posted date) and SI-9116 (posted 2026-12-02). That gives PO-2105 1,710.00, PO-2109 620.00 (1000 x 0.62) and PO-2116 1,480.00. The duplicate receipt GR-5008 is counted once, so PO-2106 is 40 x 38.50 = 1,540.00.
- Contractor amounts: C-01 (36.5 + 28) = 64.5 hours x 85 = 5,482.50. C-03 (42.5 + 8) = 50.5 x 24.50 = 1,237.25. C-02 26 x 62 = 1,612.00. C-04 10.5 x 110 = 1,155.00. C-06 5 x 78 = 390.00. C-05 correctly has no accrual: T-717 is already invoiced and T-718 is after month end.
- Totals: the goods lines add to 15,773.50 and the work lines to 9,876.75, which makes 25,650.25. All 9 account totals were recomputed, for example 5100 = 322.50 + 620.00 + 228.00 = 1,170.50, and they also add to 25,650.25. The journal credits 2150 Accrued liabilities for 25,650.25. review.csv contains all 6 flagged items: PO-2199 unknown_po, PO-2110 billed_ahead (0.5 billed, receipt is dated 12-04), PO-2112 missing_price, T-707 and T-716 not_approved, T-720 missing_rate.
What this run does not show
- The records were written for this run, which makes no estimate for costs that have no receipt and no time entry.
- The notes in review.csv are read only by the second review, apart from their figures and dates.
- A wrong figure that equals another figure the check accepts on that line would pass, as a planted change from 10 hours to 13 did.
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 8 of 8. 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
# Build the month-end accruals list function: finance for: the accountant who closes the books each month goal: Every cost the business has received but not yet been billed for is on one list with its amount and anything that cannot be costed is flagged. ## 1. Read the month and the records Read input/period.md for the month end date. Read input/purchase_orders.csv, input/goods_received.csv, input/supplier_invoices.csv and input/unbilled_work.csv. Dates on the month end date count as inside the month. A row that appears twice with the same receipt_id is one receipt. ## 2. Work out what is owed but unbilled Goods and services on purchase orders, one purchase order at a time: - Skip a purchase order whose status is `cancelled`. - Received is the total quantity_received on receipts dated on or before the month end. - Billed is the total quantity_billed on invoices whose posted_date is on or before the month end. An invoice with a blank or later posted_date is not yet in the books, so it does not count. - When received is more than billed, the accrual is (received minus billed) times the unit_price on the purchase order. Use the order price, not the invoice amount. - When billed is more than received, there is no accrual. Flag it as `billed_ahead`. - When there is something to accrue but the order has no unit_price, flag it as `missing_price`. - A receipt whose po_number is not in the orders file is flagged as `unknown_po`. Contractor work, using entries with a work_date on or before the month end and a blank invoice_id: - An entry with approved not `yes` is flagged as `not_approved` and not accrued. - An approved entry with no hourly_rate is flagged as `missing_rate` and not accrued. - Every other entry accrues hours times hourly_rate. Add them up per contractor. ## 3. Write the result Write output/accruals.csv with columns ref,type,supplier,account,amount,basis. One row per purchase order with an accrual (ref is the po_number, type `goods`) and one row per contractor with an accrual (ref is the contractor_id, type `work`). amount has two decimals. basis shows the sum, such as `150 received less 0 billed at 2.15` or `64.5 hours at 85.00`. Leave out anything with no accrual. Write output/review.csv with columns ref,issue,note. One row per flagged item. ref is the po_number or the entry_id. Write output/accruals_summary.md with the total accrual, the total for each account and the journal entry: one debit line per expense account and one credit line to the accrued liabilities account named in period.md. ## Done looks like - Every purchase order and contractor with an unbilled cost appears once in accruals.csv. - The account totals in accruals_summary.md add up to the total accrual. - Everything that could not be costed is in review.csv with its issue.
input/goods_received.csv · 31 lines, 1 KB
receipt_id,po_number,received_date,quantity_received,received_by GR-5001,PO-2103,2026-11-03,25,IT desk GR-5002,PO-2104,2026-10-31,1,Facilities GR-5003,PO-2118,2026-11-05,120,Warehouse GR-5004,PO-2102,2026-11-06,4,Warehouse GR-5005,PO-2115,2026-11-09,30,Warehouse GR-5006,PO-2101,2026-11-10,250,Warehouse GR-5007,PO-2117,2026-11-11,100,Warehouse GR-5008,PO-2106,2026-11-12,40,Front office GR-5008,PO-2106,2026-11-12,40,Front office GR-5009,PO-2109,2026-11-13,600,Warehouse GR-5010,PO-2120,2026-11-14,18,Warehouse GR-5011,PO-2107,2026-11-17,4,IT desk GR-5012,PO-2119,2026-11-18,10,IT desk GR-5013,PO-2105,2026-11-19,6,Marketing GR-5014,PO-2102,2026-11-20,4,Warehouse GR-5015,PO-2112,2026-11-21,1,Marketing GR-5016,PO-2199,2026-11-22,15,Warehouse GR-5017,PO-2121,2026-11-23,1,Facilities GR-5018,PO-2101,2026-11-24,150,Warehouse GR-5019,PO-2118,2026-11-25,80,Warehouse GR-5020,PO-2114,2026-11-26,1,Finance GR-5021,PO-2109,2026-11-27,400,Warehouse GR-5022,PO-2116,2026-11-28,80,Front office GR-5023,PO-2120,2026-11-28,9,Warehouse GR-5024,PO-2104,2026-11-30,1,Facilities GR-5025,PO-2111,2026-11-30,12,Marketing GR-5026,PO-2122,2026-11-30,60,Front office GR-5027,PO-2117,2026-12-01,140,Warehouse GR-5028,PO-2102,2026-12-02,2,Warehouse GR-5029,PO-2110,2026-12-04,1,Facilities
input/period.md · 7 lines, 189 bytes
# Month being closed Company: Pennywhistle Packaging (an invented company) Month: November 2026 Month end date: 2026-11-30 Accrued costs are credited to account 2150 Accrued liabilities.
input/purchase_orders.csv · 23 lines, 2 KB
po_number,supplier,account,item,quantity,unit_price,status PO-2101,Halvorsen Supply,5100 Materials,Corrugated cartons,400,2.15,open PO-2102,Marrow Lane Logistics,5200 Freight,Pallet freight runs,12,310.00,open PO-2103,Kestrel Software,6200 IT and software,Design licences,25,144.00,open PO-2104,Thornbury Cleaning,6300 Facilities,Monthly cleaning visits,3,1850.00,open PO-2105,Quillfeather Print,6400 Marketing,Trade show banners,6,285.00,open PO-2106,Dovecote Stationery,6100 Office supplies,Paper and toner cases,40,38.50,open PO-2107,Castlereach Telecom,6200 IT and software,Network switches,4,615.00,open PO-2108,Greywell Fabrication,5100 Materials,Steel brackets,500,4.80,open PO-2109,Halvorsen Supply,5100 Materials,Foam inserts,1000,0.62,open PO-2110,Pell & Sons,6300 Facilities,Loading dock repair,1,4200.00,open PO-2111,Fernhill Media,6400 Marketing,Radio spots,20,95.00,open PO-2112,Northgate Signs,6400 Marketing,Shopfront sign,1,,open PO-2113,Brightline Freight,5200 Freight,Container haulage,3,1275.00,cancelled PO-2114,Wexcombe Legal,6600 Professional fees,Lease review,1,3600.00,open PO-2115,Lindqvist Tooling,5100 Materials,Die cutter blades,30,46.75,open PO-2116,Sorrel Catering,6700 Staff welfare,Staff event meals,80,18.50,open PO-2117,Halvorsen Supply,5100 Materials,Packing tape rolls,240,3.10,open PO-2118,Tiverton Pallets,5100 Materials,Timber pallets,200,11.40,open PO-2119,Ashgrove IT,6200 IT and software,Laptop docks,10,129.00,open PO-2120,Marrow Lane Logistics,5200 Freight,Express courier drops,30,42.00,open PO-2121,Brannock Safety,6300 Facilities,Fire extinguisher service,1,780.00,open PO-2122,Dovecote Stationery,6100 Office supplies,Filing boxes,60,7.25,open
input/supplier_invoices.csv · 17 lines, 1 KB
invoice_id,po_number,supplier,invoice_date,quantity_billed,amount,posted_date SI-9101,PO-2103,Kestrel Software,2026-11-03,25,3600.00,2026-11-05 SI-9102,PO-2104,Thornbury Cleaning,2026-11-01,1,1850.00,2026-11-04 SI-9103,PO-2118,Tiverton Pallets,2026-11-06,120,1368.00,2026-11-12 SI-9104,PO-2102,Marrow Lane Logistics,2026-11-09,4,1240.00,2026-11-14 SI-9105,PO-2115,Lindqvist Tooling,2026-11-10,30,1402.50,2026-11-16 SI-9106,PO-2101,Halverson Supply,2026-11-12,250,537.50,2026-11-18 SI-9107,PO-2117,Halvorsen Supply,2026-11-13,100,310.00,2026-11-19 SI-9108,PO-2110,Pell & Sons,2026-11-16,0.5,2100.00,2026-11-20 SI-9109,PO-2120,Marrow Lane Logistics,2026-11-17,18,756.00,2026-11-21 SI-9110,PO-2119,Ashgrove IT,2026-11-19,10,1290.00,2026-11-24 SI-9111,PO-2107,Castlereach Telecom,2026-11-20,2,1260.00,2026-11-27 SI-9112,PO-2121,Brannock Safety,2026-11-24,1,780.00,2026-11-30 SI-9113,PO-2118,Tiverton Pallets,2026-11-26,60,684.00,2026-11-30 SI-9114,PO-2105,Quillfeather Print,2026-11-25,6,1710.00,2026-12-03 SI-9115,PO-2109,Halvorsen Supply,2026-11-28,1000,620.00, SI-9116,PO-2116,Sorrel Catering,2026-11-30,80,1480.00,2026-12-02
input/unbilled_work.csv · 21 lines, 1 KB
entry_id,contractor_id,contractor,account,work_date,hours,hourly_rate,approved,invoice_id T-701,C-01,Aldous Byrne,6500 Contract labor,2026-11-06,32,85.00,yes,CI-880 T-702,C-01,Aldous Byrne,6500 Contract labor,2026-11-13,30,85.00,yes,CI-880 T-703,C-01,Aldous Byrne,6500 Contract labor,2026-11-20,36.5,85.00,yes, T-704,C-01,Aldous Byrne,6500 Contract labor,2026-11-27,28,85.00,yes, T-705,C-01,Aldous Byrne,6500 Contract labor,2026-12-04,20,85.00,yes, T-706,C-02,Marisol Etxeberria,6600 Professional fees,2026-11-13,12,62.00,yes, T-707,C-02,Marisol Etxeberria,6600 Professional fees,2026-11-20,10,62.00,no, T-708,C-02,Marisol Etxeberria,6600 Professional fees,2026-11-27,14,62.00,yes, T-709,C-03,Idris Vance,6500 Contract labor,2026-11-06,40,24.50,yes,CI-871 T-710,C-03,Idris Vance,6500 Contract labor,2026-11-13,40,24.50,yes,CI-871 T-711,C-03,Idris Vance,6500 Contract labor,2026-11-20,38,24.50,yes,CI-893 T-712,C-03,Idris Vance,6500 Contract labor,2026-11-27,42.5,24.50,yes, T-713,C-03,Idris Vance,6500 Contract labor,2026-11-30,8,24.50,yes, T-714,C-04,Petra Solheim,6200 IT and software,2026-11-10,6,110.00,yes, T-715,C-04,Petra Solheim,6200 IT and software,2026-11-24,4.5,110.00,yes, T-716,C-04,Petra Solheim,6200 IT and software,2026-11-28,3,110.00,no, T-717,C-05,Oluwaseun Adair,6400 Marketing,2026-11-19,8,95.00,yes,CI-902 T-718,C-05,Oluwaseun Adair,6400 Marketing,2026-12-02,6,95.00,yes, T-719,C-06,Hollis Tran,6300 Facilities,2026-11-18,5,78.00,yes, T-720,C-06,Hollis Tran,6300 Facilities,2026-11-25,7,,yes,
output/accruals.csv · written by the agent, 19 lines
ref,type,supplier,account,amount,basis PO-2101,goods,Halvorsen Supply,5100 Materials,322.50,400 received less 250 billed at 2.15 PO-2102,goods,Marrow Lane Logistics,5200 Freight,1240.00,8 received less 4 billed at 310.00 PO-2104,goods,Thornbury Cleaning,6300 Facilities,1850.00,2 received less 1 billed at 1850.00 PO-2105,goods,Quillfeather Print,6400 Marketing,1710.00,6 received less 0 billed at 285.00 PO-2106,goods,Dovecote Stationery,6100 Office supplies,1540.00,40 received less 0 billed at 38.50 PO-2107,goods,Castlereach Telecom,6200 IT and software,1230.00,4 received less 2 billed at 615.00 PO-2109,goods,Halvorsen Supply,5100 Materials,620.00,1000 received less 0 billed at 0.62 PO-2111,goods,Fernhill Media,6400 Marketing,1140.00,12 received less 0 billed at 95.00 PO-2114,goods,Wexcombe Legal,6600 Professional fees,3600.00,1 received less 0 billed at 3600.00 PO-2116,goods,Sorrel Catering,6700 Staff welfare,1480.00,80 received less 0 billed at 18.50 PO-2118,goods,Tiverton Pallets,5100 Materials,228.00,200 received less 180 billed at 11.40 PO-2120,goods,Marrow Lane Logistics,5200 Freight,378.00,27 received less 18 billed at 42.00 PO-2122,goods,Dovecote Stationery,6100 Office supplies,435.00,60 received less 0 billed at 7.25 C-01,work,Aldous Byrne,6500 Contract labor,5482.50,64.5 hours at 85.00 C-02,work,Marisol Etxeberria,6600 Professional fees,1612.00,26 hours at 62.00 C-03,work,Idris Vance,6500 Contract labor,1237.25,50.5 hours at 24.50 C-04,work,Petra Solheim,6200 IT and software,1155.00,10.5 hours at 110.00 C-06,work,Hollis Tran,6300 Facilities,390.00,5 hours at 78.00
output/accruals_summary.md · written by the agent, 55 lines
# Accruals summary - November 2026 (month end 2026-11-30) Company: Pennywhistle Packaging **Total accrual: 25,650.25** (18 lines: 13 purchase orders, 5 contractors) ## Total by account | Account | Amount | |---|---:| | 5100 Materials | 1,170.50 | | 5200 Freight | 1,618.00 | | 6100 Office supplies | 1,975.00 | | 6200 IT and software | 2,385.00 | | 6300 Facilities | 2,240.00 | | 6400 Marketing | 2,850.00 | | 6500 Contract labor | 6,719.75 | | 6600 Professional fees | 5,212.00 | | 6700 Staff welfare | 1,480.00 | | **Total** | **25,650.25** | ## Journal entry Date: 2026-11-30 | Account | Debit | Credit | |---|---:|---:| | 5100 Materials | 1,170.50 | | | 5200 Freight | 1,618.00 | | | 6100 Office supplies | 1,975.00 | | | 6200 IT and software | 2,385.00 | | | 6300 Facilities | 2,240.00 | | | 6400 Marketing | 2,850.00 | | | 6500 Contract labor | 6,719.75 | | | 6600 Professional fees | 5,212.00 | | | 6700 Staff welfare | 1,480.00 | | | 2150 Accrued liabilities | | 25,650.25 | | **Total** | **25,650.25** | **25,650.25** | ## Not costed - see review.csv 6 items flagged: - PO-2199 `unknown_po`: Receipt GR-5016 (15 units on 2026-11-22) refers to a purchase order not in the orders file; not costed. - PO-2110 `billed_ahead`: 0.5 billed in the books but only 0 received by 2026-11-30; no accrual. - PO-2112 `missing_price`: 1 received and not billed but the purchase order has no unit_price; cannot cost. - T-707 `not_approved`: Marisol Etxeberria 2026-11-20 10 hours not approved; not accrued. - T-716 `not_approved`: Petra Solheim 2026-11-28 3 hours not approved; not accrued. - T-720 `missing_rate`: Hollis Tran 2026-11-25 7 hours approved but no hourly_rate; cannot cost. ## Notes - Goods are costed at the purchase order unit_price, not the invoice amount. - Receipt GR-5008 appears twice in goods_received.csv and was counted once. - Invoices posted after 2026-11-30 or with no posted_date (SI-9114, SI-9115, SI-9116) were not counted as billed. - Contractor entries already carrying an invoice_id, and entries dated after month end, are excluded. - Invoice SI-9106 names the supplier 'Halverson Supply' vs 'Halvorsen Supply' on the order; matched by po_number, no effect on amounts.
output/review.csv · written by the agent, 7 lines
ref,issue,note PO-2199,unknown_po,Receipt GR-5016 (15 units on 2026-11-22) refers to a purchase order not in the orders file; not costed. PO-2110,billed_ahead,0.5 billed in the books but only 0 received by 2026-11-30; no accrual. PO-2112,missing_price,1 received and not billed but the purchase order has no unit_price; cannot cost. T-707,not_approved,Marisol Etxeberria 2026-11-20 10 hours not approved; not accrued. T-716,not_approved,Petra Solheim 2026-11-28 3 hours not approved; not accrued. T-720,missing_rate,Hollis Tran 2026-11-25 7 hours approved but no hourly_rate; cannot cost.
check.py · the check, written before the run
"""Rebuilds the accruals list from the input files and compares it with what the agent wrote."""
import csv, re, sys
from collections import defaultdict
from decimal import Decimal
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 money(s):
try: return round(float(str(s).replace(",", "").replace("$", "").strip()), 2)
except ValueError: return None
# Figures in the written files. A figure is a number that is not part of an id or a date.
FIG = re.compile(r"(?<![\w.])(?<!\w-)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?!\w|-\w)")
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
def dec(x): return abs(Decimal(str(x).replace(",", "").replace("$", "").strip()))
def figs(line): return [dec(m.group(0)) for m in FIG.finditer(line)]
def together(text, *vals):
"""True when one line of the text carries every one of these figures."""
return any(all(dec(v) in figs(ln) for v in vals) for ln in text.splitlines())
def writeup(text, id_re, rec, glob):
"""Every figure of two or more characters and every date must belong to a record named on its line
or to the facts that hold for the whole file. Returns how many were seen and the ones that do not."""
seen, bad = 0, []
for ln in text.splitlines():
allow = set(glob).union(*(rec[i] for i in re.findall(id_re, ln) if i in rec))
for t in [m.group(0) for m in FIG.finditer(ln) if len(m.group(0)) > 1] + DAY.findall(ln):
seen += 1
if (t if DAY.fullmatch(t) else dec(t)) not in allow: bad.append(t)
return seen, bad
def load(name): return list(csv.DictReader((root/"input"/name).open()))
end = re.search(r"Month end date:\s*(\d{4}-\d{2}-\d{2})", (root/"input/period.md").read_text()).group(1)
pos = {r["po_number"]: r for r in load("purchase_orders.csv")}
recv, billed, seen = defaultdict(float), defaultdict(float), set()
want, review = {}, {} # ref -> (amount, account) ; ref -> issue
for r in load("goods_received.csv"):
if r["receipt_id"] in seen: continue
seen.add(r["receipt_id"])
if r["po_number"] not in pos: review[r["po_number"]] = "unknown_po"; continue
if r["received_date"] <= end: recv[r["po_number"]] += float(r["quantity_received"])
for r in load("supplier_invoices.csv"):
if r["posted_date"].strip() and r["posted_date"].strip() <= end: billed[r["po_number"]] += float(r["quantity_billed"])
for po, r in pos.items():
if r["status"].strip() == "cancelled": continue
if billed[po] > recv[po]: review[po] = "billed_ahead"
elif recv[po] > billed[po]:
if not r["unit_price"].strip(): review[po] = "missing_price"
else: want[po] = (round((recv[po] - billed[po]) * float(r["unit_price"]) + 1e-9, 2), r["account"])
work = defaultdict(float); acct = {}
for r in load("unbilled_work.csv"):
if r["work_date"] > end or r["invoice_id"].strip(): continue
if r["approved"].strip().lower() != "yes": review[r["entry_id"]] = "not_approved"
elif not r["hourly_rate"].strip(): review[r["entry_id"]] = "missing_rate"
else: work[r["contractor_id"]] += float(r["hours"]) * float(r["hourly_rate"]); acct[r["contractor_id"]] = r["account"]
for c, v in work.items(): want[c] = (round(v + 1e-9, 2), acct[c])
path = root/"output/accruals.csv"
if not path.exists():
say(False, "output/accruals.csv was not written"); sys.exit(1)
rows = list(csv.DictReader(path.open()))
got = {(r.get("ref") or "").strip(): r for r in rows}
n = len(want); extra = len(set(got) - set(want))
say(set(got) == set(want) and len(rows) == n,
f"{len(set(got) & set(want))} of {n} orders and contractors with an unbilled cost are in accruals.csv and {extra} are there that should not be")
right = sum(1 for k, v in want.items() if k in got and money(got[k].get("amount")) == v[0])
say(right == n, f"{right} of {n} accrual amounts equal the amount recomputed from receipts, invoices and time entries")
rpath = root/"output/review.csv"
rrows = list(csv.DictReader(rpath.open())) if rpath.exists() else []
rgot = {(r.get("ref") or "").strip(): (r.get("issue") or "").strip() for r in rrows}
rr = sum(1 for k, v in review.items() if rgot.get(k) == v)
say(rr == len(review) and set(rgot) == set(review) and len(rrows) == len(review), f"{rr} of {len(review)} items that cannot be costed are in review.csv once with the right issue")
md = (root/"output/accruals_summary.md").read_text() if (root/"output/accruals_summary.md").exists() else ""
nums = [money(x) for x in re.findall(r"\d[\d,]*\.\d{2}", md)]
total = round(sum(v[0] for v in want.values()), 2)
say(total in nums, f"accruals_summary.md states the total accrual, {total:,.2f}")
by = defaultdict(float)
for v in want.values(): by[v[1]] += v[0]
hit = sum(1 for a, v in by.items() if together(md, a.split()[0], round(v, 2)))
say(hit == len(by), f"{hit} of {len(by)} account totals in accruals_summary.md sit beside their account and equal the sums recomputed from the input files")
liability = re.search(r"credited to account (\d+)", (root/"input/period.md").read_text()).group(1)
journal = md[md.lower().find("journal"):] if "journal" in md.lower() else ""
debits = sum(1 for a, v in by.items() if together(journal, a.split()[0], round(v, 2)))
say(together(journal, liability, total) and debits == len(by),
f"the journal entry credits account {liability} with {total:,.2f} and {debits} of {len(by)} debit lines carry the total of their account")
# the columns of accruals.csv that are copied from the records
names = {r["contractor_id"]: r["contractor"].strip() for r in load("unbilled_work.csv")}
def copied(k):
r = got.get(k, {}); kind = "goods" if k in pos else "work"
return ((r.get("type") or "").strip() == kind and (r.get("supplier") or "").strip() == (pos[k]["supplier"].strip() if k in pos else names[k])
and (r.get("account") or "").strip() == want[k][1].strip())
cp = sum(1 for k in want if copied(k))
say(cp == n, f"{cp} of {n} rows of accruals.csv carry the type, supplier and account of their order or contractor")
# what each record holds, so a figure written beside it can be compared
rec = defaultdict(set); hours = defaultdict(float); rates = defaultdict(set); seen = set()
for r in load("goods_received.csv"):
if r["receipt_id"] in seen: continue
seen.add(r["receipt_id"])
for k in (r["receipt_id"], r["po_number"]): rec[k] |= {dec(r["quantity_received"]), r["received_date"]}
for r in load("supplier_invoices.csv"):
for k in (r["invoice_id"], r["po_number"]):
rec[k] |= {dec(r["quantity_billed"]), dec(r["amount"]), r["invoice_date"], r["posted_date"].strip()}
for po, r in pos.items():
rec[po] |= {dec(r["quantity"]), dec(recv[po]), dec(billed[po]), dec(abs(recv[po] - billed[po]))} | ({dec(r["unit_price"])} if r["unit_price"].strip() else set())
if po in want: rec[po].add(dec(want[po][0]))
for r in load("unbilled_work.csv"):
own = {dec(r["hours"]), r["work_date"]} | ({dec(r["hourly_rate"]), dec(round(float(r["hours"]) * float(r["hourly_rate"]) + 1e-9, 2))} if r["hourly_rate"].strip() else set())
rec[r["entry_id"]] |= own
counts = r["work_date"] <= end and not r["invoice_id"].strip() and r["approved"].strip().lower() == "yes" and r["hourly_rate"].strip()
if counts: hours[r["contractor_id"]] += float(r["hours"]); rates[r["contractor_id"]].add(dec(r["hourly_rate"]))
for c in work: rec[c] |= {dec(hours[c]), dec(want[c][0])} | rates[c]
def basis_ok(k):
f = figs(got.get(k, {}).get("basis") or "")
must = {dec(recv[k]), dec(billed[k]), dec(pos[k]["unit_price"])} if k in pos else {dec(hours[k])} | rates[k]
return bool(f) and must <= set(f) and set(f) <= rec[k]
bs = sum(1 for k in want if basis_ok(k))
say(bs == n, f"{bs} of {n} basis sums show the received, billed and price figures or the hours and rate recomputed from the input files")
for a, v in by.items(): rec[a.split()[0]] = {dec(a.split()[0]), dec(round(v, 2))}
rec[liability] = {dec(liability), dec(total)}
tally = defaultdict(int)
for v in review.values(): tally[v] += 1
facts = set(figs((root/"input/period.md").read_text())) | {end, dec(total), dec(n), dec(len(review)), dec(sum(1 for k in want if k in pos)), dec(len(work)), dec(len(by))} | {dec(c) for c in tally.values()}
ID = r"(?:PO|GR|SI|T|C)-\d+|(?<![\w.,-])\d{4}(?![\w.,-])"
seen_n, bad = writeup(md, ID, rec, facts)
seen2 = bad2 = 0
for r in rrows:
s2, b2 = writeup(r.get("note") or "", ID, rec, facts | rec[(r.get("ref") or "").strip()])
seen2 += s2; bad2 += len(b2)
say(seen_n > 0 and not bad and bad2 == 0, f"{seen_n - len(bad)} of {seen_n} figures in accruals_summary.md and {seen2 - bad2} of {seen2} in the review notes equal a figure of the account, order or entry they sit beside or a recomputed total")
sys.exit(0 if ok else 1)
goods_received.csv: sample data written by Atris. Fingerprint 4e51e55d40e1.
period.md: sample data written by Atris. Fingerprint a5edddc74d03.
purchase_orders.csv: sample data written by Atris. Fingerprint 4470394aef3f.
supplier_invoices.csv: sample data written by Atris. Fingerprint 90261b89be53.
unbilled_work.csv: sample data written by Atris. Fingerprint 0631c98bf680.
accruals.csv: written by the agent. Fingerprint 67f52585a329.
accruals_summary.md: written by the agent. Fingerprint ea421115e6a3.
review.csv: written by the agent. Fingerprint 6343eefc1e1b.