equals-wd-card-expense-proc.../app/common.py

354 lines
16 KiB
Python

"""
Shared, Flask-free helpers used by more than one tool. Per the "simple but
modular" convention (see CLAUDE.md), this stays empty until a second tool
actually duplicates something an existing tool already has - GL Dump
loading was the first thing to hit that bar (donor_report, then
financial_reports); the GL netting/grouping pipeline below is the second
(financial_reports' Balance Sheet supporting schedules, then gl_analyzer).
"""
import re
from collections import defaultdict, deque
import pandas as pd
GL_AMOUNT_COL = "Net Ledger Debit minus Credit"
_JE_RE = re.compile(r"JE-\d{4}-\d+")
def find_gl_header_row(path, max_scan_rows=60):
"""
GL Dump exports carry a variable-length metadata block (Company,
Year, Period, Status filter, etc - one label per row) before the
real column-header row. That row's position isn't stable enough to
hardcode - seen at row index 22 in one export and 23 in another (a
difference in how many metadata rows the export included) - so scan
for the row whose values include both "Journal" and "Ledger Account"
(the real header, present in every export of this format seen so
far). Returns the 0-indexed row number, or None if no such row is
found in the first max_scan_rows rows (not a GL Dump).
"""
raw = pd.read_excel(path, sheet_name=0, header=None, nrows=max_scan_rows)
for i, row in raw.iterrows():
vals = {str(v) for v in row.tolist() if pd.notna(v)}
if "Journal" in vals and "Ledger Account" in vals:
return i
return None
def _extract_gl_metadata(path, header_row):
"""
The metadata block above the real header row (see find_gl_header_row)
is one label/value pair per row - Company, Year, Period, Include
Beginning Balance, etc. Read into a dict keyed by label, for
diagnostics (e.g. explaining why a schedule doesn't tie to the trial
balance) rather than the report data itself - callers that don't need
it can ignore df.attrs entirely.
"""
if header_row == 0:
return {}
raw = pd.read_excel(path, sheet_name=0, header=None, nrows=header_row)
meta = {}
for _, row in raw.iterrows():
vals = [v for v in row.tolist() if pd.notna(v)]
if len(vals) >= 2 and isinstance(vals[0], str):
meta[str(vals[0]).strip()] = vals[1]
return meta
def load_gl_dump(path):
"""
Read a GL Dump export: locate its header row (see
find_gl_header_row), load the data below it, and filter to
Status == "Posted" - draft/in-progress entries wouldn't be reflected
in a trial balance and would throw off any reconciliation built on
this data. Returns None if this doesn't look like a GL Dump (no
matching header row found in the first 60 rows) - the caller falls
back to treating the file as an unrecognized upload.
The returned DataFrame carries the export's own metadata block (see
_extract_gl_metadata) in df.attrs["gl_metadata"] - pandas preserves
.attrs through the filtering/reset_index below, so callers that want
it (e.g. financial_reports' schedule-mismatch diagnostics) can read
it straight off the DataFrame instead of re-parsing the file.
"""
header_row = find_gl_header_row(path)
if header_row is None:
return None
metadata = _extract_gl_metadata(path, header_row)
df = pd.read_excel(path, sheet_name=0, header=header_row)
if "Status" in df.columns:
df = df[df["Status"] == "Posted"]
df = df.reset_index(drop=True)
df.attrs["gl_metadata"] = metadata
return df
def _extract_je(text):
if pd.isna(text):
return None
m = _JE_RE.match(str(text).strip())
return m.group(0) if m else None
def reversed_by_pass(df):
"""
Pass 1 of the GL netting pipeline: drop any journal explicitly linked
to another via Reversed By/Reverses, where BOTH journals are present
in this data - meaning the reversal already happened within the
period this GL export covers, so neither side should show as still
outstanding.
"""
journals_present = set(df["Journal Number"].dropna().unique())
cleared = set()
for _, row in df.iterrows():
for field in ("Reversed By", "Reverses"):
target = _extract_je(row.get(field))
if target is not None and target in journals_present:
cleared.add(row["Journal Number"])
cleared.add(target)
return df[~df["Journal Number"].isin(cleared)]
def fifo_netting_pass(df):
"""
Pass 2: FIFO exact-amount netting on whatever's left after pass 1 -
catches informal reversals (a separate manual journal entry for the
exact opposite amount, with no explicit Reversed By/Reverses link and
not a same-journal wash). Each line cancels the oldest still-open
line with the exact opposite amount; what's left is what still makes
up the balance.
"""
df = df.sort_values("Accounting Date", kind="stable")
pending = defaultdict(deque)
for idx, row in df.iterrows():
cents = round(row[GL_AMOUNT_COL] * 100)
opp = -cents
if pending[opp]:
pending[opp].popleft()
else:
pending[cents].append(idx)
keep_idx = [i for dq in pending.values() for i in dq]
return df.loc[sorted(keep_idx)]
def journal_wash_pass(df):
"""
Pass 3: drop every line belonging to a journal whose own lines net to
~$0 - a pure reclassification/relabeling with no effect on the
balance (e.g. one line's amount split across two others within the
same journal), which pairwise exact-amount matching (pass 2) can't
catch since it only cancels 2-line pairs. Lines with no Journal
Number are left alone - nothing to group them by.
"""
has_journal = df["Journal Number"].notna()
with_journal, without_journal = df[has_journal], df[~has_journal]
if with_journal.empty:
return df
totals = with_journal.groupby("Journal Number")[GL_AMOUNT_COL].sum()
wash_journals = set(totals[totals.abs() < 0.005].index)
kept = with_journal[~with_journal["Journal Number"].isin(wash_journals)]
return pd.concat([kept, without_journal])
def net_gl_lines(df):
"""
Runs the three netting passes in the required order: Reversed
By/Reverses, THEN FIFO exact-amount netting, THEN the same-journal
wash - not wash-before-FIFO. A journal can look like a "control total
+ itemized detail" breakdown (e.g. a "Beginning Balance" journal: one
+176,983.94 line plus dozens of negative lines listing what makes it
up) rather than a genuine reclassification wash, even though its own
lines also net to ~$0. Dropping the whole journal before FIFO runs
would remove those itemized lines before they get a chance to find
their real, later-dated FIFO counterpart elsewhere - orphaning that
counterpart as a false "still outstanding" line (confirmed: this
happened for real, reproducibly, on account 20300's Beginning Balance
journal). Running FIFO first lets genuine cross-journal matches
happen normally; the wash pass then only cleans up whatever
same-journal zero-sum residue FIFO can't catch on its own (pairwise
only) - which is exactly account 13100's 3-line reclassification
case.
"""
df = reversed_by_pass(df)
df = fifo_netting_pass(df)
df = journal_wash_pass(df)
return df
def _attribute_revaluation_lines(df):
"""
A line whose original-currency amount is exactly zero but whose CAD
amount isn't is a pure revaluation/FX-timing adjustment - there's no
"original currency movement" of its own, it's purely restating an
EXISTING foreign-currency balance to a new rate. It should never
survive as its own schedule row; it belongs folded into whichever
category actually holds that foreign-currency balance, via the same
Project + currency it's tagged with (confirmed against account
20300's and 13100's real supporting schedules - every revaluation
line traced to its owning category this way).
Matching is (Project, currency) against every OTHER category's own
lines. A unique match reassigns the line's category outright and gets
folded in immediately (phase 1) - before a genuine collision (more
than one category shares that Project+currency, e.g. a small balance
and a large one booked under the same Project) gets resolved (phase
2) by picking whichever candidate's resulting blended rate lands
closest to that currency's reference rate.
Two things the reference rate and the per-candidate blend must get
right, both confirmed against real collisions (Trees vs. Tribes under
"Planeterra - C&B - G Adventures"/USD; Vacation vs. Elizabeth's line
under "Planeterra - General Fund"/USD):
- The reference rate must be built ONLY from categories that were
never a candidate in any collision, not a median over every
category's raw rate. A colliding category's own pre-fold rate is
not yet trustworthy (it's exactly what's being resolved), so
including it drags the reference away from the true period rate -
confirmed for real: with Vacation and Elizabeth's raw, unfolded
rates both included in the median, the reference landed near their
shared (wrong) raw value instead of the true 1.4017 established by
the account's genuinely unambiguous categories, and every
collision resolved onto the wrong candidate as a result.
- A candidate's blended rate must be computed from ONLY that
category's rows in the SAME currency as the line being resolved -
a category spanning multiple currencies (e.g. Vacation has CAD,
GBP, and USD lines) has its currencies confused if all of that
category's rows are summed together regardless of currency.
A line with no match at all (no other category shares its Project+
currency) is left as its own row rather than silently dropped, since
dropping it would break the schedule's tie-out to the trial balance.
A reval-shaped line whose "category_reliable" column is already True
is skipped entirely - the caller (see build_gl_schedule) decides what
counts as reliable; confirmed for real that this matters for
financial_reports' Spend Category-based categorization: on account
20300, 204 of 254 reval-shaped lines already carry their own Spend
Category, and re-folding them via the Project+currency heuristic
would risk reassigning an already-correct category onto the wrong
candidate.
"""
is_reval = (df["orig_amount"].abs() < 0.005) & ~df["category_reliable"]
if not is_reval.any():
return df
labeled = df[~is_reval]
if labeled.empty:
return df
df = df.copy()
candidates_by_key = labeled.groupby(["Project", "orig_currency"])["category"].unique()
ambiguous_categories = {
cat for cands in candidates_by_key if len(cands) > 1 for cat in cands
}
def _rate_by_currency(current_df, exclude_categories=()):
cur_labeled = current_df[~is_reval]
if exclude_categories:
cur_labeled = cur_labeled[~cur_labeled["category"].isin(exclude_categories)]
tmp = cur_labeled.groupby(["category", "orig_currency"]).agg(
orig_total=("orig_amount", "sum"), cad_total=(GL_AMOUNT_COL, "sum"),
)
tmp = tmp[tmp["orig_total"].abs() >= 0.005]
if tmp.empty:
return {}
tmp["rate"] = tmp["cad_total"] / tmp["orig_total"]
return tmp.groupby(level="orig_currency")["rate"].median().to_dict()
# Phase 1: fold every unambiguous (single-candidate) line immediately.
unresolved = []
for idx in df[is_reval].index:
row = df.loc[idx]
candidates = candidates_by_key.get((row.get("Project"), row["orig_currency"]), [])
if len(candidates) == 1:
df.at[idx, "category"] = candidates[0]
else:
unresolved.append(idx)
if not unresolved:
return df
# Phase 2: resolve genuine collisions against a reference built only
# from categories that were never ambiguous in the first place, with
# an all-categories fallback for a currency where every category
# happens to be caught up in some collision.
ref_rate = _rate_by_currency(df, exclude_categories=ambiguous_categories)
fallback_rate = _rate_by_currency(df)
for idx in unresolved:
row = df.loc[idx]
currency = row["orig_currency"]
candidates = candidates_by_key.get((row.get("Project"), currency), [])
if len(candidates) == 0:
continue # no owning category found - stays its own row
target = ref_rate.get(currency, fallback_rate.get(currency))
best, best_dist = None, None
for cand in candidates:
cand_rows = df[(df["category"] == cand) & (df["orig_currency"] == currency)]
cand_orig = cand_rows["orig_amount"].sum()
if abs(cand_orig) < 0.005:
continue
implied_rate = (cand_rows[GL_AMOUNT_COL].sum() + row[GL_AMOUNT_COL]) / cand_orig
dist = abs(implied_rate - target) if target is not None else 0
if best_dist is None or dist < best_dist:
best, best_dist = cand, dist
if best is not None:
df.at[idx, "category"] = best
return df
def build_gl_schedule(df, categorize_fn, extra_columns=None):
"""
Categorize every line via categorize_fn(row) -> (label, is_reliable),
fold revaluation/FX-timing lines into their owning label (see
_attribute_revaluation_lines), then group by (label, original
currency) with an effective FX rate computed as CAD total /
original-currency total per group - a blended, period-appropriate
rate rather than one assumed flat rate, since a label can span many
different accrual/transaction dates.
extra_columns (a list of raw column names, default none) each get a
representative value per group - the raw value off whichever single
GL line in that group has the largest absolute CAD amount. These are
per-transaction fields, so a grouped row (which can combine many GL
lines) can't show all of them - the biggest line's value is the most
representative single one to surface, not a synthesized or averaged
one. Output columns are named after extra_columns verbatim.
df must already be netted (see net_gl_lines) and filtered to
whatever scope the caller wants one schedule for (e.g. one account).
"""
extra_columns = extra_columns or []
df = df.copy()
labels_reliable = df.apply(categorize_fn, axis=1, result_type="expand")
df["category"], df["category_reliable"] = labels_reliable[0], labels_reliable[1]
df["orig_currency"] = df.get("Transaction Currency.1")
df["orig_amount"] = df["Transaction Debit Amount"].fillna(0) - df["Transaction Credit Amount"].fillna(0)
is_cad_native = df["orig_currency"].isna() | (df["orig_currency"] == "CAD")
df.loc[is_cad_native, "orig_currency"] = "CAD"
df.loc[is_cad_native, "orig_amount"] = df.loc[is_cad_native, GL_AMOUNT_COL]
df = _attribute_revaluation_lines(df)
grouped = df.groupby(["category", "orig_currency"], as_index=False).agg(
orig_total=("orig_amount", "sum"), cad_total=(GL_AMOUNT_COL, "sum"),
)
has_rate = grouped["orig_total"].abs() >= 0.005
grouped["rate"] = None
grouped.loc[has_rate, "rate"] = grouped.loc[has_rate, "cad_total"] / grouped.loc[has_rate, "orig_total"]
if extra_columns:
biggest_line_idx = df.groupby(["category", "orig_currency"])[GL_AMOUNT_COL].apply(
lambda s: s.abs().idxmax()
)
representative = df.loc[biggest_line_idx.values, ["category", "orig_currency", *extra_columns]]
grouped = grouped.merge(representative, on=["category", "orig_currency"], how="left")
for col in extra_columns:
grouped[col] = grouped[col].where(grouped[col].notna(), None)
grouped["amt_cad"] = grouped["cad_total"] # always the true ledger amount, whether or not a rate applies
grouped.loc[~has_rate, "orig_total"] = None
grouped.loc[~has_rate, "orig_currency"] = None
return grouped.sort_values("amt_cad", key=lambda s: s.abs(), ascending=False).reset_index(drop=True)