jules-gate-2b-mapping-workflow-foundation-4137724387867065330
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 | import enum |
| 3 | from datetime import datetime, timezone |
| 4 | from decimal import Decimal |
| 5 | from typing import Any |
| 6 | |
| 7 | from sqlalchemy import ( |
| 8 | JSON, |
| 9 | CheckConstraint, |
| 10 | DateTime, |
| 11 | Enum, |
| 12 | ForeignKey, |
| 13 | Integer, |
| 14 | Numeric, |
| 15 | String, |
| 16 | Text, |
| 17 | UniqueConstraint, |
| 18 | event, |
| 19 | inspect, |
| 20 | select, |
| 21 | ) |
| 22 | from sqlalchemy.orm import Mapped, Session, mapped_column, relationship |
| 23 | |
| 24 | from aram_backend.database import Base |
| 25 | |
| 26 | |
| 27 | def utc_now() -> datetime: |
| 28 | return datetime.now(timezone.utc) |
| 29 | |
| 30 | |
| 31 | class FiscalYearStatus(str, enum.Enum): |
| 32 | DRAFT = "Draft" |
| 33 | APPROVED = "Approved" |
| 34 | LOCKED = "Locked" |
| 35 | |
| 36 | |
| 37 | class MappingStatus(str, enum.Enum): |
| 38 | DRAFT = "Draft" |
| 39 | PROPOSED = "Proposed" |
| 40 | ACTIVE = "Active" |
| 41 | RETIRED = "Retired" |
| 42 | |
| 43 | |
| 44 | class StatementType(str, enum.Enum): |
| 45 | BALANCE_SHEET = "BS" |
| 46 | INCOME_STATEMENT = "IS" |
| 47 | CASH_FLOW = "CF" |
| 48 | EQUITY = "EQ" |
| 49 | |
| 50 | |
| 51 | class TimestampMixin: |
| 52 | created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now) |
| 53 | updated_at: Mapped[datetime] = mapped_column( |
| 54 | DateTime(timezone=True), default=utc_now, onupdate=utc_now |
| 55 | ) |
| 56 | |
| 57 | |
| 58 | class Company(TimestampMixin, Base): |
| 59 | __tablename__ = "companies" |
| 60 | id: Mapped[int] = mapped_column(primary_key=True) |
| 61 | code: Mapped[str] = mapped_column(String(64), unique=True, index=True) |
| 62 | name: Mapped[str] = mapped_column(String(255)) |
| 63 | fiscal_years: Mapped[list["FiscalYear"]] = relationship( |
| 64 | back_populates="company", cascade="all, delete-orphan" |
| 65 | ) |
| 66 | |
| 67 | |
| 68 | class FiscalYear(TimestampMixin, Base): |
| 69 | __tablename__ = "fiscal_years" |
| 70 | __table_args__ = ( |
| 71 | UniqueConstraint("company_id", "year", name="uq_fiscal_year_company_year"), |
| 72 | CheckConstraint("year > 0", name="positive_year"), |
| 73 | ) |
| 74 | id: Mapped[int] = mapped_column(primary_key=True) |
| 75 | company_id: Mapped[int] = mapped_column(ForeignKey("companies.id", ondelete="RESTRICT")) |
| 76 | year: Mapped[int] = mapped_column(Integer) |
| 77 | status: Mapped[FiscalYearStatus] = mapped_column( |
| 78 | Enum(FiscalYearStatus, native_enum=False), default=FiscalYearStatus.DRAFT |
| 79 | ) |
| 80 | company: Mapped[Company] = relationship(back_populates="fiscal_years") |
| 81 | |
| 82 | |
| 83 | class YearOwnedMixin: |
| 84 | year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True) |
| 85 | |
| 86 | |
| 87 | class SourceDocument(TimestampMixin, YearOwnedMixin, Base): |
| 88 | __tablename__ = "source_documents" |
| 89 | __table_args__ = ( |
| 90 | UniqueConstraint("year_id", "file_hash", name="uq_source_document_year_hash"), |
| 91 | ) |
| 92 | id: Mapped[int] = mapped_column(primary_key=True) |
| 93 | filename: Mapped[str] = mapped_column(String(512)) |
| 94 | file_hash: Mapped[str] = mapped_column(String(128)) |
| 95 | document_type: Mapped[str] = mapped_column(String(64)) |
| 96 | uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now) |
| 97 | |
| 98 | |
| 99 | class AccountVersion(TimestampMixin, YearOwnedMixin, Base): |
| 100 | __tablename__ = "account_versions" |
| 101 | __table_args__ = ( |
| 102 | UniqueConstraint("year_id", "account_code", "version", name="uq_account_year_code_version"), |
| 103 | CheckConstraint("version > 0", name="positive_version"), |
| 104 | ) |
| 105 | id: Mapped[int] = mapped_column(primary_key=True) |
| 106 | account_code: Mapped[str] = mapped_column(String(64), index=True) |
| 107 | account_name: Mapped[str] = mapped_column(String(512)) |
| 108 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 109 | t1: Mapped[str | None] = mapped_column(String(128)) |
| 110 | t2: Mapped[str | None] = mapped_column(String(128)) |
| 111 | t3: Mapped[str | None] = mapped_column(String(128)) |
| 112 | t4: Mapped[str | None] = mapped_column(String(128)) |
| 113 | nature: Mapped[str | None] = mapped_column(String(64)) |
| 114 | |
| 115 | |
| 116 | class NoteDefinition(TimestampMixin, YearOwnedMixin, Base): |
| 117 | __tablename__ = "note_definitions" |
| 118 | __table_args__ = ( |
| 119 | UniqueConstraint("year_id", "note_number", "version", name="uq_note_year_number_version"), |
| 120 | CheckConstraint("version > 0", name="positive_version"), |
| 121 | ) |
| 122 | id: Mapped[int] = mapped_column(primary_key=True) |
| 123 | note_number: Mapped[str] = mapped_column(String(32)) |
| 124 | title: Mapped[str] = mapped_column(String(512)) |
| 125 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 126 | configuration_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict) |
| 127 | rows: Mapped[list["NoteRow"]] = relationship(back_populates="note", cascade="all, delete-orphan") |
| 128 | |
| 129 | |
| 130 | class NoteRow(TimestampMixin, Base): |
| 131 | __tablename__ = "note_rows" |
| 132 | __table_args__ = ( |
| 133 | UniqueConstraint("note_id", "row_order", name="uq_note_row_order"), |
| 134 | CheckConstraint("row_order >= 0", name="nonnegative_row_order"), |
| 135 | ) |
| 136 | id: Mapped[int] = mapped_column(primary_key=True) |
| 137 | note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True) |
| 138 | row_order: Mapped[int] = mapped_column(Integer) |
| 139 | label: Mapped[str] = mapped_column(String(512)) |
| 140 | formula_logic: Mapped[str | None] = mapped_column(Text) |
| 141 | sorting_rule_id: Mapped[str | None] = mapped_column(String(128)) |
| 142 | note: Mapped[NoteDefinition] = relationship(back_populates="rows") |
| 143 | |
| 144 | |
| 145 | class MappingRule(TimestampMixin, YearOwnedMixin, Base): |
| 146 | __tablename__ = "mapping_rules" |
| 147 | __table_args__ = ( |
| 148 | UniqueConstraint("year_id", "rule_key", "version", name="uq_mapping_year_key_version"), |
| 149 | CheckConstraint("version > 0", name="positive_version"), |
| 150 | ) |
| 151 | id: Mapped[int] = mapped_column(primary_key=True) |
| 152 | rule_key: Mapped[str] = mapped_column(String(128)) |
| 153 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 154 | account_code: Mapped[str] = mapped_column(String(64), index=True) |
| 155 | target_note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT")) |
| 156 | mapping_type: Mapped[str] = mapped_column(String(32)) |
| 157 | status: Mapped[MappingStatus] = mapped_column( |
| 158 | Enum(MappingStatus, native_enum=False), default=MappingStatus.DRAFT |
| 159 | ) |
| 160 | target_note: Mapped[NoteDefinition] = relationship() |
| 161 | |
| 162 | |
| 163 | class FinancialStatement(TimestampMixin, YearOwnedMixin, Base): |
| 164 | __tablename__ = "financial_statements" |
| 165 | __table_args__ = ( |
| 166 | UniqueConstraint("year_id", "statement_type", "version", name="uq_statement_year_type_version"), |
| 167 | CheckConstraint("version > 0", name="positive_version"), |
| 168 | ) |
| 169 | id: Mapped[int] = mapped_column(primary_key=True) |
| 170 | statement_type: Mapped[StatementType] = mapped_column(Enum(StatementType, native_enum=False)) |
| 171 | version: Mapped[int] = mapped_column(Integer, default=1) |
| 172 | lines: Mapped[list["StatementLine"]] = relationship( |
| 173 | back_populates="statement", cascade="all, delete-orphan" |
| 174 | ) |
| 175 | |
| 176 | |
| 177 | class StatementLine(TimestampMixin, Base): |
| 178 | __tablename__ = "statement_lines" |
| 179 | __table_args__ = ( |
| 180 | UniqueConstraint("statement_id", "line_order", name="uq_statement_line_order"), |
| 181 | CheckConstraint("line_order >= 0", name="nonnegative_line_order"), |
| 182 | ) |
| 183 | id: Mapped[int] = mapped_column(primary_key=True) |
| 184 | statement_id: Mapped[int] = mapped_column(ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True) |
| 185 | line_order: Mapped[int] = mapped_column(Integer) |
| 186 | line_label: Mapped[str] = mapped_column(String(512)) |
| 187 | target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT")) |
| 188 | mapped_total: Mapped[Decimal | None] = mapped_column(Numeric(24, 4)) |
| 189 | statement: Mapped[FinancialStatement] = relationship(back_populates="lines") |
| 190 | target_note: Mapped[NoteDefinition | None] = relationship() |
| 191 | |
| 192 | |
| 193 | def _resolve_parent_year_id( |
| 194 | obj: Any, session: Session, rel_attr: str, fk_attr: str, parent_cls: type[Any] |
| 195 | ) -> int | None: |
| 196 | parent = getattr(obj, rel_attr, None) |
| 197 | if parent is not None: |
| 198 | return parent.year_id |
| 199 | fk_val = getattr(obj, fk_attr, None) |
| 200 | if fk_val is not None: |
| 201 | return session.scalar(select(parent_cls.year_id).where(parent_cls.id == fk_val)) |
| 202 | return None |
| 203 | |
| 204 | |
| 205 | def _year_id_for(obj: object, session: Session) -> int | None: |
| 206 | if isinstance(obj, FiscalYear): |
| 207 | return obj.id |
| 208 | if isinstance(obj, YearOwnedMixin): |
| 209 | return obj.year_id |
| 210 | if isinstance(obj, NoteRow): |
| 211 | return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition) |
| 212 | if isinstance(obj, StatementLine): |
| 213 | return _resolve_parent_year_id(obj, session, "statement", "statement_id", FinancialStatement) |
| 214 | return None |
| 215 | |
| 216 | |
| 217 | @event.listens_for(Session, "before_flush") |
| 218 | def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None: |
| 219 | for obj in session.dirty: |
| 220 | if isinstance(obj, FiscalYear): |
| 221 | history = inspect(obj).attrs.status.history |
| 222 | if history.deleted: |
| 223 | old = history.deleted[0] |
| 224 | allowed = { |
| 225 | FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED}, |
| 226 | FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED}, |
| 227 | FiscalYearStatus.LOCKED: set(), |
| 228 | } |
| 229 | if obj.status not in allowed[old]: |
| 230 | raise ValueError(f"Invalid fiscal-year transition: {old.value} -> {obj.status.value}") |
| 231 | |
| 232 | if isinstance(obj, MappingRule): |
| 233 | history = inspect(obj).attrs.status.history |
| 234 | if history.deleted: |
| 235 | old = history.deleted[0] |
| 236 | allowed = { |
| 237 | MappingStatus.DRAFT: {MappingStatus.PROPOSED, MappingStatus.RETIRED}, |
| 238 | MappingStatus.PROPOSED: {MappingStatus.ACTIVE, MappingStatus.DRAFT, MappingStatus.RETIRED}, |
| 239 | MappingStatus.ACTIVE: {MappingStatus.RETIRED}, |
| 240 | MappingStatus.RETIRED: set(), |
| 241 | } |
| 242 | if obj.status not in allowed[old]: |
| 243 | raise ValueError(f"Invalid mapping transition: {old.value} -> {obj.status.value}") |
| 244 | |
| 245 | protected = (session.new | session.dirty | session.deleted) |
| 246 | for obj in protected: |
| 247 | if isinstance(obj, FiscalYear): |
| 248 | continue |
| 249 | year_id = _year_id_for(obj, session) |
| 250 | if year_id is None: |
| 251 | continue |
| 252 | status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id)) |
| 253 | if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}: |
| 254 | raise ValueError( |
| 255 | f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated" |
| 256 | ) |
| 257 | |
| 258 | if isinstance(obj, MappingRule): |
| 259 | target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition) |
| 260 | if target_year_id != obj.year_id: |
| 261 | raise ValueError("Mapping rule and target note must belong to the same fiscal year") |
| 262 | if isinstance(obj, StatementLine) and obj.target_note_id is not None: |
| 263 | target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition) |
| 264 | if target_year_id != year_id: |
| 265 | raise ValueError("Statement line and target note must belong to the same fiscal year") |