""" GL Analyzer: a general-purpose version of financial_reports' Balance Sheet supporting-schedule feature. That feature nets out reversing/wash GL entries and groups what's left by a fixed categorization chain (Spend Category, Contingent Worker, Supplier/memo fallback), for Balance Sheet accounts only. This tool exposes the same underlying pipeline (see common.net_gl_lines / common.build_gl_schedule) for ANY account and ANY GL Dump column the user picks as the grouping field - "what's actually making up this balance" for a revenue or expense account works exactly the same way as it does for a Balance Sheet account. Flask-free per this repo's tool convention. """ import re import pandas as pd import openpyxl from openpyxl.styles import Font from openpyxl.utils import get_column_letter from common import GL_AMOUNT_COL, net_gl_lines, build_gl_schedule FONT_NAME = "Arial" FONT_SIZE = 11 BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True) ACCOUNTING_FORMAT_CENTS = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' _SHEET_INVALID_CHARS = re.compile(r'[:\\/?*\[\]]') def list_accounts(gl_df): """ Distinct Ledger Account values in this GL Dump, each with a line count, sorted by account code - the account picker's data source. Deliberately no prefix restriction (unlike financial_reports' Balance Sheet schedules, scoped to codes 1/2/3) - this tool works on any account, revenue and expense included. """ codes = gl_df["Ledger Account"].astype(str).str.strip() counts = codes.value_counts() accounts = [ {"code": account.split(":")[0].strip(), "label": account, "line_count": int(count)} for account, count in counts.items() ] accounts.sort(key=lambda a: a["code"]) return accounts def header_fill_rates(gl_df, account_codes): """ For the GL lines belonging to any of account_codes, every column's non-null fill rate (0-100), sorted highest first - lets the UI steer the user toward a header that will actually produce a useful schedule for THIS account rather than a generic column list that might be mostly blank (confirmed for real: Spend Category coverage alone ranges from 0% on AP/AR-type accounts to ~88% on accrual-type ones - see financial_reports' CONTINGENT_WORKER_ACCOUNT_CODES). """ codes = set(account_codes) account_col = gl_df["Ledger Account"].astype(str).str.strip().str.split(":").str[0] sub = gl_df[account_col.isin(codes)] line_count = len(sub) if line_count == 0: return {"columns": [], "line_count": 0} columns = [ {"name": col, "fill_pct": round(100 * sub[col].notna().mean(), 1)} for col in gl_df.columns ] columns.sort(key=lambda c: (-c["fill_pct"], c["name"])) return {"columns": columns, "line_count": line_count} def _make_categorize_fn(main_header): def categorize(row): value = row.get(main_header) if pd.notna(value) and str(value).strip(): return str(value).strip(), True return "(blank)", False return categorize def build_account_report(gl_df, account, main_header, extra_headers): """ Full pipeline for one account: filter to its posted GL lines, net out reversals/wash entries (common.net_gl_lines - same three-pass pipeline financial_reports' Balance Sheet schedules use), then group what's left by main_header's raw value ("(blank)" for a missing value - still subject to revaluation-line folding, see common._attribute_revaluation_lines, so a blank FX-timing line still gets attributed to whichever real group shares its Project+currency) with an effective FX rate per group (common.build_gl_schedule). Returns the grouped schedule DataFrame (empty if no GL activity for this account). """ account_code = account.split(":")[0].strip() sub = gl_df[gl_df["Ledger Account"].astype(str).str.strip().str.startswith(account_code)].copy() sub = sub[sub[GL_AMOUNT_COL].abs() >= 0.005] empty_columns = ["category", "orig_currency", "orig_total", "cad_total", "rate", "amt_cad", *extra_headers] if sub.empty: return pd.DataFrame(columns=empty_columns) sub = net_gl_lines(sub) if sub.empty: return pd.DataFrame(columns=empty_columns) return build_gl_schedule(sub, _make_categorize_fn(main_header), extra_columns=extra_headers) def _sanitize_sheet_name(account): code, _, name = account.partition(":") label = f"{code} {name}".strip() if name else code cleaned = _SHEET_INVALID_CHARS.sub("", label) return cleaned[:31] or "Schedule" def _write_cell(ws, row, col, value, bold=False, number_format=None): c = ws.cell(row=row, column=col, value=value) c.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=bold) if number_format: c.number_format = number_format return c def write_account_sheet(wb, account, schedule_df, main_header, extra_headers, report_date, number_format=ACCOUNTING_FORMAT_CENTS): """ One sheet per account: Description (main_header's value) | one column per extra_headers | Original Curr | Curr | Rate | Amt (CAD), one row per (category, currency) - same row shape as financial_reports' write_schedule_sheet, but with a dynamic extra-column set and no Trial Balance check block (there's no separate TB upload in this tool - just a Total row via a live SUM formula). """ ws = wb.create_sheet(_sanitize_sheet_name(account)) ws.column_dimensions["A"].width = 46 for i in range(len(extra_headers)): ws.column_dimensions[get_column_letter(2 + i)].width = 28 curr_col = 2 + len(extra_headers) # Original Curr rate_col = curr_col + 2 # Rate amt_col = curr_col + 3 # Amt (CAD) for offset, width in enumerate((15, 7, 9)): ws.column_dimensions[get_column_letter(curr_col + offset)].width = width ws.column_dimensions[get_column_letter(amt_col)].width = 16 _write_cell(ws, 1, 1, f"GL Analysis — {account}", bold=True) _write_cell(ws, 2, 1, f"Grouped by: {main_header}", bold=True) _write_cell(ws, 3, 1, f"As of {report_date}", bold=True) header_row = 5 headers = ["Description", *extra_headers, "Original Curr", "Curr", "Rate", "Amt (CAD)"] for col, label in enumerate(headers, start=1): _write_cell(ws, header_row, col, label, bold=True) row = header_row + 1 first_data_row = row if schedule_df.empty: _write_cell(ws, row, 1, "No matching GL activity found for this account", bold=False) _write_cell(ws, row, amt_col, 0, number_format=number_format) row += 1 for _, r in schedule_df.iterrows(): _write_cell(ws, row, 1, r["category"], bold=False) for i, col_name in enumerate(extra_headers): value = r[col_name] _write_cell(ws, row, 2 + i, value if pd.notna(value) else "", bold=False) if r["rate"] is not None: _write_cell(ws, row, curr_col, round(r["orig_total"], 2), bold=False, number_format=number_format) _write_cell(ws, row, curr_col + 1, r["orig_currency"], bold=False) _write_cell(ws, row, rate_col, round(r["rate"], 4), bold=False, number_format="0.0000") _write_cell(ws, row, amt_col, round(r["amt_cad"], 2), bold=False, number_format=number_format) row += 1 last_data_row = row - 1 total_row = row + 1 _write_cell(ws, total_row, 1, "Total", bold=True) amt_letter = get_column_letter(amt_col) c = ws.cell(row=total_row, column=amt_col, value=f"=SUM({amt_letter}{first_data_row}:{amt_letter}{last_data_row})") c.font, c.number_format = BOLD_FONT, number_format total = round(schedule_df["amt_cad"].sum(), 2) if not schedule_df.empty else 0.0 return {"account": account, "total": total, "row_count": len(schedule_df)}