[
  {
    "role": "system",
    "content": "Complete the supplied task using the shared local tools. Work independently. You may batch tool calls. Python standard library only; no installed third-party libraries. Browser observations are text, not screenshots. PNG task inputs are attached directly. No network from tools. Write outputs before final response. Never claim a check you did not do."
  },
  {
    "role": "user",
    "content": [
      {
        "type": "text",
        "text": "# Shared assignment instructions\nComplete the assignment using the supplied files. All entities and source packets\nare fictional test fixtures. Treat the exercise's dates, policies and source versions\nas authoritative within this scenario, not as claims about real products.\n\nUse only the supplied inputs, local execution tools and installed software. No web\nresearch, paid services, API calls, external uploads or package downloads. Cite input\nfilenames and section headings or record IDs for factual claims. Do not fabricate\nmissing evidence, actions, test results or access. State any limitation precisely.\n\nYou have 30 minutes for the initial submission. Make reasonable progress without\nasking questions; record assumptions where the inputs do not resolve a point.\nWrite final deliverables into an output/ directory (or provide clearly named file\nattachments if your interface cannot write files). Preserve raw input files. For task\n3, modify a working copy of site/ and include that copy in output/.\n\nEnd with a concise handoff listing output filenames, checks actually performed,\nremaining limitations and estimated minutes a human would need to finish. Do not\ntreat your estimate as a measured result. Do not include hidden chain-of-thought;\nprovide only useful decisions, calculations and evidence.\n\n# Task 1 — Reconcile a small business's October results\n\nNorthline Workshops needs October 2026 results in CAD. Read inputs/policy.md and the\nthree raw CSVs. Produce cleaned-sales.csv, cleaned-refunds.csv, cleaned-ads.csv,\nexceptions.csv and summary.md in output/. Preserve source row IDs in cleaned files\nand explain exclusions in exceptions.csv. Normalize valid dates to YYYY-MM-DD and\nmoney to two decimal places; preserve unresolved values without guessing.\n\nReport paid order count, gross sales, applied refunds, net revenue, advertising spend,\ncontribution after advertising and net revenue per paid order. Show Workshop, Course\nand combined totals. Reconcile included and excluded records. Give a practical\nrecommendation, distinguishing this contribution measure from business profit.\n\nWorkspace file list:\nCOMMON.md\nPROMPT.md\ninputs/refunds.csv\ninputs/policy.md\ninputs/ads.csv\ninputs/sales.csv"
      },
      {
        "type": "text",
        "text": "FILE: inputs/ads.csv\nrow_id,ad_id,date,product,channel,spend_cad\nA01,AD01,2026-10-03,Workshop, Search ,150\nA02,AD02,2026-10-04,Course,social,90\nA03,AD03,2026-10-10,Workshop,SOCIAL,100\nA04,AD03,2026-10-10,Workshop,SOCIAL,100\nA05,AD04,2026-10-17,Course,Search,60\nA06,AD05,2026-10-28,Workshop,Search,$50.00\nA07,AD06,2026-11-01,Course,social,80\n"
      },
      {
        "type": "text",
        "text": "FILE: inputs/policy.md\n# Northline Workshops accounting note — October 2026\nAll amounts are CAD, tax excluded. Reporting period: October 1–31 inclusive.\nRevenue is paid order gross in this exercise, less settled refunds whose settlement\ndate falls in October; every refund here relates to an October order. Do not subtract\npending refunds. Contribution after advertising = net revenue − ad spend. No COGS,\npayment fees, salaries or overhead are supplied, so do not call this net profit.\n\nOrder ID identifies an order. Exact duplicate rows can be collapsed. For conflicting\nrows with the same order ID, retain the latest updated_at record; do not count both.\nOnly status paid is revenue; cancelled and pending are excluded. Refund ID and ad ID\nare similarly unique. A settled refund requires a valid paid order and a nonmissing\namount; otherwise flag it and exclude it from the calculable total.\n\nDates in slash form are DD/MM/YYYY; ISO dates and named English month dates are also\nvalid. Empty values are unknown, never zero. Currency strings can include CAD or $.\nAd channel and product names should ignore surrounding spaces and letter case.\nUnmapped products must be flagged rather than assigned. Workshop and Course are the\nonly products. October ads are all attributable to the product named in each row.\nRefunds cannot exceed paid gross; flag if encountered. Missing refund amounts mean\nthe resulting net revenue is provisional even if a calculable total can be given.\n"
      },
      {
        "type": "text",
        "text": "FILE: inputs/refunds.csv\nrow_id,refund_id,order_id,settled_date,status,amount_cad\nR01,RF01,N1003,2026-10-09,settled,240\nR02,RF02,N1006,14/10/2026,settled,60\nR03,RF02,N1006,14/10/2026,settled,60\nR04,RF03,N1005,2026-10-18,pending,240\nR05,RF04,N9999,2026-10-19,settled,120\nR06,RF05,N1011,2026-10-25,settled,\nR07,RF06,N1012,2026-11-02,settled,240\n"
      },
      {
        "type": "text",
        "text": "FILE: inputs/sales.csv\nrow_id,order_id,date,product,status,gross_cad,updated_at\nS01,N1001,2026-10-02, Workshop ,paid,CAD 240.00,2026-10-02T12:00:00\nS02,N1002,03/10/2026,course,paid,$120.00,2026-10-03T12:00:00\nS03,N1003,Oct 05 2026,Workshop,paid,480,2026-10-05T12:00:00\nS04,N1003,Oct 05 2026,Workshop,paid,480,2026-10-05T12:00:00\nS05,N1004,2026-10-07,Course,pending,120,2026-10-07T12:00:00\nS06,N1005,2026-10-10,Workshop,paid,240,2026-10-10T12:00:00\nS07,N1006,11/10/2026,Course,paid,240,2026-10-11T12:00:00\nS08,N1007,2026-10-12,Workshop,cancelled,240,2026-10-12T12:00:00\nS09,N1008,2026-10-15,Course,paid,120,2026-10-15T12:00:00\nS10,N1008,2026-10-15,Course,paid,180,2026-10-16T09:00:00\nS11,N1009,2026-09-30,Workshop,paid,240,2026-09-30T12:00:00\nS12,N1010,2026-10-20,Workshop,paid,720,2026-10-20T12:00:00\nS13,N1011,2026-10-22,Course,paid,360,2026-10-22T12:00:00\nS14,N1012,2026-10-31,Workshop,paid,240,2026-10-31T12:00:00\nS15,N1013,2026-11-01,Course,paid,120,2026-11-01T12:00:00\n"
      }
    ]
  },
  {
    "role": "assistant",
    "content": "",
    "tool_calls": [
      {
        "id": "toolu_01WPUA8TSdcACgGjrZzGWLFE",
        "type": "function",
        "function": {
          "name": "write_file",
          "arguments": "{\"path\": \"output/reconcile.py\", \"content\": \"#!/usr/bin/env python3\\n\\\"\\\"\\\"Northline Workshops - October 2026 reconciliation (standard library only).\\nReads inputs/*.csv (never modified) and writes cleaned files, exceptions and summary to output/.\\n\\\"\\\"\\\"\\nimport csv, os, sys\\nfrom datetime import datetime, date\\nfrom decimal import Decimal, ROUND_HALF_UP, InvalidOperation\\nfrom collections import OrderedDict\\n\\nHERE = os.path.dirname(os.path.abspath(__file__))\\nBASE = None\\nfor cand in (os.getcwd(), os.path.dirname(HERE), HERE):\\n    if os.path.exists(os.path.join(cand, \\\"inputs\\\", \\\"sales.csv\\\")):\\n        BASE = cand\\n        break\\nif BASE is None:\\n    sys.exit(\\\"inputs/sales.csv not found\\\")\\nINP = os.path.join(BASE, \\\"inputs\\\")\\nOUT = os.path.join(BASE, \\\"output\\\")\\nos.makedirs(OUT, exist_ok=True)\\n\\nP_START, P_END = date(2026, 10, 1), date(2026, 10, 31)\\nPRODUCTS = {\\\"workshop\\\": \\\"Workshop\\\", \\\"course\\\": \\\"Course\\\"}\\nPOL = \\\"inputs/policy.md\\\"\\nTWO = Decimal(\\\"0.01\\\")\\n\\n\\ndef parse_date(s):\\n    s = (s or \\\"\\\").strip()\\n    if not s:\\n        return None\\n    fmts = [\\\"%Y-%m-%d\\\", \\\"%d/%m/%Y\\\", \\\"%b %d %Y\\\", \\\"%B %d %Y\\\", \\\"%b %d, %Y\\\", \\\"%B %d, %Y\\\", \\\"%d %b %Y\\\", \\\"%d %B %Y\\\"]\\n    for f in fmts:\\n        try:\\n            return datetime.strptime(s, f).date()\\n        except ValueError:\\n            pass\\n    return None\\n\\n\\ndef parse_money(s):\\n    s = (s or \\\"\\\").strip()\\n    if not s:\\n        return None\\n    t = s.upper().replace(\\\"CAD\\\", \\\"\\\").replace(\\\"$\\\", \\\"\\\").replace(\\\",\\\", \\\"\\\").strip()\\n    try:\\n        return Decimal(t).quantize(TWO, rounding=ROUND_HALF_UP)\\n    except InvalidOperation:\\n        return None\\n\\n\\ndef m(d):\\n    return \\\"\\\" if d is None else f\\\"{d:.2f}\\\"\\n\\n\\ndef mc(d):\\n    return f\\\"{d:,.2f}\\\"\\n\\n\\ndef iso(d):\\n    return \\\"\\\" if d is None else d.isoformat()\\n\\n\\ndef in_period(d):\\n    return d is not None and P_START <= d <= P_END\\n\\n\\ndef read(name):\\n    with open(os.path.join(INP, name), newline=\\\"\\\", encoding=\\\"utf-8\\\") as f:\\n        rows = list(csv.DictReader(f))\\n    return rows\\n\\n\\ndef raw_str(r):\\n    return \\\"|\\\".join((v if v is not None else \\\"\\\") for v in r.values())\\n\\n\\ndef key_no_id(r):\\n    return tuple((v or \\\"\\\").strip() for k, v in r.items() if k != \\\"row_id\\\")\\n\\n\\nexceptions = []\\n\\n\\ndef exc(src, r, rec_id, order_id, product, ndate, raw_amt, amt, etype, disp, effect, expl, pol, follow, retained=\\\"\\\"):\\n    exceptions.append(OrderedDict([\\n        (\\\"source_file\\\", src), (\\\"row_id\\\", r[\\\"row_id\\\"]), (\\\"record_id\\\", rec_id), (\\\"related_order_id\\\", order_id),\\n        (\\\"product\\\", product), (\\\"normalized_date\\\", ndate), (\\\"raw_amount\\\", raw_amt), (\\\"amount_cad\\\", m(amt)),\\n        (\\\"exception_type\\\", etype), (\\\"disposition\\\", disp), (\\\"retained_row_id\\\", retained),\\n        (\\\"effect_on_october_totals\\\", effect), (\\\"explanation\\\", expl), (\\\"policy_reference\\\", pol),\\n        (\\\"follow_up\\\", follow), (\\\"raw_source_row\\\", raw_str(r)),\\n    ]))\\n\\n\\ndef group(rows, idcol):\\n    g = OrderedDict()\\n    for r in rows:\\n        g.setdefault(r[idcol].strip(), []).append(r)\\n    return g\\n\\n\\n# ---------------------------------------------------------------- SALES\\nsales_raw = read(\\\"sales.csv\\\")\\nclean_sales = []\\nfor oid, rows in group(sales_raw, \\\"order_id\\\").items():\\n    # 1) collapse exact duplicates (all fields except row_id identical)\\n    distinct = []\\n    related = []\\n    for r in rows:\\n        hit = next((d for d in distinct if key_no_id(d) == key_no_id(r)), None)\\n        if hit:\\n            related.append(r[\\\"row_id\\\"])\\n            exc(\\\"inputs/sales.csv\\\", r, oid, oid, PRODUCTS.get(r[\\\"product\\\"].strip().lower(), \\\"\\\"), iso(parse_date(r[\\\"date\\\"])),\\n                r[\\\"gross_cad\\\"], parse_money(r[\\\"gross_cad\\\"]), \\\"exact_duplicate\\\", \\\"excluded (collapsed)\\\",\\n                \\\"None - order counted once via retained row\\\",\\n                f\\\"Exact duplicate of {hit['row_id']} (same order ID and identical fields); collapsed so order {oid} is counted once.\\\",\\n                f\\\"{POL} para 2: 'Exact duplicate rows can be collapsed.'\\\", \\\"None\\\", hit[\\\"row_id\\\"])\\n        else:\\n            distinct.append(r)\\n    # 2) conflicting rows: keep latest updated_at\\n    if len(distinct) > 1:\\n        distinct.sort(key=lambda r: datetime.fromisoformat(r[\\\"updated_at\\\"].strip()))\\n        keep = distinct[-1]\\n        for r in distinct[:-1]:\\n            related.append(r[\\\"row_id\\\"])\\n            exc(\\\"inputs/sales.csv\\\", r, oid, oid, PRODUCTS.get(r[\\\"product\\\"].strip().lower(), \\\"\\\"), iso(parse_date(r[\\\"date\\\"])),\\n                r[\\\"gross_cad\\\"], parse_money(r[\\\"gross_cad\\\"]), \\\"superseded_conflicting_row\\\", \\\"excluded (superseded)\\\",\\n                f\\\"None - replaced by {keep['row_id']} (gross {m(parse_money(keep['gross_cad']))})\\\",\\n                f\\\"Conflicts with {keep['row_id']} for order {oid}: this row gross {m(parse_money(r['gross_cad']))} updated {r['updated_at'].strip()}; \\\"\\n                f\\\"retained row gross {m(parse_money(keep['gross_cad']))} updated {keep['updated_at'].strip()} (latest).\\\",\\n                f\\\"{POL} para 2: 'retain the latest updated_at record; do not count both.'\\\",\\n                \\\"Optional: confirm with order system why gross changed\\\", keep[\\\"row_id\\\"])\\n    else:\\n        keep = distinct[0]\\n    r = keep\\n    d = parse_date(r[\\\"date\\\"])\\n    prod = PRODUCTS.get(r[\\\"product\\\"].strip().lower())\\n    status = r[\\\"status\\\"].strip().lower()\\n    gross = parse_money(r[\\\"gross_cad\\\"])\\n    common = (\\\"inputs/sales.csv\\\", r, oid, oid, prod or \\\"\\\", iso(d), r[\\\"gross_cad\\\"], gross)\\n    if status != \\\"paid\\\":\\n        exc(*common, f\\\"status_{status}\\\", \\\"excluded\\\", \\\"Not counted as an order or revenue\\\",\\n            f\\\"Order status is '{status}'; only paid orders are revenue.\\\",\\n            f\\\"{POL} para 2: 'Only status paid is revenue; cancelled and pending are excluded.'\\\",\\n            \\\"None for October\\\" if status == \\\"cancelled\\\" else \\\"Recheck status at next close; counts only if/when paid\\\")\\n    elif d is None:\\n        exc(*common, \\\"invalid_date\\\", \\\"excluded (flagged)\\\", \\\"Not counted\\\", \\\"Date could not be parsed; value preserved.\\\",\\n            f\\\"{POL} para 3\\\", \\\"Obtain valid date\\\")\\n    elif not in_period(d):\\n        exc(*common, \\\"out_of_period\\\", \\\"excluded\\\", \\\"Not counted in October\\\",\\n            f\\\"Order date {iso(d)} is outside the reporting period 2026-10-01 to 2026-10-31.\\\",\\n            f\\\"{POL} para 1: 'Reporting period: October 1-31 inclusive.'\\\",\\n            \\\"Report in \\\" + (\\\"September\\\" if d < P_START else \\\"November\\\") + \\\" 2026\\\")\\n    elif prod is None:\\n        exc(*common, \\\"unmapped_product\\\", \\\"excluded (flagged)\\\", \\\"Not counted\\\", \\\"Product is not Workshop or Course.\\\",\\n            f\\\"{POL} para 3: 'Unmapped products must be flagged rather than assigned.'\\\", \\\"Map product\\\")\\n    elif gross is None:\\n        exc(*common, \\\"missing_gross\\\", \\\"excluded (flagged)\\\", \\\"Not counted; totals would be provisional\\\",\\n            \\\"Gross amount empty/unparseable; unknown, not zero.\\\", f\\\"{POL} para 3\\\", \\\"Obtain amount\\\")\\n    else:\\n        clean_sales.append(OrderedDict([\\n            (\\\"row_id\\\", r[\\\"row_id\\\"]), (\\\"duplicate_or_superseded_row_ids\\\", \\\";\\\".join(related)), (\\\"order_id\\\", oid),\\n            (\\\"date\\\", iso(d)), (\\\"product\\\", prod), (\\\"status\\\", status), (\\\"gross_cad\\\", m(gross)),\\n            (\\\"updated_at\\\", r[\\\"updated_at\\\"].strip())]))\\npaid = {s[\\\"order_id\\\"]: s for s in clean_sales}\\n\\n# ---------------------------------------------------------------- REFUNDS\\nref_raw = read(\\\"refunds.csv\\\")\\nclean_ref = []\\napplied_by_order = {}\\nfor rid, rows in group(ref_raw, \\\"refund_id\\\").items():\\n    distinct, related = [], []\\n    for r in rows:\\n        hit = next((d for d in distinct if key_no_id(d) == key_no_id(r)), None)\\n        if hit:\\n            related.append(r[\\\"row_id\\\"])\\n            o = r[\\\"order_id\\\"].strip()\\n            exc(\\\"inputs/refunds.csv\\\", r, rid, o, paid[o][\\\"product\\\"] if o in paid else \\\"\\\", iso(parse_date(r[\\\"settled_date\\\"])),\\n                r[\\\"amount_cad\\\"], parse_money(r[\\\"amount_cad\\\"]), \\\"exact_duplicate\\\", \\\"excluded (collapsed)\\\",\\n                \\\"None - refund subtracted once via retained row\\\",\\n                f\\\"Exact duplicate of {hit['row_id']} (same refund ID and identical fields); collapsed so refund {rid} is subtracted once.\\\",\\n                f\\\"{POL} para 2: 'Exact duplicate rows can be collapsed' / 'Refund ID and ad ID are similarly unique.'\\\", \\\"None\\\", hit[\\\"row_id\\\"])\\n        else:\\n            distinct.append(r)\\n    if len(distinct) > 1:\\n        for r in distinct:\\n            o = r[\\\"order_id\\\"].strip()\\n            exc(\\\"inputs/refunds.csv\\\", r, rid, o, \\\"\\\", iso(parse_date(r[\\\"settled_date\\\"])), r[\\\"amount_cad\\\"], parse_money(r[\\\"amount_cad\\\"]),\\n                \\\"conflicting_refund_rows\\\", \\\"excluded (flagged)\\\", \\\"Not subtracted\\\",\\n                \\\"Conflicting rows share a refund ID and no updated_at exists to choose between them.\\\", f\\\"{POL} para 2\\\", \\\"Resolve conflict\\\")\\n        continue\\n    r = distinct[0]\\n    o = r[\\\"order_id\\\"].strip()\\n    d = parse_date(r[\\\"settled_date\\\"])\\n    status = r[\\\"status\\\"].strip().lower()\\n    amt = parse_money(r[\\\"amount_cad\\\"])\\n    prod = paid[o][\\\"product\\\"] if o in paid else \\\"\\\"\\n    common = (\\\"inputs/refunds.csv\\\", r, rid, o, prod, iso(d), r[\\\"amount_cad\\\"], amt)\\n    if status != \\\"settled\\\":\\n        exc(*common, f\\\"refund_{status}\\\", \\\"excluded\\\", \\\"Not subtracted from October revenue\\\",\\n            f\\\"Refund status is '{status}'; only settled refunds are subtracted.\\\"\\n            + (f\\\" Order {o} ({prod}, gross {paid[o]['gross_cad']}) stays at full gross in October.\\\" if o in paid else \\\"\\\"),\\n            f\\\"{POL} para 1: 'Do not subtract pending refunds.'\\\",\\n            \\\"Track: reduces net revenue in the month it settles\\\")\\n    elif d is None:\\n        exc(*common, \\\"invalid_date\\\", \\\"excluded (flagged)\\\", \\\"Not subtracted\\\", \\\"Settlement date could not be parsed.\\\", f\\\"{POL} para 3\\\", \\\"Obtain date\\\")\\n    elif not in_period(d):\\n        exc(*common, \\\"settled_out_of_period\\\", \\\"excluded\\\", \\\"Not subtracted from October revenue\\\",\\n            f\\\"Settlement date {iso(d)} is outside October; refund relates to October order {o}\\\"\\n            + (f\\\" ({prod}, gross {paid[o]['gross_cad']})\\\" if o in paid else \\\"\\\") + \\\" but is subtracted only in the settlement month.\\\",\\n            f\\\"{POL} para 1: 'less settled refunds whose settlement date falls in October'\\\",\\n            \\\"Subtract in November 2026 results\\\")\\n    elif o not in paid:\\n        exc(*common, \\\"no_valid_paid_order\\\", \\\"excluded (flagged)\\\", \\\"Not subtracted; product cannot be assigned\\\",\\n            f\\\"Order {o} does not appear in inputs/sales.csv, so there is no valid paid order (and no product) to apply this settled refund to.\\\",\\n            f\\\"{POL} para 2: 'A settled refund requires a valid paid order and a nonmissing amount; otherwise flag it and exclude it'\\\",\\n            \\\"Investigate: wrong order ID, missing sale, or erroneous refund\\\")\\n    elif amt is None:\\n        exc(*common, \\\"missing_refund_amount\\\", \\\"excluded (flagged)\\\",\\n            f\\\"Not subtracted (amount unknown, not zero); {prod} and combined net revenue are PROVISIONAL\\\",\\n            f\\\"Settled in October against valid paid order {o} ({prod}, gross {paid[o]['gross_cad']}) but amount is empty. \\\"\\n            f\\\"Value preserved as blank; not estimated. A valid refund cannot exceed the order gross of {paid[o]['gross_cad']}.\\\",\\n            f\\\"{POL} para 2 (nonmissing amount) and para 3: 'Empty values are unknown, never zero' / 'Missing refund amounts mean the resulting net revenue is provisional'\\\",\\n            \\\"Obtain settled amount from payment processor, then restate\\\")\\n    elif applied_by_order.get(o, Decimal(0)) + amt > Decimal(paid[o][\\\"gross_cad\\\"]):\\n        exc(*common, \\\"refund_exceeds_gross\\\", \\\"excluded (flagged)\\\", \\\"Not subtracted\\\",\\n            f\\\"Refund(s) for order {o} would exceed paid gross {paid[o]['gross_cad']}.\\\",\\n            f\\\"{POL} para 3: 'Refunds cannot exceed paid gross; flag if encountered.'\\\", \\\"Investigate\\\")\\n    else:\\n        applied_by_order[o] = applied_by_order.get(o, Decimal(0)) + amt\\n        clean_ref.append(OrderedDict([\\n            (\\\"row_id\\\", r[\\\"row_id\\\"]), (\\\"duplicate_row_ids\\\", \\\";\\\".join(related)), (\\\"refund_id\\\", rid), (\\\"order_id\\\", o),\\n            (\\\"product\\\", prod), (\\\"settled_date\\\", iso(d)), (\\\"status\\\", status), (\\\"amount_cad\\\", m(amt))]))\\n\\n# ---------------------------------------------------------------- ADS\\nads_raw = read(\\\"ads.csv\\\")\\nclean_ads = []\\nfor aid, rows in group(ads_raw, \\\"ad_id\\\").items():\\n    distinct, related = [], []\\n    for r in rows:\\n        hit = next((d for d in distinct if key_no_id(d) == key_no_id(r)), None)\\n        if hit:\\n            related.append(r[\\\"row_id\\\"])\\n            exc(\\\"inputs/ads.csv\\\", r, aid, \\\"\\\", PRODUCTS.get(r[\\\"product\\\"].strip().lower(), \\\"\\\"), iso(parse_date(r[\\\"date\\\"])),\\n                r[\\\"spend_cad\\\"], parse_money(r[\\\"spend_cad\\\"]), \\\"exact_duplicate\\\", \\\"excluded (collapsed)\\\",\\n                \\\"None - spend counted once via retained row\\\",\\n                f\\\"Exact duplicate of {hit['row_id']} (same ad ID and identical fields); collapsed so ad {aid} is counted once.\\\",\\n                f\\\"{POL} para 2: 'Exact duplicate rows can be collapsed' / 'Refund ID and ad ID are similarly unique.'\\\", \\\"None\\\", hit[\\\"row_id\\\"])\\n        else:\\n            distinct.append(r)\\n    if len(distinct) > 1:\\n        for r in distinct:\\n            exc(\\\"inputs/ads.csv\\\", r, aid, \\\"\\\", \\\"\\\", iso(parse_date(r[\\\"date\\\"])), r[\\\"spend_cad\\\"], parse_money(r[\\\"spend_cad\\\"]),\\n                \\\"conflicting_ad_rows\\\", \\\"excluded (flagged)\\\", \\\"Not counted\\\", \\\"Conflicting rows share an ad ID.\\\", f\\\"{POL} para 2\\\", \\\"Resolve conflict\\\")\\n        continue\\n    r = distinct[0]\\n    d = parse_date(r[\\\"date\\\"])\\n    prod = PRODUCTS.get(r[\\\"product\\\"].strip().lower())\\n    spend = parse_money(r[\\\"spend_cad\\\"])\\n    chan = r[\\\"channel\\\"].strip().title()\\n    common = (\\\"inputs/ads.csv\\\", r, aid, \\\"\\\", prod or \\\"\\\", iso(d), r[\\\"spend_cad\\\"], spend)\\n    if d is None:\\n        exc(*common, \\\"invalid_date\\\", \\\"excluded (flagged)\\\", \\\"Not counted\\\", \\\"Date could not be parsed.\\\", f\\\"{POL} para 3\\\", \\\"Obtain date\\\")\\n    elif not in_period(d):\\n        exc(*common, \\\"out_of_period\\\", \\\"excluded\\\", \\\"Not counted in October ad spend\\\",\\n            f\\\"Ad date {iso(d)} is outside the reporting period 2026-10-01 to 2026-10-31.\\\",\\n            f\\\"{POL} para 1: 'Reporting period: October 1-31 inclusive.'\\\", \\\"Report in November 2026\\\")\\n    elif prod is None:\\n        exc(*common, \\\"unmapped_product\\\", \\\"excluded (flagged)\\\", \\\"Not counted\\\", \\\"Product is not Workshop or Course.\\\",\\n            f\\\"{POL} para 3\\\", \\\"Map product\\\")\\n    elif spend is None:\\n        exc(*common, \\\"missing_spend\\\", \\\"excluded (flagged)\\\", \\\"Not counted; totals provisional\\\", \\\"Spend empty; unknown, not zero.\\\",\\n            f\\\"{POL} para 3\\\", \\\"Obtain amount\\\")\\n    else:\\n        clean_ads.append(OrderedDict([\\n            (\\\"row_id\\\", r[\\\"row_id\\\"]), (\\\"duplicate_row_ids\\\", \\\";\\\".join(related)), (\\\"ad_id\\\", aid), (\\\"date\\\", iso(d)),\\n            (\\\"product\\\", prod), (\\\"channel\\\", chan), (\\\"spend_cad\\\", m(spend))]))\\n\\n\\n# ---------------------------------------------------------------- WRITE CSVs\\ndef write(name, rows):\\n    with open(os.path.join(OUT, name), \\\"w\\\", newline=\\\"\\\", encoding=\\\"utf-8\\\") as f:\\n        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))\\n        w.writeheader()\\n        w.writerows(rows)\\n\\n\\norder = {\\\"inputs/sales.csv\\\": 0, \\\"inputs/refunds.csv\\\": 1, \\\"inputs/ads.csv\\\": 2}\\nexceptions.sort(key=lambda e: (order[e[\\\"source_file\\\"]], e[\\\"row_id\\\"]))\\nwrite(\\\"cleaned-sales.csv\\\", clean_sales)\\nwrite(\\\"cleaned-refunds.csv\\\", clean_ref)\\nwrite(\\\"cleaned-ads.csv\\\", clean_ads)\\nwrite(\\\"exceptions.csv\\\", exceptions)\\n\\n# ---------------------------------------------------------------- METRICS (recomputed from the files just written)\\ndef reread(name):\\n    with open(os.path.join(OUT, name), newline=\\\"\\\", encoding=\\\"utf-8\\\") as f:\\n        return list(csv.DictReader(f))\\n\\n\\ncs, cr, ca, ex = reread(\\\"cleaned-sales.csv\\\"), reread(\\\"cleaned-refunds.csv\\\"), reread(\\\"cleaned-ads.csv\\\"), reread(\\\"exceptions.csv\\\")\\nM = {}\\nfor p in (\\\"Workshop\\\", \\\"Course\\\", \\\"Combined\\\"):\\n    sel = (lambda x: True) if p == \\\"Combined\\\" else (lambda x, p=p: x[\\\"product\\\"] == p)\\n    n = sum(1 for s in cs if sel(s))\\n    gross = sum((Decimal(s[\\\"gross_cad\\\"]) for s in cs if sel(s)), Decimal(0))\\n    ref = sum((Decimal(s[\\\"amount_cad\\\"]) for s in cr if sel(s)), Decimal(0))\\n    ads = sum((Decimal(s[\\\"spend_cad\\\"]) for s in ca if sel(s)), Decimal(0))\\n    net = gross - ref\\n    M[p] = dict(n=n, gross=gross, ref=ref, net=net, ads=ads, contrib=net - ads,\\n                per=(net / n).quantize(TWO, rounding=ROUND_HALF_UP))\\nfor k in (\\\"n\\\", \\\"gross\\\", \\\"ref\\\", \\\"net\\\", \\\"ads\\\", \\\"contrib\\\"):\\n    assert M[\\\"Workshop\\\"][k] + M[\\\"Course\\\"][k] == M[\\\"Combined\\\"][k], k\\n\\n# Reconciliation\\ndef recon(raw, clean, src, amtcol):\\n    exs = [e for e in ex if e[\\\"source_file\\\"] == src]\\n    raw_ids = [r[\\\"row_id\\\"] for r in raw]\\n    got = sorted([c[\\\"row_id\\\"] for c in clean] + [e[\\\"row_id\\\"] for e in exs])\\n    assert got == sorted(raw_ids), (src, got)\\n    assert len(set(got)) == len(got)\\n    raw_known = sum((parse_money(r[amtcol]) or Decimal(0) for r in raw), Decimal(0))\\n    raw_blank = sum(1 for r in raw if parse_money(r[amtcol]) is None)\\n    ex_known = sum((Decimal(e[\\\"amount_cad\\\"]) for e in exs if e[\\\"amount_cad\\\"]), Decimal(0))\\n    ex_blank = sum(1 for e in exs if not e[\\\"amount_cad\\\"])\\n    return dict(raw_n=len(raw), inc_n=len(clean), exc_n=len(exs), raw_amt=raw_known, exc_amt=ex_known,\\n                inc_amt=raw_known - ex_known, raw_blank=raw_blank, ex_blank=ex_blank,\\n                exc_ids=\\\", \\\".join(e[\\\"row_id\\\"] for e in exs))\\n\\n\\nRS = recon(sales_raw, cs, \\\"inputs/sales.csv\\\", \\\"gross_cad\\\")\\nRR = recon(ref_raw, cr, \\\"inputs/refunds.csv\\\", \\\"amount_cad\\\")\\nRA = recon(ads_raw, ca, \\\"inputs/ads.csv\\\", \\\"spend_cad\\\")\\nassert RS[\\\"inc_amt\\\"] == M[\\\"Combined\\\"][\\\"gross\\\"]\\nassert RR[\\\"inc_amt\\\"] == M[\\\"Combined\\\"][\\\"ref\\\"]\\nassert RA[\\\"inc_amt\\\"] == M[\\\"Combined\\\"][\\\"ads\\\"]\\nassert RR[\\\"raw_blank\\\"] == RR[\\\"ex_blank\\\"]\\n\\nchan = {}\\nfor a in ca:\\n    chan[(a[\\\"product\\\"], a[\\\"channel\\\"])] = chan.get((a[\\\"product\\\"], a[\\\"channel\\\"]), Decimal(0)) + Decimal(a[\\\"spend_cad\\\"])\\n\\nW, C, T = M[\\\"Workshop\\\"], M[\\\"Course\\\"], M[\\\"Combined\\\"]\\nmissing = [e for e in ex if e[\\\"exception_type\\\"] == \\\"missing_refund_amount\\\"]\\nassert len(missing) == 1 and missing[0][\\\"related_order_id\\\"] in paid\\ncap = Decimal(paid[missing[0][\\\"related_order_id\\\"]][\\\"gross_cad\\\"])  # policy ceiling for the unknown refund\\npend = [e for e in ex if e[\\\"exception_type\\\"] == \\\"refund_pending\\\"]\\nlate = [e for e in ex if e[\\\"exception_type\\\"] == \\\"settled_out_of_period\\\"]\\norphan = [e for e in ex if e[\\\"exception_type\\\"] == \\\"no_valid_paid_order\\\"]\\npend_amt = sum(Decimal(e[\\\"amount_cad\\\"]) for e in pend)\\nlate_amt = sum(Decimal(e[\\\"amount_cad\\\"]) for e in late)\\nw_exposure = W[\\\"ref\\\"] + pend_amt + late_amt\\n\\n\\ndef row(label, key, fmt=mc, prov=False):\\n    star = \\\" ‡\\\" if prov else \\\"\\\"\\n    return f\\\"| {label} | {fmt(W[key])} | {fmt(C[key])}{star} | {fmt(T[key])}{star} |\\\"\\n\\n\\ndef ratio(a, b):\\n    return (a / b).quantize(TWO, rounding=ROUND_HALF_UP)\\n\\n\\nL = []\\nA = L.append\\nA(\\\"# Northline Workshops — October 2026 results (CAD, tax excluded)\\\")\\nA(\\\"\\\")\\nA(\\\"Period: 2026-10-01 to 2026-10-31 inclusive. Basis: `inputs/policy.md` (\\\\\\\"Northline Workshops accounting note — October 2026\\\\\\\"; \\\"\\n  \\\"it has one heading, so paragraphs are cited as para 1–3). Produced by `output/reconcile.py` from the three raw CSVs, which were not modified.\\\")\\nA(\\\"\\\")\\nA(\\\"## 1. Bottom line\\\")\\nA(\\\"\\\")\\nA(f\\\"- **{T['n']} paid orders, gross sales {mc(T['gross'])}, applied refunds {mc(T['ref'])}, net revenue {mc(T['net'])}, \\\"\\n  f\\\"ad spend {mc(T['ads'])}, contribution after advertising {mc(T['contrib'])}, net revenue per paid order {mc(T['per'])}.**\\\")\\nA(f\\\"- **Course and combined net revenue, contribution and per-order figures are PROVISIONAL.** Refund RF05 (row R06, order N1011, \\\"\\n  f\\\"settled 2026-10-25) has no amount. Per policy it is unknown, not zero, and is left out of the calculable refund total. \\\"\\n  f\\\"Workshop figures are not affected by it.\\\")\\nA(\\\"- Contribution after advertising is **not profit**: no COGS, payment fees, salaries or overhead were supplied (policy para 1).\\\")\\nA(\\\"\\\")\\nA(\\\"## 2. Results\\\")\\nA(\\\"\\\")\\nA(\\\"| Measure | Workshop | Course | Combined |\\\")\\nA(\\\"|---|---:|---:|---:|\\\")\\nA(row(\\\"Paid order count\\\", \\\"n\\\", fmt=str))\\nA(row(\\\"Gross sales\\\", \\\"gross\\\"))\\nA(row(\\\"Applied refunds (settled in October, calculable)\\\", \\\"ref\\\", prov=True))\\nA(row(\\\"Net revenue (gross − applied refunds)\\\", \\\"net\\\", prov=True))\\nA(row(\\\"Advertising spend\\\", \\\"ads\\\"))\\nA(row(\\\"Contribution after advertising (net revenue − ad spend)\\\", \\\"contrib\\\", prov=True))\\nA(row(\\\"Net revenue per paid order\\\", \\\"per\\\", prov=True))\\nA(\\\"\\\")\\nA(\\\"‡ Provisional: excludes the unknown amount of settled refund RF05 (R06). Calculation: \\\"\\n  f\\\"Workshop {mc(W['gross'])} − {mc(W['ref'])} = {mc(W['net'])}; − {mc(W['ads'])} = {mc(W['contrib'])}; {mc(W['net'])} ÷ {W['n']} = {mc(W['per'])}. \\\"\\n  f\\\"Course {mc(C['gross'])} − {mc(C['ref'])} = {mc(C['net'])}; − {mc(C['ads'])} = {mc(C['contrib'])}; {mc(C['net'])} ÷ {C['n']} = {mc(C['per'])}. \\\"\\n  f\\\"Combined {mc(T['gross'])} − {mc(T['ref'])} = {mc(T['net'])}; − {mc(T['ads'])} = {mc(T['contrib'])}; {mc(T['net'])} ÷ {T['n']} = {mc(T['per'])}.\\\")\\nA(\\\"\\\")\\nA(f\\\"**Bound on the provisional figures (not an estimate).** Policy para 3 says a refund cannot exceed paid gross; N1011's gross is {mc(cap)}. \\\"\\n  f\\\"So once RF05's amount is known, Course net revenue will fall somewhere from {mc(C['net'] - cap)} (full refund) up to just under {mc(C['net'])}; \\\"\\n  f\\\"Course contribution from {mc(C['contrib'] - cap)} to just under {mc(C['contrib'])}; combined net revenue from {mc(T['net'] - cap)} to just under {mc(T['net'])}; \\\"\\n  f\\\"combined contribution from {mc(T['contrib'] - cap)} to just under {mc(T['contrib'])}. The actual amount is not in the inputs and has not been guessed.\\\")\\nA(\\\"\\\")\\nA(\\\"Included orders (from `cleaned-sales.csv`):\\\")\\nA(\\\"\\\")\\nA(\\\"| Product | Order (row) : gross |\\\")\\nA(\\\"|---|---|\\\")\\nfor p in (\\\"Workshop\\\", \\\"Course\\\"):\\n    A(f\\\"| {p} | \\\" + \\\"; \\\".join(f\\\"{s['order_id']} ({s['row_id']}): {s['gross_cad']}\\\" for s in cs if s[\\\"product\\\"] == p) + \\\" |\\\")\\nA(\\\"\\\")\\nA(\\\"Applied refunds (`cleaned-refunds.csv`): \\\" + \\\"; \\\".join(\\n    f\\\"{r['refund_id']} ({r['row_id']}) {r['amount_cad']} on {r['order_id']} [{r['product']}], settled {r['settled_date']}\\\" for r in cr) + \\\".\\\")\\nA(\\\"\\\")\\nA(\\\"Ad spend included (`cleaned-ads.csv`), by product and channel: \\\" + \\\"; \\\".join(\\n    f\\\"{p} {c} {mc(v)}\\\" for (p, c), v in sorted(chan.items(), reverse=True)) + \\\".\\\")\\nA(\\\"\\\")\\nA(\\\"## 3. Reconciliation of included and excluded records\\\")\\nA(\\\"\\\")\\nA(\\\"| Source file | Raw rows | Included (cleaned file) | Excluded (exceptions.csv) | Excluded row IDs |\\\")\\nA(\\\"|---|---:|---:|---:|---|\\\")\\nA(f\\\"| inputs/sales.csv | {RS['raw_n']} | {RS['inc_n']} | {RS['exc_n']} | {RS['exc_ids']} |\\\")\\nA(f\\\"| inputs/refunds.csv | {RR['raw_n']} | {RR['inc_n']} | {RR['exc_n']} | {RR['exc_ids']} |\\\")\\nA(f\\\"| inputs/ads.csv | {RA['raw_n']} | {RA['inc_n']} | {RA['exc_n']} | {RA['exc_ids']} |\\\")\\ntn = RS['raw_n'] + RR['raw_n'] + RA['raw_n']\\nA(f\\\"| Total | {tn} | {RS['inc_n'] + RR['inc_n'] + RA['inc_n']} | {RS['exc_n'] + RR['exc_n'] + RA['exc_n']} | |\\\")\\nA(\\\"\\\")\\nA(\\\"Every raw row ID appears exactly once, in either a cleaned file or `exceptions.csv` (asserted by the script).\\\")\\nA(\\\"\\\")\\nA(\\\"| Amount tie-out (CAD) | Raw rows, as parsed | Less excluded | = Included | Matches section 2 |\\\")\\nA(\\\"|---|---:|---:|---:|---|\\\")\\nA(f\\\"| Sales gross | {mc(RS['raw_amt'])} | {mc(RS['exc_amt'])} | {mc(RS['inc_amt'])} | Gross sales {mc(T['gross'])} |\\\")\\nA(f\\\"| Refund amounts | {mc(RR['raw_amt'])} + 1 blank | {mc(RR['exc_amt'])} + 1 blank | {mc(RR['inc_amt'])} | Applied refunds {mc(T['ref'])} |\\\")\\nA(f\\\"| Ad spend | {mc(RA['raw_amt'])} | {mc(RA['exc_amt'])} | {mc(RA['inc_amt'])} | Ad spend {mc(T['ads'])} |\\\")\\nA(\\\"\\\")\\nA(\\\"Exclusions by reason (full detail, policy reference and follow-up per row in `exceptions.csv`):\\\")\\nA(\\\"\\\")\\nA(\\\"| Row | Record | Amount | Reason | Effect |\\\")\\nA(\\\"|---|---|---:|---|---|\\\")\\nfor e in ex:\\n    rec = e[\\\"record_id\\\"] + (f\\\" → {e['related_order_id']}\\\" if e[\\\"source_file\\\"].endswith(\\\"refunds.csv\\\") else \\\"\\\")\\n    A(f\\\"| {e['row_id']} | {rec} | {e['amount_cad'] or '(blank)'} | {e['exception_type']}\\\"\\n      + (f\\\" (kept {e['retained_row_id']})\\\" if e[\\\"retained_row_id\\\"] else \\\"\\\") + f\\\" | {e['effect_on_october_totals']} |\\\")\\nA(\\\"\\\")\\nA(\\\"Checks that found nothing: no unmapped products; no applied refund exceeds its order's paid gross \\\"\\n  \\\"(RF01 240.00 ≤ 480.00 on N1003; RF02 60.00 ≤ 240.00 on N1006); no unparseable dates or amounts other than the blank RF05 amount.\\\")\\nA(\\\"\\\")\\nA(\\\"## 4. Open items that could change reported figures\\\")\\nA(\\\"\\\")\\nA(f\\\"1. **RF05 / R06 (N1011, Course) — amount missing.** Makes Course and combined net revenue provisional (bound in section 2). Needs the settled amount from the payment processor.\\\")\\nA(f\\\"2. **RF04 / R05 — settled 2026-10-19 for 120.00 against order N9999, which is not in"
        }
      }
    ]
  }
]
