CS 101 — Programming Foundations with Python — Integrated project

Optional integrated project

Build an importable and command-line estimator for a fictional service company. Accept event IDs, customer IDs and integer-cent transactions from CSV. Specify duplicate, refund and invoice-rounding policies. Produce customer and overall reconciliations plus a run manifest. A failed export must preserve the last valid report.

  1. A hand-calculated ledger with distinct duplicate-value events, an identical retry and a conflicting-ID rejection.
  2. Explicit cents, type, missingness, refund and rounding contracts.
  3. Pure computation functions separated from input, output and terminal execution.
  4. CSV quoting, invalid row and late-file failure tests with preserved previous output.
  5. Normal, boundary and adversarial test cases with independently calculated expected results.
  6. A reproducible invocation, input checksum and documented operational limits.
Worked approach and limits

Use four accepted events: +500 for Ada, +500 for Ada under a distinct ID, −500 reversing the first event, and +700 replacing it. Ada reconciles to 1200 cents before any separately specified discount. An identical retry changes no total; a reused ID with changed payload is rejected. Validate representation at the parser boundary, then pass typed records to a pure accumulator. Stage output separately and replace the destination after success. Verify that importing the module creates no files. Demonstrate the failure path with an invalid last row and compare yesterday’s output byte for byte. The project establishes calculation and export behavior; it does not implement payment settlement or guarantee filesystem durability after hardware failure.

Runnable reference implementation

The reference demonstrates the bounded mechanisms described in the course; use the project criteria to identify what a complete independent implementation still needs.

Download the runnable reference implementation
"""Original Lawfare Academy reference lab. Fictional work orders; Python 3 standard library.
Run: python python_estimator.py. Read the assertions before changing the policy.
"""
import csv
import io
from dataclasses import dataclass

@dataclass(frozen=True)
class WorkOrder:
    order_id: str
    customer: str
    minutes: int
    rate_cents_hour: int

    def cents(self):
        # Half-up rounding, one line at a time; nonnegative integers only.
        return (self.minutes * self.rate_cents_hour + 30) // 60

def parse_batch(text):
    reader = csv.DictReader(io.StringIO(text))
    expected = ['id', 'customer', 'minutes', 'rate_cents_hour']
    if reader.fieldnames != expected:
        raise ValueError('Wrong columns or order')
    accepted, rejected, seen = [], [], set()
    for line, row in enumerate(reader, 2):
        try:
            if None in row or any(v is None for v in row.values()):
                raise ValueError('Column count mismatch')
            oid, customer = row['id'].strip(), row['customer'].strip()
            if not oid or not customer or oid in seen:
                raise ValueError('Missing identity or duplicate order id')
            minutes, rate = int(row['minutes']), int(row['rate_cents_hour'])
            if minutes < 0 or rate < 0:
                raise ValueError('Negative quantity')
            accepted.append(WorkOrder(oid, customer, minutes, rate))
            seen.add(oid)
        except (ValueError, TypeError) as error:
            rejected.append({'line': line, 'reason': str(error)})
    return accepted, rejected

def allocate(cents, count):
    if type(cents) is not int or type(count) is not int or cents < 0 or count <= 0:
        raise ValueError('Nonnegative integer cents and positive integer count required')
    share, remainder = divmod(cents, count)
    return [share + (i < remainder) for i in range(count)]

def report(orders):
    result = {}
    for order in orders:
        record = result.setdefault(order.customer, {'orders': 0, 'cents': 0})
        record['orders'] += 1
        record['cents'] += order.cents()
    return result

def main():
    fixture = 'id,customer,minutes,rate_cents_hour\nA,Ada,35,6250\nB,Ada,60,6250\nC,Ben,0,5000\nD,Ben,-1,5000\nA,Ada,60,6250\n'
    orders, errors = parse_batch(fixture)
    assert len(orders) == 3 and len(errors) == 2
    assert report(orders) == {'Ada': {'orders': 2, 'cents': 9896}, 'Ben': {'orders': 1, 'cents': 0}}
    assert len(orders) + len(errors) == 5
    assert allocate(1000, 3) == [334, 333, 333]
    for amount in range(30):
        for count in range(1, 12):
            shares = allocate(amount, count)
            assert sum(shares) == amount and max(shares) - min(shares) <= 1
    assert WorkOrder('X', 'X', 1, 30).cents() == 1
    assert report([]) == {}
    print('PASS: reconciliation, duplicates, zero, invalid input, half-up rounding and allocation invariants')
    print(report(orders), errors)

if __name__ == '__main__':
    main()