diff --git a/app/tools/donor_report/logic.py b/app/tools/donor_report/logic.py index 2d4efe4..3dab563 100644 --- a/app/tools/donor_report/logic.py +++ b/app/tools/donor_report/logic.py @@ -96,10 +96,6 @@ def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map): df = tb_df.copy() df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(account_codes)] - codes = df["Ledger Account"].astype(str).str.split(":", n=1) - df["account_code"] = codes.str[0].str.strip() - df["account_name"] = codes.str[1].str.strip() - parsed = df["Project"].apply(parse_project) df["slob"] = parsed.apply(lambda t: t[0]) df["donor"] = parsed.apply(lambda t: resolve_donor(t[1], merge_map)) @@ -108,8 +104,15 @@ def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map): raw_amount = df["Planeterra Foundation"].fillna(0) df["amount"] = -raw_amount if flip_sign else raw_amount + # Grouped by donor -> project code -> category only, deliberately not + # by Ledger Account: the same project code/category can appear under + # more than one GL account (e.g. the same spend category posted to + # two different expense accounts), and showing that as two rows with + # an identical-looking label is exactly the clutter a non-finance + # reader doesn't need - one combined row per (project code, category) + # is the whole point of grouping "by project code". grouped = ( - df.groupby(["donor", "account_code", "account_name", "slob", "category"], as_index=False)["amount"] + df.groupby(["donor", "slob", "category"], as_index=False)["amount"] .sum() ) # Drop groups that net to exactly zero - since this is a trial @@ -154,18 +157,8 @@ def _write_cell(ws, row, col, value, bold=False, number_format=None): def _rows_needed(df): - """How many rows a section (Revenue or Expenses) needs: one header - row per account, then per project code (SLOB) one row per category - plus one subtotal row.""" - if df.empty: - return 0 - needed = 0 - for code in df["account_code"].unique(): - needed += 1 - acct_df = df[df["account_code"] == code] - for slob in acct_df["slob"].unique(): - needed += len(acct_df[acct_df["slob"] == slob]) + 1 - return needed + """One row per (project code, category) - no header or subtotal rows.""" + return len(df) def _adjust_block(ws, block_start, available, needed): @@ -185,48 +178,33 @@ def _adjust_block(ws, block_start, available, needed): def _write_section(ws, start_row, df): """ - Write Account -> Category rows starting at start_row, subtotaled by - project code (SLOB), with a SUM formula (over its own category rows) - on each subtotal row. Project code and category are already their - own columns (C, D), so detail rows leave column A blank rather than - repeating that text - only the account header and each subtotal row - get an A-column label. Returns the list of subtotal cell coordinates - (for the section total's own SUM formula) and this section's raw total. + Write one row per (project code, category), sorted by project code + then category, starting at start_row - a flat, clean list with no + account/subtotal rows breaking it up, so the whole section is one + contiguous range for the section total's SUM formula. Returns + (first_row, last_row) of the written range (None if empty) and this + section's raw total. """ - row = start_row - subtotal_cells = [] - section_total = 0.0 if df.empty: - return subtotal_cells, section_total + return None, 0.0 - for code in sorted(df["account_code"].unique()): - acct_df = df[df["account_code"] == code] - account_name = acct_df["account_name"].iloc[0] - _write_cell(ws, row, 1, account_name, bold=False) + row = start_row + section_total = 0.0 + for _, r in df.sort_values(["slob", "category"]).iterrows(): + amount = round(r["amount"], 2) + slob_label = r["slob"] or "(No project code)" + # Explicitly blank column A - the template's own placeholder text + # ("Donations & Fundraising Revenue", "Disbursement to Projects") + # sits on this first row otherwise, since ws.cell(value=None) is a + # no-op in openpyxl rather than a clear - direct assignment is needed. + ws.cell(row=row, column=1).value = None + _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) + _write_cell(ws, row, 3, slob_label, bold=False) + _write_cell(ws, row, 4, r["category"], bold=False) + section_total += amount row += 1 - for slob in sorted(acct_df["slob"].unique()): - slob_df = acct_df[acct_df["slob"] == slob] - slob_label = slob or "(No project code)" - - cat_first_row = row - for _, r in slob_df.sort_values("category").iterrows(): - amount = round(r["amount"], 2) - _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) - _write_cell(ws, row, 3, slob_label, bold=False) - _write_cell(ws, row, 4, r["category"], bold=False) - section_total += amount - row += 1 - cat_last_row = row - 1 - - _write_cell(ws, row, 1, f"{slob_label} Subtotal", bold=True) - c = ws.cell(row=row, column=2, value=f"=SUM(B{cat_first_row}:B{cat_last_row})") - c.font = BOLD_FONT - c.number_format = AMOUNT_FORMAT - subtotal_cells.append(f"B{row}") - row += 1 - - return subtotal_cells, round(section_total, 2) + return (start_row, row - 1), round(section_total, 2) def _write_donor_sheet(wb, template_ws, donor, revenue_df, expense_df): @@ -250,18 +228,18 @@ def _write_donor_sheet(wb, template_ws, donor, revenue_df, expense_df): total_expenses_row = expense_block_start + expense_needed surplus_row = total_expenses_row + 2 - rev_subtotals, revenue_total = _write_section(ws, 7, revenue_df) - exp_subtotals, expense_total = _write_section(ws, expense_block_start, expense_df) + rev_range, revenue_total = _write_section(ws, 7, revenue_df) + exp_range, expense_total = _write_section(ws, expense_block_start, expense_df) _write_cell(ws, total_revenue_row, 1, "Total Revenue", bold=True) c = ws.cell(row=total_revenue_row, column=2, - value=("=SUM(" + ",".join(rev_subtotals) + ")") if rev_subtotals else 0) + value=f"=SUM(B{rev_range[0]}:B{rev_range[1]})" if rev_range else 0) c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT _write_cell(ws, total_expenses_row, 1, "Total Expenses", bold=True) c = ws.cell(row=total_expenses_row, column=2, - value=("=SUM(" + ",".join(exp_subtotals) + ")") if exp_subtotals else 0) + value=f"=SUM(B{exp_range[0]}:B{exp_range[1]})" if exp_range else 0) c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT