|
| 1 | +# SPDX-License-Identifier: MIT |
| 2 | +"""Generic 'core_gl' adapter for Track D BYOD normalization. |
| 3 | +
|
| 4 | +This adapter is the bridge from "perfect" template exports (already matching the |
| 5 | +contract) to "slightly messy" Sheets/Excel exports. |
| 6 | +
|
| 7 | +Features (v1): |
| 8 | +- Header matching that tolerates case/spacing/punctuation (e.g., "Account ID") |
| 9 | +- Whitespace trimming across all cells |
| 10 | +- Money cleanup for debit/credit (commas, $, parentheses-as-negative) |
| 11 | +- Canonical output column order (required first, then passthrough extras) |
| 12 | +
|
| 13 | +Inputs |
| 14 | +------ |
| 15 | +Reads contract-named files from ``tables/``: |
| 16 | +- chart_of_accounts.csv |
| 17 | +- gl_journal.csv |
| 18 | +
|
| 19 | +Outputs |
| 20 | +------- |
| 21 | +Writes contract-named files to ``normalized/`` with contract column names. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import csv |
| 27 | +from pathlib import Path |
| 28 | +from typing import Any |
| 29 | + |
| 30 | +from .._errors import TrackDDataError, TrackDSchemaError |
| 31 | +from ..contracts import schemas_for_profile |
| 32 | +from .base import NormalizeContext |
| 33 | +from .mapping import ( |
| 34 | + build_rename_map, |
| 35 | + clean_cell, |
| 36 | + detect_duplicate_destinations, |
| 37 | + parse_money, |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +_COA_ALIASES: dict[str, tuple[str, ...]] = { |
| 42 | + "account_id": ("acct_id", "acct", "account", "account number", "account_no"), |
| 43 | + "account_name": ("acct_name", "name"), |
| 44 | + "account_type": ("type",), |
| 45 | + "normal_side": ("normal", "side"), |
| 46 | +} |
| 47 | + |
| 48 | +_GL_ALIASES: dict[str, tuple[str, ...]] = { |
| 49 | + "txn_id": ("txnid", "transaction_id", "transaction id", "id"), |
| 50 | + "doc_id": ("doc", "document", "document_id", "document id"), |
| 51 | + "description": ("desc", "memo", "narrative"), |
| 52 | + "account_id": ("acct_id", "acct", "account", "account number", "account_no"), |
| 53 | + "debit": ("dr", "debits"), |
| 54 | + "credit": ("cr", "credits"), |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +def _write_normalized_csv( |
| 59 | + src: Path, |
| 60 | + dst: Path, |
| 61 | + *, |
| 62 | + required_columns: tuple[str, ...], |
| 63 | + aliases: dict[str, tuple[str, ...]] | None = None, |
| 64 | + money_columns: tuple[str, ...] = (), |
| 65 | +) -> dict[str, Any]: |
| 66 | + with src.open("r", newline="", encoding="utf-8-sig") as f_in: |
| 67 | + reader = csv.DictReader(f_in) |
| 68 | + if not reader.fieldnames: |
| 69 | + raise TrackDDataError(f"CSV appears to have no header row: {src.name}") |
| 70 | + |
| 71 | + fieldnames = [str(c) for c in reader.fieldnames if c is not None] |
| 72 | + rename_map = build_rename_map(fieldnames, required_columns=required_columns, aliases=aliases) |
| 73 | + |
| 74 | + dups = detect_duplicate_destinations(rename_map) |
| 75 | + if dups: |
| 76 | + pieces = [f"{dst}: {', '.join(srcs)}" for dst, srcs in sorted(dups.items())] |
| 77 | + raise TrackDSchemaError( |
| 78 | + "Ambiguous column mapping (multiple source columns map to the same required column).\n" |
| 79 | + + "\n".join(pieces) |
| 80 | + ) |
| 81 | + |
| 82 | + # Determine output fields: required columns first, then passthrough extras. |
| 83 | + required_set = set(required_columns) |
| 84 | + extras: list[str] = [] |
| 85 | + for c in fieldnames: |
| 86 | + dest = rename_map.get(c, c) |
| 87 | + if dest in required_set: |
| 88 | + continue |
| 89 | + # Preserve original extra column names (trimmed). |
| 90 | + extras.append(c.strip()) |
| 91 | + |
| 92 | + out_fields = list(required_columns) + extras |
| 93 | + |
| 94 | + dst.parent.mkdir(parents=True, exist_ok=True) |
| 95 | + with dst.open("w", newline="", encoding="utf-8") as f_out: |
| 96 | + writer = csv.DictWriter(f_out, fieldnames=out_fields) |
| 97 | + writer.writeheader() |
| 98 | + n_rows = 0 |
| 99 | + for row in reader: |
| 100 | + out_row: dict[str, str] = {k: "" for k in out_fields} |
| 101 | + |
| 102 | + # Map + clean required columns |
| 103 | + for src_col in fieldnames: |
| 104 | + raw_val = row.get(src_col) |
| 105 | + val = clean_cell(raw_val) |
| 106 | + dest = rename_map.get(src_col, src_col).strip() |
| 107 | + |
| 108 | + # Extra columns: keep under original header (trimmed). |
| 109 | + if dest not in required_set: |
| 110 | + dest = src_col.strip() |
| 111 | + |
| 112 | + if dest not in out_row: |
| 113 | + # If an extra column name collides with required, prefer required slot. |
| 114 | + continue |
| 115 | + |
| 116 | + if dest in money_columns: |
| 117 | + val = parse_money(val) |
| 118 | + |
| 119 | + out_row[dest] = val |
| 120 | + |
| 121 | + writer.writerow(out_row) |
| 122 | + n_rows += 1 |
| 123 | + |
| 124 | + return { |
| 125 | + "src": str(src), |
| 126 | + "dst": str(dst), |
| 127 | + "written_rows": n_rows, |
| 128 | + "written_columns": out_fields, |
| 129 | + } |
| 130 | + |
| 131 | + |
| 132 | +class CoreGLAdapter: |
| 133 | + name = "core_gl" |
| 134 | + |
| 135 | + def normalize(self, ctx: NormalizeContext) -> dict[str, Any]: |
| 136 | + schemas = schemas_for_profile(ctx.profile) |
| 137 | + |
| 138 | + ctx.normalized_dir.mkdir(parents=True, exist_ok=True) |
| 139 | + |
| 140 | + files: list[dict[str, Any]] = [] |
| 141 | + for schema in schemas: |
| 142 | + src = ctx.tables_dir / schema.name |
| 143 | + dst = ctx.normalized_dir / schema.name |
| 144 | + if not src.exists(): |
| 145 | + raise TrackDDataError(f"Missing required input file for adapter '{self.name}': {src}") |
| 146 | + |
| 147 | + if schema.name == "chart_of_accounts.csv": |
| 148 | + aliases = _COA_ALIASES |
| 149 | + money_cols: tuple[str, ...] = () |
| 150 | + elif schema.name == "gl_journal.csv": |
| 151 | + aliases = _GL_ALIASES |
| 152 | + money_cols = ("debit", "credit") |
| 153 | + else: |
| 154 | + aliases = None |
| 155 | + money_cols = () |
| 156 | + |
| 157 | + files.append( |
| 158 | + _write_normalized_csv( |
| 159 | + src, |
| 160 | + dst, |
| 161 | + required_columns=schema.required_columns, |
| 162 | + aliases=aliases, |
| 163 | + money_columns=money_cols, |
| 164 | + ) |
| 165 | + ) |
| 166 | + |
| 167 | + return { |
| 168 | + "ok": True, |
| 169 | + "adapter": self.name, |
| 170 | + "profile": ctx.profile, |
| 171 | + "project": str(ctx.project_root), |
| 172 | + "tables_dir": str(ctx.tables_dir), |
| 173 | + "normalized_dir": str(ctx.normalized_dir), |
| 174 | + "files": files, |
| 175 | + } |
0 commit comments