codex/aram-mapping-source-parser-20261101
add-index-html-10623938925177053894
arena/094f314c-aram
chatgpt-phase1b2-autopilot
codex/adr-future-connectors-pi-v1
codex/aram-account-note-source-trace-20261031
codex/aram-actions-node24-maintenance-20261031
codex/aram-analyst-review-workbook-20261031
codex/aram-bs-candidate-statement-20261031
codex/aram-cash-flow-direct-candidate-20261031
codex/aram-clean-reference-year-integrity-20261030
codex/aram-cross-statement-controls-20261031
codex/aram-equity-changes-candidate-20261031
codex/aram-five-statement-cli-20261031
codex/aram-five-statement-integration-20261031
codex/aram-five-statement-orchestrator-20261031
codex/aram-gate3-coverage-target-guard-20261030
codex/aram-gate3-hidden-xlsx-guard-20261030
codex/aram-gate3-integration-validation-20261030
codex/aram-gate3-mapping-change-preview-20261030
codex/aram-gate3-stale-note-guard-20261030
codex/aram-income-statement-candidate-20261031
codex/aram-manifest-referential-integrity-20261031
codex/aram-mapping-source-parser-20261101
codex/aram-multidimensional-mapping-20261101
codex/aram-multistatement-mapping-20261031
codex/aram-pipeline-manifest-schema-20261031
codex/aram-readonly-mapping-coverage-20261031
codex/aram-reconciliation-review-gate-20261031
codex/aram-same-flush-fiscal-lock-20261030
codex/aram-synthetic-windows-demo-20261031
codex/aram-trial-balance-diagnostic-20261031
codex/aram-windows-background-detail-search-20261031
codex/aram-windows-detail-review-20261031
codex/aram-windows-five-statement-pilot-20261031
codex/aram-windows-statement-figures-20261031
codex/gate-2a-pilot-workbook
codex/gate-2a-pilot-workbook-6864754244772568979
codex/gate3-authenticated-principal-boundary-20261030
codex/gate3-authored-draft-staging-20261030
codex/gate3-carry-forward-preview-20261023
codex/gate3-draft-staging-audit-20261030
codex/gate3-mapping-batch-freshness-20261030
codex/gate3-mapping-batch-review-20261030
codex/gate3-mapping-core
codex/gate3-mapping-coverage-20261023
codex/gate3-mapping-excel-20261023
codex/gate3-note-mapping-review-20261023
codex/gate3-signed-year-scope-20261030
codex/gate3-unapproved-proposal-storage-20261030
codex/payvast-mapping-discovery-20261023
codex/phase-2a-backend-foundation
codex/phase-2b-post-merge-record
codex/phase-2b-source-registration
codex/phase-2b-source-registration-12955190277775369594
codex/post-gate2a-control-reconciliation
codex/post-pr18-acceptance-record
codex/project-control-foundation
codex/t1-repo-hygiene-20261023
codex/t2-ci-hardening-20261023
codex/t3-explicit-migrations-20261023
codex/t6a-readonly-diagnostics-20261023
codex/v1-01-safety-gate-hardening
codex/v1-year-isolation-followup-20261023
codex/windows-native-pilot-shell-20261030
docs/aram-master-control-plan-20261111
docs/aram-roadmap-dashboard-20261030
docs/financial-statement-reconciliation-1402-1404-20261110
feat/gate3-governed-mapping-20261101
feat/gate3-package9-1-security-20261103
feat/gate3-package9-isolated-20261103
fix/password-unicode-validation-20261111
governance/aram-5-1-3-controls-20261030
governance/role-based-operating-model
jules-1168663913887856558-73b8a885
jules-gate-2b-mapping-workflow-foundation-4137724387867065330
phase-1b1-audit-report-7365389436990903239
phase-2a-backend-foundation-10237597358138521261
phase1b2-postmerge-metadata-fix
refactor/drg-parent-year-id-15088443704684163304
source-data-cleanup
| 1 | from __future__ import annotations |
| 2 | |
| 3 | import enum |
| 4 | from datetime import UTC, datetime |
| 5 | from decimal import Decimal |
| 6 | from typing import Any |
| 7 | |
| 8 | from sqlalchemy import ( |
| 9 | JSON, |
| 10 | CheckConstraint, |
| 11 | DateTime, |
| 12 | Enum, |
| 13 | ForeignKey, |
| 14 | Integer, |
| 15 | Numeric, |
| 16 | String, |
| 17 | Text, |
| 18 | UniqueConstraint, |
| 19 | event, |
| 20 | inspect, |
| 21 | select, |
| 22 | ) |
| 23 | from sqlalchemy.orm import Mapped, Session, mapped_column, relationship |
| 24 | |
| 25 | from aram_backend.database import Base |
| 26 | |
| 27 | |
| 28 | def utc_now() -> datetime: |
| 29 | return datetime.now(UTC) |
| 30 | |
| 31 | |
| 32 | class FiscalYearStatus(str, enum.Enum): |
| 33 | DRAFT = "Draft" |
| 34 | APPROVED = "Approved" |
| 35 | LOCKED = "Locked" |
| 36 | |
| 37 | |
| 38 | class StatementType(str, enum.Enum): |
| 39 | BALANCE_SHEET = "BS" |
| 40 | INCOME_STATEMENT = "IS" |
| 41 | CASH_FLOW = "CF" |
| 42 | EQUITY = "EQ" |
| 43 | |
| 44 | |
| 45 | class TimestampMixin: |
| 46 | created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now) |
| 47 | updated_at: Mapped[datetime] = mapped_column( |
| 48 | DateTime(timezone=True), default=utc_now, onupdate=utc_now |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | class Company(TimestampMixin, Base): |
| 53 | __tablename__ = "companies" |
| 54 | id: Mapped[int] = mapped_column(primary_key=True) |
| 55 | code: Mapped[str] = mapped_column(String(64), unique=True, index=True) |
| 56 | name: Mapped[str] = mapped_column(String(255)) |
| 57 | fiscal_years: Mapped[list[FiscalYear]] = relationship( |
| 58 | back_populates="company", cascade="all, delete-orphan" |
| 59 | ) |
| 60 | |
| 61 | |
| 62 | class FiscalYear(TimestampMixin, Base): |
| 63 | __tablename__ = "fiscal_years" |
| 64 | __table_args__ = ( |
| 65 | UniqueConstraint("company_id", "year", name="uq_fiscal_year_company_year"), |
| 66 | CheckConstraint("year > 0", name="positive_year"), |
| 67 | ) |
| 68 | id: Mapped[int] = mapped_column(primary_key=True) |
| 69 | company_id: Mapped[int] = mapped_column(ForeignKey("companies.id", ondelete="RESTRICT")) |
| 70 | year: Mapped[int] = mapped_column(Integer) |
| 71 | status: Mapped[FiscalYearStatus] = mapped_column( |
| 72 | Enum(FiscalYearStatus, native_enum=False), default=FiscalYearStatus.DRAFT |
| 73 | ) |
| 74 | company: Mapped[Company] = relationship(back_populates="fiscal_years") |
| 75 | |
| 76 | |
| 77 | class YearOwnedMixin: |
| 78 | year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True) |
| 79 | |
| 80 | |
| 81 | class SourceDocument(TimestampMixin, YearOwnedMixin, Base): |
| 82 | __tablename__ = "source_documents" |
| 83 | __table_args__ = ( |
| 84 | UniqueConstraint("year_id", "file_hash", name="uq_source_document_year_hash"), |
| 85 | ) |
| 86 | id: Mapped[int] = mapped_column(primary_key=True) |
| 87 | filename: Mapped[str] = mapped_column(String(512)) |
| 88 | file_hash: Mapped[str] = mapped_column(String(128)) |
| 89 | document_type: Mapped[str] = mapped_column(String(64)) |
| 90 | uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now) |
| 91 | |
| 92 | |
| 93 | class AccountVersion(TimestampMixin, YearOwnedMixin, Base): |
| 94 | __tablename__ = "account_versions" |
| 95 | __table_args__ = ( |
| 96 | UniqueConstraint("year_id", "account_code", "version", name="uq_account_year_code_version"), |
| 97 | CheckConstraint("version > 0", name="positive_version"), |
| 98 | ) |
| 99 | id: Mapped[int] = mapped_column(primary_key=True) |
| 100 | account_code: Mapped[str] = mapped_column(String(64), index=True) |
| 101 | account_name: Mapped[str] = mapped_column(String(512)) |
| 102 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 103 | t1: Mapped[str | None] = mapped_column(String(128)) |
| 104 | t2: Mapped[str | None] = mapped_column(String(128)) |
| 105 | t3: Mapped[str | None] = mapped_column(String(128)) |
| 106 | t4: Mapped[str | None] = mapped_column(String(128)) |
| 107 | nature: Mapped[str | None] = mapped_column(String(64)) |
| 108 | |
| 109 | |
| 110 | class NoteDefinition(TimestampMixin, YearOwnedMixin, Base): |
| 111 | __tablename__ = "note_definitions" |
| 112 | __table_args__ = ( |
| 113 | UniqueConstraint("year_id", "note_number", "version", name="uq_note_year_number_version"), |
| 114 | CheckConstraint("version > 0", name="positive_version"), |
| 115 | ) |
| 116 | id: Mapped[int] = mapped_column(primary_key=True) |
| 117 | note_number: Mapped[str] = mapped_column(String(32)) |
| 118 | title: Mapped[str] = mapped_column(String(512)) |
| 119 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 120 | configuration_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict) |
| 121 | rows: Mapped[list[NoteRow]] = relationship(back_populates="note", cascade="all, delete-orphan") |
| 122 | |
| 123 | |
| 124 | class NoteRow(TimestampMixin, Base): |
| 125 | __tablename__ = "note_rows" |
| 126 | __table_args__ = ( |
| 127 | UniqueConstraint("note_id", "row_order", name="uq_note_row_order"), |
| 128 | CheckConstraint("row_order >= 0", name="nonnegative_row_order"), |
| 129 | ) |
| 130 | id: Mapped[int] = mapped_column(primary_key=True) |
| 131 | note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True) |
| 132 | row_order: Mapped[int] = mapped_column(Integer) |
| 133 | label: Mapped[str] = mapped_column(String(512)) |
| 134 | formula_logic: Mapped[str | None] = mapped_column(Text) |
| 135 | sorting_rule_id: Mapped[str | None] = mapped_column(String(128)) |
| 136 | note: Mapped[NoteDefinition] = relationship(back_populates="rows") |
| 137 | |
| 138 | |
| 139 | class MappingRule(TimestampMixin, YearOwnedMixin, Base): |
| 140 | __tablename__ = "mapping_rules" |
| 141 | __table_args__ = ( |
| 142 | UniqueConstraint("year_id", "rule_key", "version", name="uq_mapping_year_key_version"), |
| 143 | CheckConstraint("version > 0", name="positive_version"), |
| 144 | ) |
| 145 | id: Mapped[int] = mapped_column(primary_key=True) |
| 146 | rule_key: Mapped[str] = mapped_column(String(128)) |
| 147 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 148 | account_code: Mapped[str] = mapped_column(String(64), index=True) |
| 149 | target_note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT")) |
| 150 | mapping_type: Mapped[str] = mapped_column(String(32)) |
| 151 | target_note: Mapped[NoteDefinition] = relationship() |
| 152 | |
| 153 | |
| 154 | class FinancialStatement(TimestampMixin, YearOwnedMixin, Base): |
| 155 | __tablename__ = "financial_statements" |
| 156 | __table_args__ = ( |
| 157 | UniqueConstraint("year_id", "statement_type", "version", name="uq_statement_year_type_version"), |
| 158 | CheckConstraint("version > 0", name="positive_version"), |
| 159 | ) |
| 160 | id: Mapped[int] = mapped_column(primary_key=True) |
| 161 | statement_type: Mapped[StatementType] = mapped_column(Enum(StatementType, native_enum=False)) |
| 162 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 163 | lines: Mapped[list[StatementLine]] = relationship( |
| 164 | back_populates="statement", cascade="all, delete-orphan" |
| 165 | ) |
| 166 | |
| 167 | |
| 168 | class StatementLine(TimestampMixin, Base): |
| 169 | __tablename__ = "statement_lines" |
| 170 | __table_args__ = ( |
| 171 | UniqueConstraint("statement_id", "line_order", name="uq_statement_line_order"), |
| 172 | CheckConstraint("line_order >= 0", name="nonnegative_line_order"), |
| 173 | ) |
| 174 | id: Mapped[int] = mapped_column(primary_key=True) |
| 175 | statement_id: Mapped[int] = mapped_column(ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True) |
| 176 | line_order: Mapped[int] = mapped_column(Integer) |
| 177 | line_label: Mapped[str] = mapped_column(String(512)) |
| 178 | target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT")) |
| 179 | mapped_total: Mapped[Decimal | None] = mapped_column(Numeric(24, 4)) |
| 180 | statement: Mapped[FinancialStatement] = relationship(back_populates="lines") |
| 181 | target_note: Mapped[NoteDefinition | None] = relationship() |
| 182 | |
| 183 | |
| 184 | def _resolve_parent_year_id( |
| 185 | obj: Any, session: Session, rel_attr: str, fk_attr: str, parent_cls: type[Any] |
| 186 | ) -> int | None: |
| 187 | parent = getattr(obj, rel_attr, None) |
| 188 | if parent is not None: |
| 189 | return parent.year_id |
| 190 | fk_val = getattr(obj, fk_attr, None) |
| 191 | if fk_val is not None: |
| 192 | return session.scalar(select(parent_cls.year_id).where(parent_cls.id == fk_val)) |
| 193 | return None |
| 194 | |
| 195 | |
| 196 | def _year_id_for(obj: object, session: Session) -> int | None: |
| 197 | if isinstance(obj, FiscalYear): |
| 198 | return obj.id |
| 199 | if isinstance(obj, YearOwnedMixin): |
| 200 | return obj.year_id |
| 201 | if isinstance(obj, NoteRow): |
| 202 | return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition) |
| 203 | if isinstance(obj, StatementLine): |
| 204 | return _resolve_parent_year_id(obj, session, "statement", "statement_id", FinancialStatement) |
| 205 | return None |
| 206 | |
| 207 | |
| 208 | _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED} |
| 209 | |
| 210 | |
| 211 | def _company_has_protected_year(session: Session, company_id: int) -> bool: |
| 212 | status = session.scalar( |
| 213 | select(FiscalYear.status).where( |
| 214 | FiscalYear.company_id == company_id, |
| 215 | FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES), |
| 216 | ).limit(1) |
| 217 | ) |
| 218 | return status is not None |
| 219 | |
| 220 | |
| 221 | @event.listens_for(Session, "before_flush") |
| 222 | def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None: |
| 223 | for obj in session.deleted: |
| 224 | if isinstance(obj, FiscalYear) and obj.status in _PROTECTED_YEAR_STATUSES: |
| 225 | raise ValueError( |
| 226 | f"Fiscal year {obj.id} is {obj.status.value.lower()} and cannot be deleted" |
| 227 | ) |
| 228 | |
| 229 | for obj in session.dirty: |
| 230 | if ( |
| 231 | isinstance(obj, Company) |
| 232 | and obj.id is not None |
| 233 | and _company_has_protected_year(session, obj.id) |
| 234 | ): |
| 235 | raise ValueError( |
| 236 | f"Company {obj.id} has approved or locked fiscal years and cannot be mutated" |
| 237 | ) |
| 238 | |
| 239 | if not isinstance(obj, FiscalYear): |
| 240 | continue |
| 241 | |
| 242 | state = inspect(obj) |
| 243 | status_history = state.attrs.status.history |
| 244 | old_status = status_history.deleted[0] if status_history.deleted else obj.status |
| 245 | if status_history.deleted: |
| 246 | allowed = { |
| 247 | FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED}, |
| 248 | FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED}, |
| 249 | FiscalYearStatus.LOCKED: set(), |
| 250 | } |
| 251 | if obj.status not in allowed[old_status]: |
| 252 | raise ValueError( |
| 253 | f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}" |
| 254 | ) |
| 255 | |
| 256 | protected_metadata_changed = state.attrs.company.history.has_changes() or any( |
| 257 | state.attrs[field].history.has_changes() for field in ("company_id", "year") |
| 258 | ) |
| 259 | if old_status in _PROTECTED_YEAR_STATUSES and protected_metadata_changed: |
| 260 | raise ValueError( |
| 261 | f"Fiscal year {obj.id} is {old_status.value.lower()} and its identity cannot be mutated" |
| 262 | ) |
| 263 | |
| 264 | for obj in session.deleted: |
| 265 | if ( |
| 266 | isinstance(obj, Company) |
| 267 | and obj.id is not None |
| 268 | and _company_has_protected_year(session, obj.id) |
| 269 | ): |
| 270 | raise ValueError( |
| 271 | f"Company {obj.id} has approved or locked fiscal years and cannot be deleted" |
| 272 | ) |
| 273 | |
| 274 | protected = (session.new | session.dirty | session.deleted) |
| 275 | for obj in protected: |
| 276 | if isinstance(obj, FiscalYear): |
| 277 | continue |
| 278 | year_id = _year_id_for(obj, session) |
| 279 | if year_id is None: |
| 280 | continue |
| 281 | status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id)) |
| 282 | if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}: |
| 283 | raise ValueError( |
| 284 | f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated" |
| 285 | ) |
| 286 | |
| 287 | if isinstance(obj, MappingRule): |
| 288 | target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition) |
| 289 | if target_year_id != obj.year_id: |
| 290 | raise ValueError("Mapping rule and target note must belong to the same fiscal year") |
| 291 | if isinstance(obj, StatementLine) and obj.target_note_id is not None: |
| 292 | target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition) |
| 293 | if target_year_id != year_id: |
| 294 | raise ValueError("Statement line and target note must belong to the same fiscal year") |