Age unpaid invoices and draft reminder letters.
Done by an agent. Checked twice.
Every unpaid invoice aged to the day and a ready reminder letter for each late customer, firmer the later they are.
Real files in
- as_of.md
The review date and who signs the letters. 6 lines, 221 bytes. - customers.csv
Fourteen customers with contact, email and payment terms, one with no contact on file. 15 lines, 1018 bytes. - open_invoices.csv
Thirty-eight invoice rows, with part payments, paid invoices, disputes, a credit note, an overpayment, blank due dates and a repeated row. 39 lines, 3 KB.
Sample data written by Atris. Not a real company.
Three steps
- 1.Read the invoices and the customers
- 2.Age each invoice and pick each letter
- 3.Write the result
Claude Sonnet 5.5, 49 seconds. No web. It never saw the check.
Checked twice
- Passed: 35 of 35 invoices with a balance appear once in aging.csv, with paid and repeated rows left out
- Passed: 35 of 35 rows carry the customer, balance, due date, days late and bucket recomputed from the input files
- Passed: aging_summary.md states 6 of 6 bucket totals beside their bucket and the total owed, 66,966.60
- Passed: 12 of 12 customers with a late invoice have a letter and 0 letters went to someone who should not get one
- Passed: 12 of 12 letters carry the level set by the oldest late invoice, the contact on file and the as of date
- Passed: 19 of 19 late invoices are listed in the right letter with due date, days late and balance and 0 invoices that are current, disputed, paid or credits are listed
- Passed: 12 of 12 letters state a total overdue equal to the sum of their late balances
- Passed: aging_summary.md gives 14 of 14 customer totals beside their customer, names 2 of 2 disputed invoices and gives 12 of 12 letter levels
- Passed: 41 of 41 figures and dates in aging_summary.md and 78 of 78 in the letters equal a figure of the invoice or customer 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.
Level: hold To: Marek Nowak, Greywell Brewery Date: 2026-11-30 Dear Marek Nowak, The invoice(s) below are seriously overdue. Your account is on hold now and will stay on hold until the overdue amount is paid. - INV-4061: due 2026-07-25, 128 days late, balance 3720.00 - INV-4079: due 2026-09-01, 90 days late, balance 2105.00 - INV-4103: due 2026-11-08, 22 days late, balance 1860.00 Total overdue: 7685.00
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 49 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
- Recomputed all 35 rows of aging.csv from the input and every row matches exactly. The duplicate INV-4097 is counted once, and INV-4092 and INV-4095 are left out because their balance is 0.00. Blank due dates were filled from customer terms: INV-4104 = 2026-11-26 (45 days, 4 late), INV-4113 = 2026-12-29, INV-4122 = 2026-12-03 and CN-0031 = 2027-01-01.
- Summary totals match my recomputation: total owed 66966.60; credit -410.00, current 17127.40, 1-30 18411.00, 31-60 13913.20, 61-90 5305.00, over-90 12620.00. All 14 customer totals also match, for example CU-110 at 9325.00.
- The 12 letters go to the right customers at the right levels, such as CU-102 final (INV-4088, 72 days late), CU-104 hold (INV-4070, 91 days late), CU-114 firm (60 days late) and CU-105 friendly (only INV-4112, because disputed INV-4091 is left out). CU-111 correctly gets no letter: its only late invoice, INV-4107, is disputed. CU-107 has only a credit, so it gets none either.
- Letter contents are right: each Total overdue matches the sum of the listed invoices (e.g. CU-110 7685.00 = 3720.00 + 2105.00 + 1860.00, CU-112 570.05). No letter names a credit, a not-yet-due invoice or a disputed invoice. CU-106 is addressed to 'Accounts Payable' and is flagged in the summary as having no email. Every letter is dated 2026-11-30 and signed 'Accounts Receivable, Marrowfield Supply Co'.
What this run does not show
- The tone and wording of the letters are read only by the second review.
- No letter was sent, so nothing here shows that an email address works or that a customer has not already paid.
- The customers and invoices were written for this run, while real ledgers hold part payments spread over several invoices.
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
# Age unpaid invoices and draft reminder letters function: finance for: the person who chases customer payments goal: Every unpaid invoice is aged as of the review date and every customer with a late invoice has a reminder letter pitched to how late they are. ## 1. Read the invoices and the customers Read input/as_of.md for the as of date, input/open_invoices.csv and input/customers.csv. Go by customer_id, not by how the name is spelled. A row that repeats an invoice_id counts once. The balance of a row is amount minus paid. Leave out rows with a balance of exactly 0.00. When due_date is blank, the due date is the invoice_date plus that customer's terms_days. ## 2. Age each invoice and pick each letter Days late is the as of date minus the due date. It is never less than 0. Put each row in one bucket: - `credit` when the balance is negative (a credit note or an overpayment). Days late is 0. - `current` when it is 0 days late. - `1-30`, `31-60`, `61-90` or `over-90` by days late. A customer gets a letter when they have at least one late invoice (1 day or more) whose status is not `disputed`. The level of the letter comes from the oldest such invoice: `friendly` for 1-30, `firm` for 31-60, `final` for 61-90 and `hold` for over-90. Disputed invoices are aged like any other but never chased. Credits are never netted against a letter. ## 3. Write the result Write output/aging.csv with columns invoice_id,customer_id,balance,due_date,days_late,bucket. One row per invoice or credit with a balance, sorted by customer_id then invoice_id. Write output/aging_summary.md: the total owed (the sum of every balance, credits included), the total in each of the six buckets, one line per customer with their total, the disputed invoices, the letters written with their levels and any customer who gets a letter but has no email on file. Write one letter per customer who gets one, at output/letters/<customer_id>.md, in this shape: - Line 1 is `Level: <level>`. Line 2 is `To: <contact name>, <customer name>`, using `Accounts Payable` when no contact name is on file. - A short letter dated the as of date and signed as as_of.md says. `friendly` assumes an oversight. `firm` asks for payment within 7 days. `final` says it is the final notice and that the account goes on hold if unpaid in 7 days. `hold` says the account is on hold now until it is paid. - One line per late invoice that is not disputed, with its invoice_id, due date, days late and balance. Name no other invoice or credit anywhere in the letter. - A line `Total overdue: <sum of those balances>` with two decimals. ## Done looks like - Every invoice with a balance appears once in aging.csv in the right bucket. - Every customer with a late invoice that is not disputed has one letter at the right level. - No letter chases an invoice that is not yet due, is disputed or is already paid.
input/as_of.md · 6 lines, 221 bytes
# Receivables review Company: Marrowfield Supply Co (an invented company) As of date: 2026-11-30 Letters are signed by: Accounts Receivable, Marrowfield Supply Co Payment questions go to: receivables@marrowfield.example
input/customers.csv · 15 lines, 1018 bytes
customer_id,name,contact_name,email,terms_days CU-101,Brannock Dental Group,Helena Marsh,accounts@brannockdental.example,30 CU-102,Tiverton School Trust,Samir Qureshi,finance@tivertonschool.example,30 CU-103,Ashgrove Clinic,Nadia Ferrant,office@ashgroveclinic.example,30 CU-104,Lindqvist Motors,Oskar Lindqvist,oskar@lindqvistmotors.example,45 CU-105,Wexcombe Hotel,Gemma Hale,payables@wexcombehotel.example,30 CU-106,Sorrel Bakery,,,14 CU-107,Fenmoor Garden Centre,Ruth Abara,ruth@fenmoorgarden.example,30 CU-108,Castlereach Vets,Tom Iveson,practice@castlereachvets.example,30 CU-109,Dovecote Nursery School,Aisha Bello,bursar@dovecotenursery.example,60 CU-110,Greywell Brewery,Marek Nowak,marek@greywellbrewery.example,30 CU-111,Thornbury Gym,Callum Reyes,callum@thornburygym.example,30 CU-112,Halvorsen Farm Shop,Ingrid Halvorsen,shop@halvorsenfarm.example,14 CU-113,Pell Street Pharmacy,Yusuf Demir,accounts@pellstreetpharmacy.example,30 CU-114,Quillfeather Books,Lottie Graves,lottie@quillfeatherbooks.example,30
input/open_invoices.csv · 39 lines, 3 KB
invoice_id,customer_id,customer_name,invoice_date,due_date,amount,paid,status INV-4061,CU-110,Greywell Brewery,2026-06-25,2026-07-25,4720.00,1000.00,open INV-4070,CU-104,Lindqvist Motors,2026-07-17,2026-08-31,8900.00,0.00,open INV-4079,CU-110,Greywell Brewery,2026-08-02,2026-09-01,2105.00,0.00,open INV-4083,CU-107,Fenmoor Garden Centre,2026-08-11,2026-09-10,2150.00,2250.00,open INV-4086,CU-109,Dovecote Nursery School,2026-08-15,2026-10-14,3310.00,0.00,open INV-4088,CU-102,Tiverton School Trust,2026-08-20,2026-09-19,6400.00,3200.00,open INV-4091,CU-105,Wexcombe Hotel,2026-09-10,2026-10-10,5625.00,0.00,disputed INV-4092,CU-113,Pell Street Pharmacy,2026-09-14,2026-10-14,1530.00,1530.00,open INV-4094,CU-114,Quillfeather Books,2026-09-01,2026-10-01,2890.00,0.00,open INV-4095,CU-103,Ashgrove Clinic,2026-09-22,2026-10-22,980.50,980.50,open INV-4097,CU-108,Castlereach Vets,2026-09-28,2026-10-28,1675.40,0.00,open INV-4099,CU-106,Sorrel Bakery,2026-10-01,2026-10-15,412.80,0.00,open INV-4100,CU-114,Quillfeather Books,2026-10-01,2026-10-31,1140.00,0.00,open INV-4101,CU-101,Brannock Dental Group,2026-10-05,2026-11-04,1840.00,0.00,open INV-4102,CU-102,Tiverton School Trust,2026-10-08,2026-11-07,4150.00,0.00,open INV-4103,CU-110,Greywell Brewery,2026-10-09,2026-11-08,1860.00,0.00,open INV-4104,CU-104,Lindquist Motors,2026-10-12,,3480.00,0.00,open INV-4105,CU-113,Pell Street Pharmacy,2026-10-14,2026-11-13,1422.00,700.00,open INV-4107,CU-111,Thornbury Gym,2026-10-16,2026-11-15,745.00,0.00,disputed INV-4109,CU-103,Ashgrove Clinic,2026-10-20,2026-11-19,1215.75,0.00,open INV-4110,CU-106,Sorrel Bakery,2026-10-22,2026-11-05,388.20,0.00,open INV-4097,CU-108,Castlereach Vets,2026-09-28,2026-10-28,1675.40,0.00,open INV-4111,CU-112,Halvorsen Farm Shop,2026-10-26,2026-11-09,268.90,0.00,open INV-4112,CU-105,Wexcombe Hotel,2026-10-28,2026-11-27,2300.00,0.00,open INV-4113,CU-109,Dovecote Nursery School,2026-10-30,,2480.00,0.00,open INV-4119,CU-114,Quillfeather Books,2026-10-31,2026-11-30,960.00,0.00,open CN-0031,CU-109,Dovecote Nursery School,2026-11-02,,-310.00,0.00,open INV-4115,CU-107,Fenmoor Garden Centre,2026-11-05,2026-12-05,1990.00,0.00,open INV-4116,CU-112,Halvorsen Farm Shop,2026-11-09,2026-11-23,301.15,0.00,open INV-4117,CU-101,Brannock Dental Group,2026-11-10,2026-12-10,2260.00,0.00,open INV-4118,CU-108,Castlereach Vets,2026-11-12,2026-12-12,890.00,0.00,open INV-4120,CU-102,Tiverton School Trust,2026-11-14,2026-12-14,2975.00,0.00,open INV-4121,CU-111,Thornbury Gym,2026-11-17,2026-12-17,745.00,0.00,open INV-4122,CU-106,Sorrel Bakery,2026-11-19,,405.00,0.00,open INV-4123,CU-112,Halvorsen Farm Shop,2026-11-23,2026-12-07,289.40,0.00,open INV-4124,CU-103,Ashgrove Clinic,2026-11-24,2026-12-24,1105.00,0.00,open INV-4125,CU-110,Greywell Brewery,2026-11-25,2026-12-25,1640.00,0.00,open INV-4126,CU-113,Pell Street Pharmacy,2026-11-26,2026-12-26,1388.00,0.00,open
output/aging.csv · written by the agent, 36 lines
invoice_id,customer_id,balance,due_date,days_late,bucket INV-4101,CU-101,1840.00,2026-11-04,26,1-30 INV-4117,CU-101,2260.00,2026-12-10,0,current INV-4088,CU-102,3200.00,2026-09-19,72,61-90 INV-4102,CU-102,4150.00,2026-11-07,23,1-30 INV-4120,CU-102,2975.00,2026-12-14,0,current INV-4109,CU-103,1215.75,2026-11-19,11,1-30 INV-4124,CU-103,1105.00,2026-12-24,0,current INV-4070,CU-104,8900.00,2026-08-31,91,over-90 INV-4104,CU-104,3480.00,2026-11-26,4,1-30 INV-4091,CU-105,5625.00,2026-10-10,51,31-60 INV-4112,CU-105,2300.00,2026-11-27,3,1-30 INV-4099,CU-106,412.80,2026-10-15,46,31-60 INV-4110,CU-106,388.20,2026-11-05,25,1-30 INV-4122,CU-106,405.00,2026-12-03,0,current INV-4083,CU-107,-100.00,2026-09-10,0,credit INV-4115,CU-107,1990.00,2026-12-05,0,current INV-4097,CU-108,1675.40,2026-10-28,33,31-60 INV-4118,CU-108,890.00,2026-12-12,0,current CN-0031,CU-109,-310.00,2027-01-01,0,credit INV-4086,CU-109,3310.00,2026-10-14,47,31-60 INV-4113,CU-109,2480.00,2026-12-29,0,current INV-4061,CU-110,3720.00,2026-07-25,128,over-90 INV-4079,CU-110,2105.00,2026-09-01,90,61-90 INV-4103,CU-110,1860.00,2026-11-08,22,1-30 INV-4125,CU-110,1640.00,2026-12-25,0,current INV-4107,CU-111,745.00,2026-11-15,15,1-30 INV-4121,CU-111,745.00,2026-12-17,0,current INV-4111,CU-112,268.90,2026-11-09,21,1-30 INV-4116,CU-112,301.15,2026-11-23,7,1-30 INV-4123,CU-112,289.40,2026-12-07,0,current INV-4105,CU-113,722.00,2026-11-13,17,1-30 INV-4126,CU-113,1388.00,2026-12-26,0,current INV-4094,CU-114,2890.00,2026-10-01,60,31-60 INV-4100,CU-114,1140.00,2026-10-31,30,1-30 INV-4119,CU-114,960.00,2026-11-30,0,current
output/aging_summary.md · written by the agent, 57 lines
# Aging summary as of 2026-11-30 Marrowfield Supply Co. Invoices counted: 35 (duplicate INV-4097 counted once; zero-balance rows INV-4092 and INV-4095 left out). ## Total owed Total owed (all balances, credits included): 66966.60 ## By bucket - credit: -410.00 - current: 17127.40 - 1-30: 18411.00 - 31-60: 13913.20 - 61-90: 5305.00 - over-90: 12620.00 ## By customer - CU-101 Brannock Dental Group: 4100.00 - CU-102 Tiverton School Trust: 10325.00 - CU-103 Ashgrove Clinic: 2320.75 - CU-104 Lindqvist Motors: 12380.00 - CU-105 Wexcombe Hotel: 7925.00 - CU-106 Sorrel Bakery: 1206.00 - CU-107 Fenmoor Garden Centre: 1890.00 - CU-108 Castlereach Vets: 2565.40 - CU-109 Dovecote Nursery School: 5480.00 - CU-110 Greywell Brewery: 9325.00 - CU-111 Thornbury Gym: 1490.00 - CU-112 Halvorsen Farm Shop: 859.45 - CU-113 Pell Street Pharmacy: 2110.00 - CU-114 Quillfeather Books: 4990.00 ## Disputed invoices (aged, not chased) - INV-4091 (CU-105 Wexcombe Hotel): balance 5625.00, due 2026-10-10, 51 days late, bucket 31-60 - INV-4107 (CU-111 Thornbury Gym): balance 745.00, due 2026-11-15, 15 days late, bucket 1-30 ## Letters written - CU-101 Brannock Dental Group: friendly (total overdue 1840.00) - CU-102 Tiverton School Trust: final (total overdue 7350.00) - CU-103 Ashgrove Clinic: friendly (total overdue 1215.75) - CU-104 Lindqvist Motors: hold (total overdue 12380.00) - CU-105 Wexcombe Hotel: friendly (total overdue 2300.00) - CU-106 Sorrel Bakery: firm (total overdue 801.00) - CU-108 Castlereach Vets: firm (total overdue 1675.40) - CU-109 Dovecote Nursery School: firm (total overdue 3310.00) - CU-110 Greywell Brewery: hold (total overdue 7685.00) - CU-112 Halvorsen Farm Shop: friendly (total overdue 570.05) - CU-113 Pell Street Pharmacy: friendly (total overdue 722.00) - CU-114 Quillfeather Books: firm (total overdue 4030.00) ## Letters with no email on file - CU-106 Sorrel Bakery (no contact name either; letter addressed to Accounts Payable)
output/letters/CU-101.md · written by the agent, 17 lines
Level: friendly To: Helena Marsh, Brannock Dental Group Date: 2026-11-30 Dear Helena Marsh, We are writing about the invoice(s) below, which appear to have been overlooked and are now past their due date. If payment has already been sent, please accept our thanks and ignore this reminder; otherwise we would be grateful if you could arrange payment. - INV-4101: due 2026-11-04, 26 days late, balance 1840.00 Total overdue: 1840.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-102.md · written by the agent, 18 lines
Level: final To: Samir Qureshi, Tiverton School Trust Date: 2026-11-30 Dear Samir Qureshi, This is the final notice for the overdue invoice(s) below. If payment is not received within 7 days of the date of this letter, your account will be put on hold. - INV-4088: due 2026-09-19, 72 days late, balance 3200.00 - INV-4102: due 2026-11-07, 23 days late, balance 4150.00 Total overdue: 7350.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-103.md · written by the agent, 17 lines
Level: friendly To: Nadia Ferrant, Ashgrove Clinic Date: 2026-11-30 Dear Nadia Ferrant, We are writing about the invoice(s) below, which appear to have been overlooked and are now past their due date. If payment has already been sent, please accept our thanks and ignore this reminder; otherwise we would be grateful if you could arrange payment. - INV-4109: due 2026-11-19, 11 days late, balance 1215.75 Total overdue: 1215.75 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-104.md · written by the agent, 18 lines
Level: hold To: Oskar Lindqvist, Lindqvist Motors Date: 2026-11-30 Dear Oskar Lindqvist, The invoice(s) below are seriously overdue. Your account is on hold now and will stay on hold until the overdue amount is paid. - INV-4070: due 2026-08-31, 91 days late, balance 8900.00 - INV-4104: due 2026-11-26, 4 days late, balance 3480.00 Total overdue: 12380.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-105.md · written by the agent, 17 lines
Level: friendly To: Gemma Hale, Wexcombe Hotel Date: 2026-11-30 Dear Gemma Hale, We are writing about the invoice(s) below, which appear to have been overlooked and are now past their due date. If payment has already been sent, please accept our thanks and ignore this reminder; otherwise we would be grateful if you could arrange payment. - INV-4112: due 2026-11-27, 3 days late, balance 2300.00 Total overdue: 2300.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-106.md · written by the agent, 18 lines
Level: firm To: Accounts Payable, Sorrel Bakery Date: 2026-11-30 Dear Accounts Payable, The invoice(s) below are now significantly overdue. Please arrange payment within 7 days of the date of this letter. - INV-4099: due 2026-10-15, 46 days late, balance 412.80 - INV-4110: due 2026-11-05, 25 days late, balance 388.20 Total overdue: 801.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-108.md · written by the agent, 17 lines
Level: firm To: Tom Iveson, Castlereach Vets Date: 2026-11-30 Dear Tom Iveson, The invoice(s) below are now significantly overdue. Please arrange payment within 7 days of the date of this letter. - INV-4097: due 2026-10-28, 33 days late, balance 1675.40 Total overdue: 1675.40 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-109.md · written by the agent, 17 lines
Level: firm To: Aisha Bello, Dovecote Nursery School Date: 2026-11-30 Dear Aisha Bello, The invoice(s) below are now significantly overdue. Please arrange payment within 7 days of the date of this letter. - INV-4086: due 2026-10-14, 47 days late, balance 3310.00 Total overdue: 3310.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-110.md · written by the agent, 19 lines
Level: hold To: Marek Nowak, Greywell Brewery Date: 2026-11-30 Dear Marek Nowak, The invoice(s) below are seriously overdue. Your account is on hold now and will stay on hold until the overdue amount is paid. - INV-4061: due 2026-07-25, 128 days late, balance 3720.00 - INV-4079: due 2026-09-01, 90 days late, balance 2105.00 - INV-4103: due 2026-11-08, 22 days late, balance 1860.00 Total overdue: 7685.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-112.md · written by the agent, 18 lines
Level: friendly To: Ingrid Halvorsen, Halvorsen Farm Shop Date: 2026-11-30 Dear Ingrid Halvorsen, We are writing about the invoice(s) below, which appear to have been overlooked and are now past their due date. If payment has already been sent, please accept our thanks and ignore this reminder; otherwise we would be grateful if you could arrange payment. - INV-4111: due 2026-11-09, 21 days late, balance 268.90 - INV-4116: due 2026-11-23, 7 days late, balance 301.15 Total overdue: 570.05 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-113.md · written by the agent, 17 lines
Level: friendly To: Yusuf Demir, Pell Street Pharmacy Date: 2026-11-30 Dear Yusuf Demir, We are writing about the invoice(s) below, which appear to have been overlooked and are now past their due date. If payment has already been sent, please accept our thanks and ignore this reminder; otherwise we would be grateful if you could arrange payment. - INV-4105: due 2026-11-13, 17 days late, balance 722.00 Total overdue: 722.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
output/letters/CU-114.md · written by the agent, 18 lines
Level: firm To: Lottie Graves, Quillfeather Books Date: 2026-11-30 Dear Lottie Graves, The invoice(s) below are now significantly overdue. Please arrange payment within 7 days of the date of this letter. - INV-4094: due 2026-10-01, 60 days late, balance 2890.00 - INV-4100: due 2026-10-31, 30 days late, balance 1140.00 Total overdue: 4030.00 If you have any questions about payment, please contact receivables@marrowfield.example. Accounts Receivable Marrowfield Supply Co
check.py · the check, written before the run
"""Ages every invoice from the input files, works out who is owed a letter, and compares with what the agent wrote."""
import csv, re, sys
from collections import defaultdict
from datetime import date, timedelta
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
asof = date.fromisoformat(re.search(r"As of date:\s*(\d{4}-\d{2}-\d{2})", (root/"input/as_of.md").read_text()).group(1))
cust = {r["customer_id"]: r for r in csv.DictReader((root/"input/customers.csv").open())}
want = {}
for r in csv.DictReader((root/"input/open_invoices.csv").open()):
if r["invoice_id"] in want: continue
bal = round(float(r["amount"]) - float(r["paid"] or 0), 2)
if bal == 0: continue
due = date.fromisoformat(r["due_date"]) if r["due_date"].strip() else \
date.fromisoformat(r["invoice_date"]) + timedelta(days=int(cust[r["customer_id"]]["terms_days"]))
late = max((asof - due).days, 0)
if bal < 0: late, bucket = 0, "credit"
elif late == 0: bucket = "current"
elif late <= 30: bucket = "1-30"
elif late <= 60: bucket = "31-60"
elif late <= 90: bucket = "61-90"
else: bucket = "over-90"
want[r["invoice_id"]] = {"cust": r["customer_id"], "bal": bal, "late": late, "bucket": bucket, "due": due.isoformat(), "row": r,
"chase": bal > 0 and late > 0 and r["status"].strip() != "disputed"}
LEVEL = {"1-30": "friendly", "31-60": "firm", "61-90": "final", "over-90": "hold"}
chase = defaultdict(list)
for k, v in want.items():
if v["chase"]: chase[v["cust"]].append(k)
level = {c: LEVEL[max((want[k] for k in ids), key=lambda v: v["late"])["bucket"]] for c, ids in chase.items()}
path = root/"output/aging.csv"
if not path.exists():
say(False, "output/aging.csv was not written"); sys.exit(1)
rows = list(csv.DictReader(path.open()))
got = {(r.get("invoice_id") or "").strip(): r for r in rows}
n = len(want)
say(set(got) == set(want) and len(rows) == n, f"{len(set(got) & set(want))} of {n} invoices with a balance appear once in aging.csv, with paid and repeated rows left out")
def same(k, v):
g = got.get(k)
try: return (bool(g) and money(g["balance"]) == v["bal"] and int(float(g["days_late"])) == v["late"] and g["bucket"].strip() == v["bucket"]
and g["customer_id"].strip() == v["cust"] and g["due_date"].strip() == v["due"])
except (KeyError, ValueError, TypeError): return False
right = sum(1 for k, v in want.items() if same(k, v))
say(right == n, f"{right} of {n} rows carry the customer, balance, due date, days late and bucket recomputed from the input files")
md = (root/"output/aging_summary.md").read_text() if (root/"output/aging_summary.md").exists() else ""
nums = {abs(money(x)) for x in re.findall(r"\d[\d,]*\.\d{2}", md)}
buckets = defaultdict(float)
for v in want.values(): buckets[v["bucket"]] += v["bal"]
hit = sum(1 for b, t in buckets.items() if any(b in ln and dec(round(t, 2)) in figs(ln) for ln in md.splitlines()))
total = round(sum(v["bal"] for v in want.values()), 2)
say(hit == len(buckets) and total in nums, f"aging_summary.md states {hit} of {len(buckets)} bucket totals beside their bucket and the total owed, {total:,.2f}")
ldir = root/"output/letters"
letters = {p.stem: p.read_text() for p in ldir.glob("*.md")} if ldir.exists() else {}
say(set(letters) == set(chase), f"{len(set(letters) & set(chase))} of {len(chase)} customers with a late invoice have a letter and {len(set(letters) - set(chase))} letters went to someone who should not get one")
def first(text): return next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
def to_line(c): return "To: " + (cust[c]["contact_name"].strip() or "Accounts Payable") + ", " + cust[c]["name"].strip()
def opens(c):
top = [ln.strip() for ln in letters.get(c, "").splitlines()[:2]] + ["", ""]
return bool(re.fullmatch(r"Level:\s*" + level[c], top[0])) and top[1] == to_line(c) and asof.isoformat() in letters[c]
lv = sum(1 for c in chase if opens(c))
say(lv == len(chase), f"{lv} of {len(chase)} letters carry the level set by the oldest late invoice, the contact on file and the as of date")
def listed(c, k): # one line with the invoice, its due date, days late and balance
return any(k in ln and want[k]["due"] in ln and {dec(want[k]["late"]), dec(want[k]["bal"])} <= set(figs(ln)) for ln in letters.get(c, "").splitlines())
named = sum(1 for c, ids in chase.items() for k in ids if listed(c, k))
stray = sum(1 for c, text in letters.items() for k in set(re.findall(r"\b(?:INV|CN)-\d+", text)) if k not in chase.get(c, []))
late_n = sum(len(v) for v in chase.values())
say(named == late_n and stray == 0, f"{named} of {late_n} late invoices are listed in the right letter with due date, days late and balance and {stray} invoices that are current, disputed, paid or credits are listed")
def tot(text):
m = re.search(r"Total overdue:\D{0,6}([\d,]+\.\d{2})", text)
return money(m.group(1)) if m else None
tt = sum(1 for c, ids in chase.items() if tot(letters.get(c, "")) == round(sum(want[k]["bal"] for k in ids), 2))
say(tt == len(chase), f"{tt} of {len(chase)} letters state a total overdue equal to the sum of their late balances")
# the summary: one line per customer, the disputed invoices and the letters with their levels
owed = defaultdict(float)
for v in want.values(): owed[v["cust"]] += v["bal"]
overdue = {c: round(sum(want[k]["bal"] for k in ids), 2) for c, ids in chase.items()}
lines_md = md.splitlines()
c_ok = sum(1 for c, t in owed.items() if any(c in ln and dec(round(t, 2)) in figs(ln) for ln in lines_md))
disputed = [k for k, v in want.items() if v["row"]["status"].strip() == "disputed"]
d_ok = sum(1 for k in disputed if any(k in ln for ln in lines_md))
l_ok = sum(1 for c in chase if any(c in ln and re.search(r"\b" + level[c] + r"\b", ln) for ln in lines_md))
say(c_ok == len(owed) and d_ok == len(disputed) and l_ok == len(chase),
f"aging_summary.md gives {c_ok} of {len(owed)} customer totals beside their customer, names {d_ok} of {len(disputed)} disputed invoices and gives {l_ok} of {len(chase)} letter levels")
# every figure and date written beside an invoice or a customer must belong to it
rec = {}
for k, v in want.items():
r = v["row"]
rec[k] = {dec(v["bal"]), dec(v["late"]), v["due"], r["invoice_date"], dec(r["amount"]), dec(r["paid"] or 0)}
for c in cust:
mine = [v for v in want.values() if v["cust"] == c]
rec[c] = {dec(round(owed.get(c, 0), 2)), dec(overdue.get(c, 0)), dec(cust[c]["terms_days"]), dec(len(mine)), dec(len(chase.get(c, [])))}
facts = {asof.isoformat(), dec(total), dec(n), dec(len(owed)), dec(len(chase)), dec(len(disputed)), dec(late_n)} | {dec(round(t, 2)) for t in buckets.values()}
ID = r"(?:INV|CN|CU)-\d+"
seen, bad = writeup(md, ID, rec, facts)
seen2 = bad2 = 0
for c, text in letters.items():
s2, b2 = writeup(text, ID, rec, {asof.isoformat(), dec(overdue.get(c, 0))})
seen2 += s2; bad2 += len(b2)
say(seen > 0 and not bad and bad2 == 0, f"{seen - len(bad)} of {seen} figures and dates in aging_summary.md and {seen2 - bad2} of {seen2} in the letters equal a figure of the invoice or customer they sit beside or a recomputed total")
sys.exit(0 if ok else 1)
as_of.md: sample data written by Atris. Fingerprint e3445a7e8812.
customers.csv: sample data written by Atris. Fingerprint f947280ba479.
open_invoices.csv: sample data written by Atris. Fingerprint 6d127f88dc5a.
aging.csv: written by the agent. Fingerprint 9896de3fe505.
aging_summary.md: written by the agent. Fingerprint 71e4524b07de.
CU-101.md: written by the agent. Fingerprint c1a82aa05541.
CU-102.md: written by the agent. Fingerprint f89bd5c78648.
CU-103.md: written by the agent. Fingerprint 6d1bb533b8aa.
CU-104.md: written by the agent. Fingerprint 4e4d64bf2581.
CU-105.md: written by the agent. Fingerprint 7952975aebcb.
CU-106.md: written by the agent. Fingerprint ae18c7313266.
CU-108.md: written by the agent. Fingerprint 87c5de4ce7e6.
CU-109.md: written by the agent. Fingerprint ed720badb8a7.
CU-110.md: written by the agent. Fingerprint 43e71ae2c2a3.
CU-112.md: written by the agent. Fingerprint fbc4b3692e64.
CU-113.md: written by the agent. Fingerprint fadb43dd3a59.
CU-114.md: written by the agent. Fingerprint d22d871166c7.