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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/setup-node-6
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-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 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 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 489 lines 19.8 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 # R1 (booklet 2.1): PBKDF2 work factor stored per user so legacy hashes can be
151 # verified and transparently rehashed to the current target on first login.
152 password_rounds: Mapped[int] = mapped_column(Integer, default=600_000)
153 failed_login_count: Mapped[int] = mapped_column(Integer, default=0)
154 locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
155
156
157 class AuthSession(TimestampMixin, Base):
158 """Server-side login session (R1, booklet 2.1).
159
160 Only the SHA-256 hash of the random 256-bit bearer token is stored; the
161 plaintext token is returned to the client exactly once at login. Identity is
162 derived from this table, never from a client-supplied ``actor`` string.
163 """
164
165 __tablename__ = "auth_sessions"
166 id: Mapped[int] = mapped_column(primary_key=True)
167 user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
168 token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
169 expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
170 revoked: Mapped[bool] = mapped_column(default=False)
171
172
173 class SourceFile(TimestampMixin, Base):
174 """Content-addressed source bytes stored on disk (D-06, booklet §5).
175
176 The primary key is the SHA-256 of the bytes; ``stored_path`` points at the
177 immutable file in the content-addressed store. SourceDocument references it.
178 """
179
180 __tablename__ = "source_files"
181 sha256: Mapped[str] = mapped_column(String(64), primary_key=True)
182 size: Mapped[int] = mapped_column(Integer)
183 content_type: Mapped[str] = mapped_column(String(64), default="")
184 stored_path: Mapped[str] = mapped_column(String(512))
185
186
187 class SourceDocument(TimestampMixin, YearOwnedMixin, Base):
188 __tablename__ = "source_documents"
189 __table_args__ = (
190 UniqueConstraint("year_id", "file_hash", name="uq_source_document_year_hash"),
191 )
192 id: Mapped[int] = mapped_column(primary_key=True)
193 filename: Mapped[str] = mapped_column(String(512))
194 file_hash: Mapped[str] = mapped_column(String(128))
195 document_type: Mapped[str] = mapped_column(String(64))
196 uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
197 source_file_hash: Mapped[str | None] = mapped_column(
198 ForeignKey("source_files.sha256", ondelete="RESTRICT"), nullable=True
199 )
200
201
202 class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
203 __tablename__ = "account_versions"
204 __table_args__ = (
205 UniqueConstraint("year_id", "account_code", "version", name="uq_account_year_code_version"),
206 CheckConstraint("version > 0", name="positive_version"),
207 )
208 id: Mapped[int] = mapped_column(primary_key=True)
209 account_code: Mapped[str] = mapped_column(String(64), index=True)
210 account_name: Mapped[str] = mapped_column(String(512))
211 version: Mapped[int] = mapped_column(Integer, default=1)
212 t1: Mapped[str | None] = mapped_column(String(128))
213 t2: Mapped[str | None] = mapped_column(String(128))
214 t3: Mapped[str | None] = mapped_column(String(128))
215 t4: Mapped[str | None] = mapped_column(String(128))
216 nature: Mapped[str | None] = mapped_column(String(64))
217
218
219 class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
220 """Persisted account balance from a source ledger import (D-01, booklet §5).
221
222 Money is exact integer rial via the ``Rial`` TypeDecorator (P-02). Codes are
223 text (P-03). **One row per source ledger row** (raw, never aggregated on
224 import) so every figure drills down to its exact file/sheet/row (D3, P-01).
225 Unique per ``(year_id, source_document_id, source_row, import_version)``; a new
226 import for a Draft year creates a new version rather than mutating the prior
227 snapshot. Account-level totals are computed in the service layer.
228 """
229
230 __tablename__ = "ledger_balances"
231 __table_args__ = (
232 UniqueConstraint(
233 "year_id",
234 "source_document_id",
235 "source_row",
236 "import_version",
237 name="uq_ledger_balance_year_source_row_version",
238 ),
239 CheckConstraint("import_version > 0", name="positive_import_version"),
240 CheckConstraint("source_row > 0", name="positive_source_row"),
241 )
242 id: Mapped[int] = mapped_column(primary_key=True)
243 source_document_id: Mapped[int] = mapped_column(
244 ForeignKey("source_documents.id", ondelete="RESTRICT"), index=True
245 )
246 source_sheet: Mapped[str] = mapped_column(String(128))
247 source_row: Mapped[int] = mapped_column(Integer)
248 import_version: Mapped[int] = mapped_column(Integer, default=1)
249 account_full_code: Mapped[str] = mapped_column(String(64), index=True)
250 general_code: Mapped[str] = mapped_column(String(64), default="")
251 subsidiary_code: Mapped[str] = mapped_column(String(64), default="")
252 detail1_code: Mapped[str] = mapped_column(String(128), default="")
253 detail2_code: Mapped[str] = mapped_column(String(128), default="")
254 detail3_code: Mapped[str] = mapped_column(String(128), default="")
255 detail4_code: Mapped[str] = mapped_column(String(128), default="")
256 account_name: Mapped[str] = mapped_column(String(512))
257 opening: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
258 debit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
259 credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
260 closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
261 statement_balance: Mapped[Decimal | None] = mapped_column(Rial(), nullable=True, default=None)
262 # Note assigned by the source row itself (R3): one account may feed several
263 # notes, so the row's own assignment must survive the import.
264 source_note: Mapped[str] = mapped_column(String(32), default="", server_default="")
265 entry_type: Mapped[str] = mapped_column(String(32), default="")
266
267
268 class NoteDefinition(TimestampMixin, YearOwnedMixin, Base):
269 __tablename__ = "note_definitions"
270 __table_args__ = (
271 UniqueConstraint("year_id", "note_number", "version", name="uq_note_year_number_version"),
272 CheckConstraint("version > 0", name="positive_version"),
273 )
274 id: Mapped[int] = mapped_column(primary_key=True)
275 note_number: Mapped[str] = mapped_column(String(32))
276 title: Mapped[str] = mapped_column(String(512))
277 version: Mapped[int] = mapped_column(Integer, default=1)
278 configuration_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
279 rows: Mapped[list[NoteRow]] = relationship(back_populates="note", cascade="all, delete-orphan")
280
281
282 class NoteRow(TimestampMixin, Base):
283 __tablename__ = "note_rows"
284 __table_args__ = (
285 UniqueConstraint("note_id", "row_order", name="uq_note_row_order"),
286 CheckConstraint("row_order >= 0", name="nonnegative_row_order"),
287 )
288 id: Mapped[int] = mapped_column(primary_key=True)
289 note_id: Mapped[int] = mapped_column(
290 ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True
291 )
292 row_order: Mapped[int] = mapped_column(Integer)
293 label: Mapped[str] = mapped_column(String(512))
294 formula_logic: Mapped[str | None] = mapped_column(Text)
295 sorting_rule_id: Mapped[str | None] = mapped_column(String(128))
296 note: Mapped[NoteDefinition] = relationship(back_populates="rows")
297
298
299 class MappingRule(TimestampMixin, YearOwnedMixin, Base):
300 __tablename__ = "mapping_rules"
301 __table_args__ = (
302 UniqueConstraint("year_id", "rule_key", "version", name="uq_mapping_year_key_version"),
303 CheckConstraint("version > 0", name="positive_version"),
304 )
305 id: Mapped[int] = mapped_column(primary_key=True)
306 rule_key: Mapped[str] = mapped_column(String(128))
307 version: Mapped[int] = mapped_column(Integer, default=1)
308 account_code: Mapped[str] = mapped_column(String(64), index=True)
309 target_note_id: Mapped[int] = mapped_column(
310 ForeignKey("note_definitions.id", ondelete="RESTRICT")
311 )
312 mapping_type: Mapped[str] = mapped_column(String(32))
313 target_note: Mapped[NoteDefinition] = relationship()
314
315
316 class FinancialStatement(TimestampMixin, YearOwnedMixin, Base):
317 __tablename__ = "financial_statements"
318 __table_args__ = (
319 UniqueConstraint(
320 "year_id", "statement_type", "version", name="uq_statement_year_type_version"
321 ),
322 CheckConstraint("version > 0", name="positive_version"),
323 )
324 id: Mapped[int] = mapped_column(primary_key=True)
325 statement_type: Mapped[StatementType] = mapped_column(Enum(StatementType, native_enum=False))
326 version: Mapped[int] = mapped_column(Integer, default=1)
327 lines: Mapped[list[StatementLine]] = relationship(
328 back_populates="statement", cascade="all, delete-orphan"
329 )
330
331
332 class StatementLine(TimestampMixin, Base):
333 __tablename__ = "statement_lines"
334 __table_args__ = (
335 UniqueConstraint("statement_id", "line_order", name="uq_statement_line_order"),
336 CheckConstraint("line_order >= 0", name="nonnegative_line_order"),
337 )
338 id: Mapped[int] = mapped_column(primary_key=True)
339 statement_id: Mapped[int] = mapped_column(
340 ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True
341 )
342 line_order: Mapped[int] = mapped_column(Integer)
343 line_label: Mapped[str] = mapped_column(String(512))
344 target_note_id: Mapped[int | None] = mapped_column(
345 ForeignKey("note_definitions.id", ondelete="RESTRICT")
346 )
347 mapped_total: Mapped[Decimal | None] = mapped_column(Rial())
348 statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
349 target_note: Mapped[NoteDefinition | None] = relationship()
350
351
352 def _resolve_parent_year_id(
353 obj: Any, session: Session, rel_attr: str, fk_attr: str, parent_cls: type[Any]
354 ) -> int | None:
355 parent = getattr(obj, rel_attr, None)
356 if parent is not None:
357 return parent.year_id
358 fk_val = getattr(obj, fk_attr, None)
359 if fk_val is not None:
360 return session.scalar(select(parent_cls.year_id).where(parent_cls.id == fk_val))
361 return None
362
363
364 def _year_id_for(obj: object, session: Session) -> int | None:
365 if isinstance(obj, FiscalYear):
366 return obj.id
367 if isinstance(obj, YearOwnedMixin):
368 return obj.year_id
369 if isinstance(obj, NoteRow):
370 return _resolve_parent_year_id(obj, session, "note", "note_id", NoteDefinition)
371 if isinstance(obj, StatementLine):
372 return _resolve_parent_year_id(
373 obj, session, "statement", "statement_id", FinancialStatement
374 )
375 return None
376
377
378 _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
379
380
381 def _company_has_protected_year(session: Session, company_id: int) -> bool:
382 status = session.scalar(
383 select(FiscalYear.status)
384 .where(
385 FiscalYear.company_id == company_id,
386 FiscalYear.status.in_(_PROTECTED_YEAR_STATUSES),
387 )
388 .limit(1)
389 )
390 return status is not None
391
392
393 @event.listens_for(Session, "before_flush")
394 def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None:
395 for obj in session.deleted:
396 if isinstance(obj, FiscalYear) and obj.status in _PROTECTED_YEAR_STATUSES:
397 raise ValueError(
398 f"Fiscal year {obj.id} is {obj.status.value.lower()} and cannot be deleted"
399 )
400
401 for obj in session.dirty:
402 if (
403 isinstance(obj, Company)
404 and obj.id is not None
405 and _company_has_protected_year(session, obj.id)
406 ):
407 raise ValueError(
408 f"Company {obj.id} has approved or locked fiscal years and cannot be mutated"
409 )
410
411 if not isinstance(obj, FiscalYear):
412 continue
413
414 state = inspect(obj)
415 status_history = state.attrs.status.history
416 old_status = status_history.deleted[0] if status_history.deleted else obj.status
417 if status_history.deleted:
418 allowed = {
419 FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
420 FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
421 FiscalYearStatus.LOCKED: {FiscalYearStatus.APPROVED},
422 }
423 if obj.status not in allowed[old_status]:
424 raise ValueError(
425 f"Invalid fiscal-year transition: {old_status.value} -> {obj.status.value}"
426 )
427 if old_status == FiscalYearStatus.LOCKED and obj.status == FiscalYearStatus.APPROVED:
428 approved_reopen = session.scalar(
429 select(ReopenRequest.id)
430 .where(
431 ReopenRequest.year_id == obj.id,
432 ReopenRequest.status == "approved",
433 )
434 .limit(1)
435 )
436 if approved_reopen is None:
437 raise ValueError(
438 f"Fiscal year {obj.id} is locked; reopening requires an approved ReopenRequest"
439 )
440
441 protected_metadata_changed = state.attrs.company.history.has_changes() or any(
442 state.attrs[field].history.has_changes() for field in ("company_id", "year")
443 )
444 if old_status in _PROTECTED_YEAR_STATUSES and protected_metadata_changed:
445 raise ValueError(
446 f"Fiscal year {obj.id} is {old_status.value.lower()} and its identity cannot be mutated"
447 )
448
449 for obj in session.deleted:
450 if (
451 isinstance(obj, Company)
452 and obj.id is not None
453 and _company_has_protected_year(session, obj.id)
454 ):
455 raise ValueError(
456 f"Company {obj.id} has approved or locked fiscal years and cannot be deleted"
457 )
458
459 protected = session.new | session.dirty | session.deleted
460 for obj in protected:
461 if isinstance(obj, FiscalYear):
462 continue
463 # A ReopenRequest is the authorized mechanism to act on a locked year
464 # (ADR-016); creating/approving it must not be blocked by the year guard.
465 if isinstance(obj, ReopenRequest):
466 continue
467 year_id = _year_id_for(obj, session)
468 if year_id is None:
469 continue
470 status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
471 if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}:
472 raise ValueError(
473 f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated"
474 )
475
476 if isinstance(obj, MappingRule):
477 target_year_id = _resolve_parent_year_id(
478 obj, session, "target_note", "target_note_id", NoteDefinition
479 )
480 if target_year_id != obj.year_id:
481 raise ValueError("Mapping rule and target note must belong to the same fiscal year")
482 if isinstance(obj, StatementLine) and obj.target_note_id is not None:
483 target_year_id = _resolve_parent_year_id(
484 obj, session, "target_note", "target_note_id", NoteDefinition
485 )
486 if target_year_id != year_id:
487 raise ValueError(
488 "Statement line and target note must belong to the same fiscal year"
489 )