@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 23:15 UTC

codex/aram-clean-reference-year-integrity-20261030
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
py 428 lines 17.1 KB
Raw
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 state = inspect(obj)
188 relationship_history = state.attrs[rel_attr].history
189 foreign_key_history = state.attrs[fk_attr].history
190 fk_val = getattr(obj, fk_attr, None)
191 if relationship_history.has_changes():
192 parent = getattr(obj, rel_attr, None)
193 parent_id = parent.id if parent is not None else None
194 if foreign_key_history.has_changes() and fk_val != parent_id:
195 raise ValueError(f"Conflicting {rel_attr} relationship and {fk_attr}")
196 elif fk_val is not None:
197 # A raw FK assignment does not invalidate an already cached relationship.
198 parent = session.get(parent_cls, fk_val)
199 if parent is None:
200 # Pending explicit-ID parents are not in the Session identity map yet.
201 parent = next(
202 (
203 candidate for candidate in session.new
204 if isinstance(candidate, parent_cls) and candidate.id == fk_val
205 ),
206 None,
207 )
208 else:
209 parent = None
210 return parent.year_id if parent is not None else None
211
212
213 def _year_id_for(obj: object, session: Session) -> int | None:
214 if isinstance(obj, FiscalYear):
215 return obj.id
216 if isinstance(obj, YearOwnedMixin):
217 return obj.year_id
218 if isinstance(obj, NoteRow):
219 return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition)
220 if isinstance(obj, StatementLine):
221 return _resolve_parent_year_id(obj, session, "statement", "statement_id", FinancialStatement)
222 return None
223
224
225 def _persisted_year_id_for(obj: Any, session: Session) -> int | None:
226 """Read original ownership before flush, even when attributes are expired."""
227 identity = inspect(obj).identity
228 if identity is None:
229 return None
230 if isinstance(obj, YearOwnedMixin):
231 model = type(obj)
232 query = select(model.year_id).where(model.id == identity[0])
233 elif isinstance(obj, NoteRow):
234 query = (
235 select(NoteDefinition.year_id)
236 .join(NoteRow, NoteRow.note_id == NoteDefinition.id)
237 .where(NoteRow.id == identity[0])
238 )
239 elif isinstance(obj, StatementLine):
240 query = (
241 select(FinancialStatement.year_id)
242 .join(StatementLine, StatementLine.statement_id == FinancialStatement.id)
243 .where(StatementLine.id == identity[0])
244 )
245 else:
246 return None
247 return session.scalar(query)
248
249
250 def _check_clean_references_after_parent_year_move(session: Session, parent: Any) -> None:
251 """Reject cross-year links hidden in unchanged dependent ORM rows.
252
253 This guard is only for persisted NoteDefinition and FinancialStatement
254 ownership moves. References already modified or newly created are checked
255 by the main before_flush invariant below; here we additionally inspect
256 existing rows whose foreign keys point at the moved parent.
257 """
258 if inspect(parent).identity is None:
259 return
260 if parent.year_id == _persisted_year_id_for(parent, session):
261 return
262
263 if isinstance(parent, NoteDefinition):
264 for rule in session.scalars(
265 select(MappingRule).where(MappingRule.target_note_id == parent.id)
266 ):
267 if rule in session.deleted:
268 continue
269 target_year = _resolve_parent_year_id(
270 rule, session, "target_note", "target_note_id", NoteDefinition
271 )
272 if target_year != rule.year_id:
273 raise ValueError(
274 "Mapping rule and target note must belong to the same fiscal year"
275 )
276
277 for line in session.scalars(
278 select(StatementLine).where(StatementLine.target_note_id == parent.id)
279 ):
280 if line in session.deleted:
281 continue
282 statement_year = _year_id_for(line, session)
283 target_year = _resolve_parent_year_id(
284 line, session, "target_note", "target_note_id", NoteDefinition
285 )
286 if target_year is not None and target_year != statement_year:
287 raise ValueError(
288 "Statement line and target note must belong to the same fiscal year"
289 )
290
291 if isinstance(parent, FinancialStatement):
292 for line in session.scalars(
293 select(StatementLine).where(StatementLine.statement_id == parent.id)
294 ):
295 if line in session.deleted:
296 continue
297 statement_year = _year_id_for(line, session)
298 target_year = _resolve_parent_year_id(
299 line, session, "target_note", "target_note_id", NoteDefinition
300 )
301 if target_year is not None and target_year != statement_year:
302 raise ValueError(
303 "Statement line and target note must belong to the same fiscal year"
304 )
305
306
307 _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
308
309
310 def _protected_year_status(session: Session, year_id: int) -> FiscalYearStatus | None:
311 """Protect both persisted status and an in-flight approval/locking transition.
312
313 A database SELECT alone sees Draft until the pending FiscalYear status is
314 flushed, allowing a second dirty object to change in the approval flush.
315 """
316 for candidate in session.new | session.dirty | session.deleted:
317 if (
318 isinstance(candidate, FiscalYear)
319 and candidate.id == year_id
320 and candidate.status in _PROTECTED_YEAR_STATUSES
321 ):
322 return candidate.status
323
324 persisted = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
325 return persisted if persisted in _PROTECTED_YEAR_STATUSES else None
326
327
328
329 def _company_has_protected_year(session: Session, company_id: int) -> bool:
330 # A Company edit in the same transaction as Draft -> Approved is forbidden.
331 for candidate in session.new | session.dirty:
332 if isinstance(candidate, FiscalYear) and candidate.status in _PROTECTED_YEAR_STATUSES:
333 linked_id = candidate.company_id
334 if linked_id is None and candidate.company is not None:
335 linked_id = candidate.company.id
336 if linked_id == company_id:
337 return True
338
339 status = session.scalar(
340 select(FiscalYear.status).where(
341 FiscalYear.company_id == company_id,
342 FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES),
343 ).limit(1)
344 )
345 return status is not None
346
347
348 @event.listens_for(Session, "before_flush")
349 def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None:
350 for obj in session.deleted:
351 if isinstance(obj, FiscalYear) and obj.status in _PROTECTED_YEAR_STATUSES:
352 raise ValueError(
353 f"Fiscal year {obj.id} is {obj.status.value.lower()} and cannot be deleted"
354 )
355
356 for obj in session.dirty:
357 if (
358 isinstance(obj, Company)
359 and obj.id is not None
360 and _company_has_protected_year(session, obj.id)
361 ):
362 raise ValueError(
363 f"Company {obj.id} has approved or locked fiscal years and cannot be mutated"
364 )
365
366 if not isinstance(obj, FiscalYear):
367 continue
368
369 state = inspect(obj)
370 status_history = state.attrs.status.history
371 old_status = status_history.deleted[0] if status_history.deleted else obj.status
372 if status_history.deleted:
373 allowed = {
374 FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
375 FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
376 FiscalYearStatus.LOCKED: set(),
377 }
378 if obj.status not in allowed[old_status]:
379 raise ValueError(
380 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
381 )
382
383 protected_metadata_changed = state.attrs.company.history.has_changes() or any(
384 state.attrs[field].history.has_changes() for field in ("company_id", "year")
385 )
386 if old_status in _PROTECTED_YEAR_STATUSES and protected_metadata_changed:
387 raise ValueError(
388 f"Fiscal year {obj.id} is {old_status.value.lower()} and its identity cannot be mutated"
389 )
390
391 for obj in session.deleted:
392 if (
393 isinstance(obj, Company)
394 and obj.id is not None
395 and _company_has_protected_year(session, obj.id)
396 ):
397 raise ValueError(
398 f"Company {obj.id} has approved or locked fiscal years and cannot be deleted"
399 )
400
401 protected = (session.new | session.dirty | session.deleted)
402 for obj in protected:
403 if isinstance(obj, FiscalYear):
404 continue
405 year_id = _year_id_for(obj, session)
406 original_year_id = _persisted_year_id_for(obj, session)
407 for affected_year_id in {year_id, original_year_id} - {None}:
408 status = _protected_year_status(session, affected_year_id)
409 if status is not None:
410 raise ValueError(
411 f"Fiscal year {affected_year_id} is {status.value.lower()} and cannot be mutated"
412 )
413 if year_id is None:
414 continue
415
416 if isinstance(obj, MappingRule):
417 target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
418 if target_year_id != obj.year_id:
419 raise ValueError("Mapping rule and target note must belong to the same fiscal year")
420 if isinstance(obj, StatementLine):
421 target_year_id = _resolve_parent_year_id(obj, session, "target_note", "target_note_id", NoteDefinition)
422 if target_year_id is not None and target_year_id != year_id:
423 raise ValueError("Statement line and target note must belong to the same fiscal year")
424
425 # Parent moves may invalidate clean child rows that never enter session.dirty.
426 for parent in session.dirty:
427 if isinstance(parent, (NoteDefinition, FinancialStatement)):
428 _check_clean_references_after_parent_year_move(session, parent)