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

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

Synced Dec 3, 15:45 UTC

source-data-cleanup
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 465 lines 18.5 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 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 from aram_backend.domain.money import Rial
26
27
28 def utc_now() -> datetime:
29 return datetime.now(UTC)
30
31
32 class FiscalYearStatus(enum.StrEnum):
33 DRAFT = "Draft"
34 APPROVED = "Approved"
35 LOCKED = "Locked"
36
37
38 class StatementType(enum.StrEnum):
39 BALANCE_SHEET = "BS"
40 INCOME_STATEMENT = "IS"
41 CASH_FLOW = "CF"
42 EQUITY = "EQ"
43
44
45 class UserRole(enum.StrEnum):
46 """Local application roles (Phase 7, offline desktop; no runtime network).
47
48 admin: manage users, approve reopen requests, lock years, backup.
49 reviewer: approve years and reopen requests.
50 preparer: import, map, build statements, request reopen.
51 """
52
53 ADMIN = "admin"
54 REVIEWER = "reviewer"
55 PREPARER = "preparer"
56
57
58 class TimestampMixin:
59 created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
60 updated_at: Mapped[datetime] = mapped_column(
61 DateTime(timezone=True), default=utc_now, onupdate=utc_now
62 )
63
64
65 class Company(TimestampMixin, Base):
66 __tablename__ = "companies"
67 id: Mapped[int] = mapped_column(primary_key=True)
68 code: Mapped[str] = mapped_column(String(64), unique=True, index=True)
69 name: Mapped[str] = mapped_column(String(255))
70 fiscal_years: Mapped[list[FiscalYear]] = relationship(
71 back_populates="company", cascade="all, delete-orphan"
72 )
73
74
75 class FiscalYear(TimestampMixin, Base):
76 __tablename__ = "fiscal_years"
77 __table_args__ = (
78 UniqueConstraint("company_id", "year", name="uq_fiscal_year_company_year"),
79 CheckConstraint("year > 0", name="positive_year"),
80 )
81 id: Mapped[int] = mapped_column(primary_key=True)
82 company_id: Mapped[int] = mapped_column(ForeignKey("companies.id", ondelete="RESTRICT"))
83 year: Mapped[int] = mapped_column(Integer)
84 status: Mapped[FiscalYearStatus] = mapped_column(
85 Enum(FiscalYearStatus, native_enum=False), default=FiscalYearStatus.DRAFT
86 )
87 company: Mapped[Company] = relationship(back_populates="fiscal_years")
88
89
90 class YearOwnedMixin:
91 year_id: Mapped[int] = mapped_column(
92 ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True
93 )
94
95
96 class ReopenRequest(TimestampMixin, YearOwnedMixin, Base):
97 """A controlled request to reopen a LOCKED year (D-07, booklet §7).
98
99 LOCKED -> APPROVED is permitted only when an ``approved`` request exists.
100 Reopening versions the output; it never edits locked rows in place.
101 """
102
103 __tablename__ = "reopen_requests"
104 id: Mapped[int] = mapped_column(primary_key=True)
105 reason: Mapped[str] = mapped_column(Text)
106 requested_by: Mapped[str] = mapped_column(String(128), default="")
107 approved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
108 status: Mapped[str] = mapped_column(String(16), default="pending")
109
110
111 class AuditEntry(Base):
112 """Append-only, hash-chained audit log (D-07, booklet §12).
113
114 chain_hash = SHA256(previous_hash || payload_hash). UPDATE/DELETE are blocked
115 by triggers; verify_chain detects any tampering with past entries.
116 """
117
118 __tablename__ = "audit_entries"
119 id: Mapped[int] = mapped_column(primary_key=True)
120 year_id: Mapped[int | None] = mapped_column(
121 ForeignKey("fiscal_years.id", ondelete="RESTRICT"), nullable=True, index=True
122 )
123 actor: Mapped[str] = mapped_column(String(128), default="")
124 action: Mapped[str] = mapped_column(String(64))
125 payload_hash: Mapped[str] = mapped_column(String(64))
126 previous_hash: Mapped[str] = mapped_column(String(64))
127 chain_hash: Mapped[str] = mapped_column(String(64))
128 created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
129
130
131 class User(TimestampMixin, Base):
132 """Local application user with a role (Phase 7, booklet §7/§12).
133
134 Passwords are stored only as a PBKDF2-HMAC-SHA256 hash with a per-user random
135 salt (stdlib hashlib; no plaintext, no new dependency). Actions are attributed
136 to a username in the hash-chained audit log. This is an offline desktop app:
137 there is no runtime network or external identity provider.
138 """
139
140 __tablename__ = "users"
141 id: Mapped[int] = mapped_column(primary_key=True)
142 username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
143 display_name: Mapped[str] = mapped_column(String(128), default="")
144 role: Mapped[UserRole] = mapped_column(
145 Enum(UserRole, native_enum=False, length=16), default=UserRole.PREPARER
146 )
147 password_hash: Mapped[str] = mapped_column(String(128))
148 salt: Mapped[str] = mapped_column(String(64))
149 active: Mapped[bool] = mapped_column(default=True)
150
151
152 class SourceFile(TimestampMixin, Base):
153 """Content-addressed source bytes stored on disk (D-06, booklet §5).
154
155 The primary key is the SHA-256 of the bytes; ``stored_path`` points at the
156 immutable file in the content-addressed store. SourceDocument references it.
157 """
158
159 __tablename__ = "source_files"
160 sha256: Mapped[str] = mapped_column(String(64), primary_key=True)
161 size: Mapped[int] = mapped_column(Integer)
162 content_type: Mapped[str] = mapped_column(String(64), default="")
163 stored_path: Mapped[str] = mapped_column(String(512))
164
165
166 class SourceDocument(TimestampMixin, YearOwnedMixin, Base):
167 __tablename__ = "source_documents"
168 __table_args__ = (
169 UniqueConstraint("year_id", "file_hash", name="uq_source_document_year_hash"),
170 )
171 id: Mapped[int] = mapped_column(primary_key=True)
172 filename: Mapped[str] = mapped_column(String(512))
173 file_hash: Mapped[str] = mapped_column(String(128))
174 document_type: Mapped[str] = mapped_column(String(64))
175 uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
176 source_file_hash: Mapped[str | None] = mapped_column(
177 ForeignKey("source_files.sha256", ondelete="RESTRICT"), nullable=True
178 )
179
180
181 class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
182 __tablename__ = "account_versions"
183 __table_args__ = (
184 UniqueConstraint("year_id", "account_code", "version", name="uq_account_year_code_version"),
185 CheckConstraint("version > 0", name="positive_version"),
186 )
187 id: Mapped[int] = mapped_column(primary_key=True)
188 account_code: Mapped[str] = mapped_column(String(64), index=True)
189 account_name: Mapped[str] = mapped_column(String(512))
190 version: Mapped[int] = mapped_column(Integer, default=1)
191 t1: Mapped[str | None] = mapped_column(String(128))
192 t2: Mapped[str | None] = mapped_column(String(128))
193 t3: Mapped[str | None] = mapped_column(String(128))
194 t4: Mapped[str | None] = mapped_column(String(128))
195 nature: Mapped[str | None] = mapped_column(String(64))
196
197
198 class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
199 """Persisted account balance from a source ledger import (D-01, booklet §5).
200
201 Money is exact integer rial via the ``Rial`` TypeDecorator (P-02). Codes are
202 text (P-03). **One row per source ledger row** (raw, never aggregated on
203 import) so every figure drills down to its exact file/sheet/row (D3, P-01).
204 Unique per ``(year_id, source_document_id, source_row, import_version)``; a new
205 import for a Draft year creates a new version rather than mutating the prior
206 snapshot. Account-level totals are computed in the service layer.
207 """
208
209 __tablename__ = "ledger_balances"
210 __table_args__ = (
211 UniqueConstraint(
212 "year_id",
213 "source_document_id",
214 "source_row",
215 "import_version",
216 name="uq_ledger_balance_year_source_row_version",
217 ),
218 CheckConstraint("import_version > 0", name="positive_import_version"),
219 CheckConstraint("source_row > 0", name="positive_source_row"),
220 )
221 id: Mapped[int] = mapped_column(primary_key=True)
222 source_document_id: Mapped[int] = mapped_column(
223 ForeignKey("source_documents.id", ondelete="RESTRICT"), index=True
224 )
225 source_sheet: Mapped[str] = mapped_column(String(128))
226 source_row: Mapped[int] = mapped_column(Integer)
227 import_version: Mapped[int] = mapped_column(Integer, default=1)
228 account_full_code: Mapped[str] = mapped_column(String(64), index=True)
229 general_code: Mapped[str] = mapped_column(String(64), default="")
230 subsidiary_code: Mapped[str] = mapped_column(String(64), default="")
231 detail1_code: Mapped[str] = mapped_column(String(128), default="")
232 detail2_code: Mapped[str] = mapped_column(String(128), default="")
233 detail3_code: Mapped[str] = mapped_column(String(128), default="")
234 detail4_code: Mapped[str] = mapped_column(String(128), default="")
235 account_name: Mapped[str] = mapped_column(String(512))
236 opening: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
237 debit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
238 credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
239 closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
240 statement_balance: Mapped[Decimal | None] = mapped_column(Rial(), nullable=True, default=None)
241 entry_type: Mapped[str] = mapped_column(String(32), default="")
242
243
244 class NoteDefinition(TimestampMixin, YearOwnedMixin, Base):
245 __tablename__ = "note_definitions"
246 __table_args__ = (
247 UniqueConstraint("year_id", "note_number", "version", name="uq_note_year_number_version"),
248 CheckConstraint("version > 0", name="positive_version"),
249 )
250 id: Mapped[int] = mapped_column(primary_key=True)
251 note_number: Mapped[str] = mapped_column(String(32))
252 title: Mapped[str] = mapped_column(String(512))
253 version: Mapped[int] = mapped_column(Integer, default=1)
254 configuration_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
255 rows: Mapped[list[NoteRow]] = relationship(back_populates="note", cascade="all, delete-orphan")
256
257
258 class NoteRow(TimestampMixin, Base):
259 __tablename__ = "note_rows"
260 __table_args__ = (
261 UniqueConstraint("note_id", "row_order", name="uq_note_row_order"),
262 CheckConstraint("row_order >= 0", name="nonnegative_row_order"),
263 )
264 id: Mapped[int] = mapped_column(primary_key=True)
265 note_id: Mapped[int] = mapped_column(
266 ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True
267 )
268 row_order: Mapped[int] = mapped_column(Integer)
269 label: Mapped[str] = mapped_column(String(512))
270 formula_logic: Mapped[str | None] = mapped_column(Text)
271 sorting_rule_id: Mapped[str | None] = mapped_column(String(128))
272 note: Mapped[NoteDefinition] = relationship(back_populates="rows")
273
274
275 class MappingRule(TimestampMixin, YearOwnedMixin, Base):
276 __tablename__ = "mapping_rules"
277 __table_args__ = (
278 UniqueConstraint("year_id", "rule_key", "version", name="uq_mapping_year_key_version"),
279 CheckConstraint("version > 0", name="positive_version"),
280 )
281 id: Mapped[int] = mapped_column(primary_key=True)
282 rule_key: Mapped[str] = mapped_column(String(128))
283 version: Mapped[int] = mapped_column(Integer, default=1)
284 account_code: Mapped[str] = mapped_column(String(64), index=True)
285 target_note_id: Mapped[int] = mapped_column(
286 ForeignKey("note_definitions.id", ondelete="RESTRICT")
287 )
288 mapping_type: Mapped[str] = mapped_column(String(32))
289 target_note: Mapped[NoteDefinition] = relationship()
290
291
292 class FinancialStatement(TimestampMixin, YearOwnedMixin, Base):
293 __tablename__ = "financial_statements"
294 __table_args__ = (
295 UniqueConstraint(
296 "year_id", "statement_type", "version", name="uq_statement_year_type_version"
297 ),
298 CheckConstraint("version > 0", name="positive_version"),
299 )
300 id: Mapped[int] = mapped_column(primary_key=True)
301 statement_type: Mapped[StatementType] = mapped_column(Enum(StatementType, native_enum=False))
302 version: Mapped[int] = mapped_column(Integer, default=1)
303 lines: Mapped[list[StatementLine]] = relationship(
304 back_populates="statement", cascade="all, delete-orphan"
305 )
306
307
308 class StatementLine(TimestampMixin, Base):
309 __tablename__ = "statement_lines"
310 __table_args__ = (
311 UniqueConstraint("statement_id", "line_order", name="uq_statement_line_order"),
312 CheckConstraint("line_order >= 0", name="nonnegative_line_order"),
313 )
314 id: Mapped[int] = mapped_column(primary_key=True)
315 statement_id: Mapped[int] = mapped_column(
316 ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True
317 )
318 line_order: Mapped[int] = mapped_column(Integer)
319 line_label: Mapped[str] = mapped_column(String(512))
320 target_note_id: Mapped[int | None] = mapped_column(
321 ForeignKey("note_definitions.id", ondelete="RESTRICT")
322 )
323 mapped_total: Mapped[Decimal | None] = mapped_column(Rial())
324 statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
325 target_note: Mapped[NoteDefinition | None] = relationship()
326
327
328 def _resolve_parent_year_id(
329 obj: Any, session: Session, rel_attr: str, fk_attr: str, parent_cls: type[Any]
330 ) -> int | None:
331 parent = getattr(obj, rel_attr, None)
332 if parent is not None:
333 return parent.year_id
334 fk_val = getattr(obj, fk_attr, None)
335 if fk_val is not None:
336 return session.scalar(select(parent_cls.year_id).where(parent_cls.id == fk_val))
337 return None
338
339
340 def _year_id_for(obj: object, session: Session) -> int | None:
341 if isinstance(obj, FiscalYear):
342 return obj.id
343 if isinstance(obj, YearOwnedMixin):
344 return obj.year_id
345 if isinstance(obj, NoteRow):
346 return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition)
347 if isinstance(obj, StatementLine):
348 return _resolve_parent_year_id(
349 obj, session, "statement", "statement_id", FinancialStatement
350 )
351 return None
352
353
354 _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
355
356
357 def _company_has_protected_year(session: Session, company_id: int) -> bool:
358 status = session.scalar(
359 select(FiscalYear.status)
360 .where(
361 FiscalYear.company_id == company_id,
362 FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES),
363 )
364 .limit(1)
365 )
366 return status is not None
367
368
369 @event.listens_for(Session, "before_flush")
370 def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None:
371 for obj in session.deleted:
372 if isinstance(obj, FiscalYear) and obj.status in _PROTECTED_YEAR_STATUSES:
373 raise ValueError(
374 f"Fiscal year {obj.id} is {obj.status.value.lower()} and cannot be deleted"
375 )
376
377 for obj in session.dirty:
378 if (
379 isinstance(obj, Company)
380 and obj.id is not None
381 and _company_has_protected_year(session, obj.id)
382 ):
383 raise ValueError(
384 f"Company {obj.id} has approved or locked fiscal years and cannot be mutated"
385 )
386
387 if not isinstance(obj, FiscalYear):
388 continue
389
390 state = inspect(obj)
391 status_history = state.attrs.status.history
392 old_status = status_history.deleted[0] if status_history.deleted else obj.status
393 if status_history.deleted:
394 allowed = {
395 FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
396 FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
397 FiscalYearStatus.LOCKED: {FiscalYearStatus.APPROVED},
398 }
399 if obj.status not in allowed[old_status]:
400 raise ValueError(
401 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
402 )
403 if old_status == FiscalYearStatus.LOCKED and obj.status == FiscalYearStatus.APPROVED:
404 approved_reopen = session.scalar(
405 select(ReopenRequest.id)
406 .where(
407 ReopenRequest.year_id == obj.id,
408 ReopenRequest.status == "approved",
409 )
410 .limit(1)
411 )
412 if approved_reopen is None:
413 raise ValueError(
414 f"Fiscal year {obj.id} is locked; reopening requires an approved ReopenRequest"
415 )
416
417 protected_metadata_changed = state.attrs.company.history.has_changes() or any(
418 state.attrs[field].history.has_changes() for field in ("company_id", "year")
419 )
420 if old_status in _PROTECTED_YEAR_STATUSES and protected_metadata_changed:
421 raise ValueError(
422 f"Fiscal year {obj.id} is {old_status.value.lower()} and its identity cannot be mutated"
423 )
424
425 for obj in session.deleted:
426 if (
427 isinstance(obj, Company)
428 and obj.id is not None
429 and _company_has_protected_year(session, obj.id)
430 ):
431 raise ValueError(
432 f"Company {obj.id} has approved or locked fiscal years and cannot be deleted"
433 )
434
435 protected = session.new | session.dirty | session.deleted
436 for obj in protected:
437 if isinstance(obj, FiscalYear):
438 continue
439 # A ReopenRequest is the authorized mechanism to act on a locked year
440 # (ADR-016); creating/approving it must not be blocked by the year guard.
441 if isinstance(obj, ReopenRequest):
442 continue
443 year_id = _year_id_for(obj, session)
444 if year_id is None:
445 continue
446 status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
447 if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}:
448 raise ValueError(
449 f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated"
450 )
451
452 if isinstance(obj, MappingRule):
453 target_year_id = _resolve_parent_year_id(
454 obj, session, "target_note", "target_note_id", NoteDefinition
455 )
456 if target_year_id != obj.year_id:
457 raise ValueError("Mapping rule and target note must belong to the same fiscal year")
458 if isinstance(obj, StatementLine) and obj.target_note_id is not None:
459 target_year_id = _resolve_parent_year_id(
460 obj, session, "target_note", "target_note_id", NoteDefinition
461 )
462 if target_year_id != year_id:
463 raise ValueError(
464 "Statement line and target note must belong to the same fiscal year"
465 )