@davoodmehraban89 / Aram / commits / 7dc864f
Fork 0

fix(v1): harden safety gate before Mapping (#21)

Accept V1-01 safety-gate hardening after independent exact-head review and successful Backend CI #41. Protect approved/locked fiscal-year identity and deletion, harden Pilot preflight validation, quarantine the disconnected legacy UI, and preserve canonical financial data.

davoodmehraban89 committed Aug 27, 2026 at 13:55 UTC 7dc864fd032f0c4ae4d650d89304a01286a6d914
8 files changed +494 -850
PROJECT_STATUS.md
+7 -3
@@ -35,6 +35,7 @@
35 | Phase 2B ingestion foundation | VERIFIED_AND_MERGED | [PR #12](https://github.com/davoodmehraban89/Aram/pull/12), squash merge 7b5bd79b760d534dad34b3162f770e838616ebe9 |
36 | Phase 2B control reconciliation | VERIFIED_AND_MERGED | [PR #13](https://github.com/davoodmehraban89/Aram/pull/13), squash merge 7c7533ee87146dc8fc78b46ebf423be55532c7eb |
37 | Gate 2A Pilot workbook contract/preflight | VERIFIED_AND_MERGED | [PR #15](https://github.com/davoodmehraban89/Aram/pull/15), reviewed head 74b6a6397a2a2c9199a5c7bcf818bb661b2ebe06, squash merge 4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4, [Backend CI #24](https://github.com/davoodmehraban89/Aram/actions/runs/32712900800) |
38 +| V1-01 safety-gate hardening | IN_PROGRESS | Draft [PR #21](https://github.com/davoodmehraban89/Aram/pull/21) from exact base `b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`; independently reviewed implementation head `700d800dbd9c657f6bd510faafedcbde4847fafd`; CI-verified stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded with 67 tests, migration round-trip, and compile after broadening one reparent-rejection assertion to accept either valid protection message; code, scope, and protected-data boundary remain unchanged; final independent acceptance is pending this durable-document reconciliation |
39 | Post-Gate-2A control reconciliation | VERIFIED_AND_MERGED | [PR #18](https://github.com/davoodmehraban89/Aram/pull/18), reviewed head `fcbeb7387218e9ab294318ae462ed59de717fc95`, squash merge `f213d321ff4cd7d3d6fa65ba78dc48f090ee846b`; documentation only |
40 | Durable post-merge acceptance record | VERIFIED_AND_MERGED | [PR #19](https://github.com/davoodmehraban89/Aram/pull/19), reviewed head `b9059592409606a0a4f11a71c30778cff158b6b6`, squash merge `77f9f595ccfe67a87b11024ff0f6143629dba438`; documentation only |
41 | Role-based project operating model | VERIFIED_AND_MERGED | Permanent responsibilities and current assignments are defined in `docs/handoff/MASTER_RECOVERY_PROMPT.md` and ADR-011; introduced through [PR #20](https://github.com/davoodmehraban89/Aram/pull/20) |
@@ -63,6 +64,9 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
64 ## Current risks and blockers
65
66 - The accepted branch is not protected by GitHub branch protection.
67 +- The accepted branch still permits direct identity mutation/deletion of approved or locked fiscal years and parent-company deletion; the V1-01 candidate fixes this but is not accepted yet.
68 +- The accepted Pilot preflight can still accept targetless or structurally invalid mappings and can ignore a declared closing-delta mismatch; the V1-01 candidate fixes this but is not accepted yet.
69 +- The accepted root `index.html` is still a disconnected hard-coded prototype; the V1-01 candidate replaces it with an explicit quarantine page.
70 - PR #17 was closed without merge; its stale-base 12-file diff is reference material only, and its narrative listed only 9 files.
71 - PR #17 CI was green on its own stale head, but compatibility with accepted Gate 2A was never proven.
72 - Binary execution, release provenance, and clean Windows verification do not exist.
@@ -70,9 +74,9 @@ The accepted branch does not include PR #7 desktop/release work, PR #16 alternat
74
75 ## Next approved action
76
73 -1. The Operational Coordinator fetches the live `source-data-cleanup` head and confirms that no open implementation PR exists.
74 -2. It defines one focused Gate 3 / Gate 2B Mapping task from that exact head and routes the scope package to the Senior Technical Supervisor / Independent Reviewer.
75 -3. After scope review, Jules implements through one focused Draft PR; closed PR #17 remains reference-only and must not be reopened or merged.
77 +1. Publish this two-file durable-document reconciliation on Draft PR #21; [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194) succeeded on stabilized candidate `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` with 67 tests, migration round-trip, and compile.
78 +2. The independent reviewer re-fetches the resulting documentation-only head, confirms that its comparison with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` changes only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md`, verifies the final workflow result, then marks the PR ready and squash-merges it.
79 +3. Only after V1-01 is accepted, start the first focused Gate 3 Mapping import/persistence task from the new accepted head.
80
81 ## Control documents
82
backend/src/aram_backend/models.py
+64 -13
@@ -1,7 +1,7 @@
1 from __future__ import annotations
2
3 import enum
4 -from datetime import datetime, timezone
4 +from datetime import UTC, datetime
5 from decimal import Decimal
6 from typing import Any
7
@@ -26,7 +26,7 @@ from aram_backend.database import Base
26
27
28 def utc_now() -> datetime:
29 - return datetime.now(timezone.utc)
29 + return datetime.now(UTC)
30
31
32 class FiscalYearStatus(str, enum.Enum):
@@ -205,20 +205,71 @@ def _year_id_for(obj: object, session: Session) -> int | None:
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:
211 - if isinstance(obj, FiscalYear):
212 - history = inspect(obj).attrs.status.history
213 - if history.deleted:
214 - old = history.deleted[0]
215 - allowed = {
216 - FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
217 - FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
218 - FiscalYearStatus.LOCKED: set(),
219 - }
220 - if obj.status not in allowed[old]:
221 - raise ValueError(f"Invalid fiscal-year transition: {old.value} -> {obj.status.value}")
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:
backend/src/aram_backend/pilot_workbook.py
+183 -18
@@ -2,6 +2,7 @@ from __future__ import annotations
2
3 from collections import Counter
4 from dataclasses import dataclass
5 +from datetime import date, datetime
6 from decimal import Decimal, InvalidOperation
7 from io import BytesIO
8 from typing import Any
@@ -10,7 +11,6 @@ from zipfile import BadZipFile
11 from openpyxl import load_workbook
12 from openpyxl.utils.exceptions import InvalidFileException
13
13 -
14 SHEET_HEADERS: dict[str, tuple[str, ...]] = {
15 "Company": (
16 "company_code", "company_name", "fiscal_year", "currency", "unit",
@@ -56,15 +56,41 @@ _REQUIRED: dict[str, set[str]] = {
56 "Accounts": {
57 "company_code", "fiscal_year", "general_code", "general_name",
58 "account_full_code", "account_name", "opening", "debit", "credit",
59 - "closing", "source_row", "row_status",
59 + "closing", "source_row", "row_status", "closing_delta",
60 + },
61 + "Notes": {
62 + "company_code", "fiscal_year", "statement", "statement_section",
63 + "note_number", "note_title",
64 },
61 - "Notes": {"company_code", "fiscal_year", "statement", "note_number", "note_title"},
65 "Mapping": {
66 "mapping_id", "company_code", "fiscal_year", "account_full_code",
64 - "account_level", "mapping_version", "approval_status",
67 + "account_level", "target_statement", "statement_section", "note_number",
68 + "mapping_version", "approval_status", "source", "validation_status",
69 },
70 }
71
72 +_STATEMENTS = {"BS", "IS", "CF", "EQ"}
73 +_ACCOUNT_LEVELS: dict[str, tuple[str, ...]] = {
74 + "General": ("general_code",),
75 + "Subsidiary": ("general_code", "subsidiary_code"),
76 + "Detail1": ("general_code", "subsidiary_code", "detail1_code"),
77 + "Detail2": (
78 + "general_code", "subsidiary_code", "detail1_code", "detail2_code",
79 + ),
80 + "Detail3": (
81 + "general_code", "subsidiary_code", "detail1_code", "detail2_code",
82 + "detail3_code",
83 + ),
84 + "Detail4": (
85 + "general_code", "subsidiary_code", "detail1_code", "detail2_code",
86 + "detail3_code", "detail4_code",
87 + ),
88 +}
89 +_HIERARCHY_FIELDS = (
90 + "general_code", "subsidiary_code", "detail1_code", "detail2_code",
91 + "detail3_code", "detail4_code",
92 +)
93 +
94
95 @dataclass(frozen=True)
96 class PilotIssue:
@@ -100,7 +126,12 @@ def _text_code(value: Any, issues: list[PilotIssue], sheet: str, row: int,
126 _issue(issues, "CODE_NOT_TEXT", sheet, row, field,
127 "Code cells must use Excel text format; numeric coercion is forbidden.")
128 return None
103 - return value.strip()
129 + code = value.strip()
130 + if code.startswith("="):
131 + _issue(issues, "CODE_FORMULA_FORBIDDEN", sheet, row, field,
132 + "Code cells must contain literal text; formulas are forbidden.")
133 + return None
134 + return code
135
136
137 def _positive_int(value: Any, issues: list[PilotIssue], sheet: str, row: int,
@@ -187,16 +218,17 @@ def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
218 code = _text_code(row["company_code"], [], "Company", row_number, "company_code")
219 year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
220 if code and year and year > 0:
190 - key = (code, year)
191 - if key in companies:
221 + company_key = (code, year)
222 + if company_key in companies:
223 _issue(issues, "DUPLICATE_COMPANY_YEAR", "Company", row_number,
224 "company_code", "Company/fiscal-year key must be unique.")
194 - companies.add(key)
225 + companies.add(company_key)
226 if not _empty(row["status"]) and row["status"] not in {"Draft", "Approved", "Locked"}:
227 _issue(issues, "INVALID_LIFECYCLE", "Company", row_number, "status",
228 "Allowed values are Draft, Approved, and Locked.")
229
230 account_keys: set[tuple[str, int, str]] = set()
231 + account_rows: dict[tuple[str, int, str], dict[str, Any]] = {}
232 for row_number, row in parsed.get("Accounts", []):
233 code = row["company_code"] if isinstance(row["company_code"], str) else None
234 year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
@@ -205,22 +237,39 @@ def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
237 _issue(issues, "UNKNOWN_COMPANY_YEAR", "Accounts", row_number, "company_code",
238 "Referenced company/fiscal year is not defined in Company.")
239 if code and year and account:
208 - key = (code.strip(), year, account.strip())
209 - if key in account_keys:
240 + account_key = (code.strip(), year, account.strip())
241 + if account_key in account_keys:
242 _issue(issues, "DUPLICATE_ACCOUNT", "Accounts", row_number,
243 "account_full_code", "Account key is duplicated within company/fiscal year.")
212 - account_keys.add(key)
213 - values = [_finite_decimal(row[field], issues, "Accounts", row_number, field)
214 - for field in ("opening", "debit", "credit", "closing")]
244 + account_keys.add(account_key)
245 + account_rows.setdefault(account_key, row)
246 + opening, debit, credit, closing = (
247 + _finite_decimal(row[field], issues, "Accounts", row_number, field)
248 + for field in ("opening", "debit", "credit", "closing")
249 + )
250 + declared_delta = _finite_decimal(
251 + row["closing_delta"], issues, "Accounts", row_number, "closing_delta"
252 + )
253 _positive_int(row["source_row"], issues, "Accounts", row_number, "source_row")
254 if not _empty(row["row_status"]) and row["row_status"] not in {"Draft", "Reviewed", "Approved"}:
255 _issue(issues, "INVALID_LIFECYCLE", "Accounts", row_number, "row_status",
256 "Allowed values are Draft, Reviewed, and Approved.")
219 - if all(value is not None for value in values):
220 - delta = values[0] + values[1] - values[2] - values[3]
257 + if (
258 + opening is not None
259 + and debit is not None
260 + and credit is not None
261 + and closing is not None
262 + ):
263 + delta = opening + debit - credit - closing
264 if delta != 0:
265 _issue(issues, "NON_ZERO_CLOSING_DELTA", "Accounts", row_number,
266 "closing_delta", f"opening + debit - credit - closing equals {delta}.")
267 + if declared_delta is not None and declared_delta != delta:
268 + _issue(
269 + issues, "CLOSING_DELTA_MISMATCH", "Accounts", row_number,
270 + "closing_delta",
271 + f"Declared closing_delta {declared_delta} does not equal computed delta {delta}.",
272 + )
273
274 for sheet_name in ("Notes", "Mapping"):
275 for row_number, row in parsed.get(sheet_name, []):
@@ -230,6 +279,31 @@ def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
279 _issue(issues, "UNKNOWN_COMPANY_YEAR", sheet_name, row_number,
280 "company_code", "Referenced company/fiscal year is not defined in Company.")
281
282 + note_keys: set[tuple[str, int, str, str, str, str]] = set()
283 + for row_number, row in parsed.get("Notes", []):
284 + statement = row["statement"]
285 + if not _empty(statement) and statement not in _STATEMENTS:
286 + _issue(
287 + issues, "INVALID_STATEMENT", "Notes", row_number, "statement",
288 + "Allowed statement values are BS, IS, CF, and EQ.",
289 + )
290 + code = row["company_code"] if isinstance(row["company_code"], str) else None
291 + year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
292 + note_number = row["note_number"] if isinstance(row["note_number"], str) else None
293 + section = row["statement_section"] if isinstance(row["statement_section"], str) else None
294 + subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else ""
295 + if code and year and statement in _STATEMENTS and section and note_number:
296 + note_key = (
297 + code.strip(), year, statement, section.strip(), note_number.strip(),
298 + subnote.strip(),
299 + )
300 + if note_key in note_keys:
301 + _issue(
302 + issues, "DUPLICATE_NOTE_TARGET", "Notes", row_number,
303 + "note_number", "Note/sub-note target is duplicated.",
304 + )
305 + note_keys.add(note_key)
306 +
307 mapping_ids: set[str] = set()
308 for row_number, row in parsed.get("Mapping", []):
309 mapping_id = row["mapping_id"] if isinstance(row["mapping_id"], str) else None
@@ -242,12 +316,103 @@ def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
316 if not _empty(row["approval_status"]) and row["approval_status"] not in {"Draft", "Reviewed", "Approved"}:
317 _issue(issues, "INVALID_LIFECYCLE", "Mapping", row_number, "approval_status",
318 "Allowed values are Draft, Reviewed, and Approved.")
319 + if not _empty(row["validation_status"]) and row["validation_status"] not in {"Valid", "Invalid", "Pending"}:
320 + _issue(
321 + issues, "INVALID_VALIDATION_STATUS", "Mapping", row_number,
322 + "validation_status", "Allowed values are Valid, Invalid, and Pending.",
323 + )
324 + if not _empty(row["target_statement"]) and row["target_statement"] not in _STATEMENTS:
325 + _issue(
326 + issues, "INVALID_STATEMENT", "Mapping", row_number,
327 + "target_statement", "Allowed statement values are BS, IS, CF, and EQ.",
328 + )
329 +
330 + level = row["account_level"]
331 + if not _empty(level) and level not in _ACCOUNT_LEVELS:
332 + _issue(
333 + issues, "INVALID_ACCOUNT_LEVEL", "Mapping", row_number,
334 + "account_level",
335 + "Allowed levels are General, Subsidiary, Detail1, Detail2, Detail3, and Detail4.",
336 + )
337 + elif level in _ACCOUNT_LEVELS:
338 + required_fields = set(_ACCOUNT_LEVELS[level])
339 + for field in required_fields:
340 + if _empty(row[field]):
341 + _issue(
342 + issues, "MAPPING_HIERARCHY_MISSING", "Mapping", row_number,
343 + field, f"{field} is required for account level {level}.",
344 + )
345 + for field in _HIERARCHY_FIELDS[len(_ACCOUNT_LEVELS[level]):]:
346 + if not _empty(row[field]):
347 + _issue(
348 + issues, "MAPPING_HIERARCHY_EXCESS", "Mapping", row_number,
349 + field, f"{field} must be empty for account level {level}.",
350 + )
351 +
352 + approval_status = row["approval_status"]
353 + if approval_status in {"Reviewed", "Approved"}:
354 + if _empty(row["reviewer"]):
355 + _issue(
356 + issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number,
357 + "reviewer", "Reviewed and Approved mappings require a reviewer.",
358 + )
359 + review_date = row["review_date"]
360 + if _empty(review_date):
361 + _issue(
362 + issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number,
363 + "review_date", "Reviewed and Approved mappings require a review date.",
364 + )
365 + elif not isinstance(review_date, (str, date, datetime)):
366 + _issue(
367 + issues, "INVALID_REVIEW_DATE", "Mapping", row_number,
368 + "review_date", "Review date must be an Excel date or text date.",
369 + )
370 + if approval_status == "Approved" and row["validation_status"] != "Valid":
371 + _issue(
372 + issues, "APPROVAL_REQUIRES_VALID_MAPPING", "Mapping", row_number,
373 + "validation_status", "Approved mappings must have validation_status Valid.",
374 + )
375 +
376 code = row["company_code"] if isinstance(row["company_code"], str) else None
377 year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
378 account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None
248 - if code and year and account and (code.strip(), year, account.strip()) not in account_keys:
249 - _issue(issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number,
250 - "account_full_code", "Mapped account does not exist in Accounts for this company/fiscal year.")
379 + mapping_account_key = (
380 + (code.strip(), year, account.strip())
381 + if code and year and account else None
382 + )
383 + if mapping_account_key and mapping_account_key not in account_keys:
384 + _issue(
385 + issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number,
386 + "account_full_code",
387 + "Mapped account does not exist in Accounts for this company/fiscal year.",
388 + )
389 + elif mapping_account_key:
390 + source_account = account_rows[mapping_account_key]
391 + for field in _HIERARCHY_FIELDS:
392 + mapping_value = row[field].strip() if isinstance(row[field], str) else None
393 + account_value = source_account[field].strip() if isinstance(source_account[field], str) else None
394 + if mapping_value != account_value:
395 + _issue(
396 + issues, "MAPPING_HIERARCHY_MISMATCH", "Mapping", row_number,
397 + field,
398 + f"Mapping hierarchy does not match Accounts for {field}.",
399 + )
400 +
401 + statement = row["target_statement"]
402 + section = row["statement_section"] if isinstance(row["statement_section"], str) else None
403 + note_number = row["note_number"] if isinstance(row["note_number"], str) else None
404 + subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else ""
405 + if code and year and statement in _STATEMENTS and section and note_number:
406 + target_key = (
407 + code.strip(), year, statement, section.strip(), note_number.strip(),
408 + subnote.strip(),
409 + )
410 + if target_key not in note_keys:
411 + _issue(
412 + issues, "UNKNOWN_MAPPING_TARGET", "Mapping", row_number,
413 + "note_number",
414 + "Mapped statement/note/sub-note target does not exist in Notes.",
415 + )
416
417 ordered = tuple(sorted(issues, key=lambda item: (
418 _SHEET_ORDER.get(item.sheet, -1), item.row,
backend/tests/test_models.py
+73
@@ -158,3 +158,76 @@ def test_invalid_status_skip_is_rejected(session):
158 year.status = FiscalYearStatus.LOCKED
159 with pytest.raises(ValueError, match="Invalid fiscal-year transition"):
160 session.commit()
161 +
162 +
163 +# These adversarial cases reproduce the V1 audit bypasses; keep them as release gates.
164 +@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
165 +def test_protected_year_identity_cannot_be_mutated(session, status):
166 + year = make_year(session)
167 + year.status = FiscalYearStatus.APPROVED
168 + session.commit()
169 + if status is FiscalYearStatus.LOCKED:
170 + year.status = FiscalYearStatus.LOCKED
171 + session.commit()
172 +
173 + year.year = 1405
174 + with pytest.raises(ValueError, match="identity cannot be mutated"):
175 + session.commit()
176 +
177 +
178 +@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
179 +def test_protected_year_cannot_be_deleted(session, status):
180 + year = make_year(session)
181 + year.status = FiscalYearStatus.APPROVED
182 + session.commit()
183 + if status is FiscalYearStatus.LOCKED:
184 + year.status = FiscalYearStatus.LOCKED
185 + session.commit()
186 +
187 + session.delete(year)
188 + with pytest.raises(ValueError, match="cannot be deleted"):
189 + session.commit()
190 +
191 +
192 +def test_company_with_protected_year_cannot_be_mutated(session):
193 + year = make_year(session)
194 + year.status = FiscalYearStatus.APPROVED
195 + session.commit()
196 +
197 + year.company.name = "Changed after approval"
198 + with pytest.raises(ValueError, match="cannot be mutated"):
199 + session.commit()
200 +
201 +
202 +def test_company_with_protected_year_cannot_be_deleted(session):
203 + year = make_year(session)
204 + year.status = FiscalYearStatus.APPROVED
205 + session.commit()
206 +
207 + session.delete(year.company)
208 + with pytest.raises(ValueError, match="cannot be deleted"):
209 + session.commit()
210 +
211 +
212 +def test_protected_year_cannot_be_reparented_through_relationship(session):
213 + year = make_year(session)
214 + replacement = Company(code="REPLACEMENT", name="Replacement Company")
215 + session.add(replacement)
216 + session.commit()
217 + year.status = FiscalYearStatus.APPROVED
218 + session.commit()
219 +
220 + year.company = replacement
221 + with pytest.raises(ValueError, match="cannot be mutated"):
222 + session.commit()
223 +
224 +
225 +def test_draft_year_identity_and_deletion_remain_mutable(session):
226 + year = make_year(session)
227 + year.year = 1405
228 + session.commit()
229 + assert year.year == 1405
230 +
231 + session.delete(year)
232 + session.commit()
233 + assert session.get(FiscalYear, year.id) is None
backend/tests/test_pilot_workbook.py
+69
@@ -153,3 +153,72 @@ def test_validation_does_not_persist_any_artifact(tmp_path, monkeypatch):
153 before = set(tmp_path.iterdir())
154 preflight_pilot_workbook(workbook_bytes(valid_rows()))
155 assert set(tmp_path.iterdir()) == before
156 +
157 +
158 +def test_mapping_requires_a_real_target_and_valid_account_level():
159 + rows = valid_rows()
160 + mapping = list(rows["Mapping"][0])
161 + mapping[4] = 99
162 + mapping[11] = None
163 + mapping[12] = None
164 + mapping[13] = None
165 + rows["Mapping"] = [tuple(mapping)]
166 +
167 + codes = issue_codes(workbook_bytes(rows))
168 + assert "INVALID_ACCOUNT_LEVEL" in codes
169 + assert codes.count("REQUIRED_FIELD") >= 3
170 +
171 +
172 +def test_mapping_target_must_exist_in_notes():
173 + rows = valid_rows()
174 + mapping = list(rows["Mapping"][0])
175 + mapping[14] = "999"
176 + rows["Mapping"] = [tuple(mapping)]
177 +
178 + assert "UNKNOWN_MAPPING_TARGET" in issue_codes(workbook_bytes(rows))
179 +
180 +
181 +def test_mapping_hierarchy_must_match_the_account_row():
182 + rows = valid_rows()
183 + mapping = list(rows["Mapping"][0])
184 + mapping[5] = "99"
185 + rows["Mapping"] = [tuple(mapping)]
186 +
187 + assert "MAPPING_HIERARCHY_MISMATCH" in issue_codes(workbook_bytes(rows))
188 +
189 +
190 +def test_declared_closing_delta_must_match_computed_delta():
191 + rows = valid_rows()
192 + account = list(rows["Accounts"][0])
193 + account[22] = 999
194 + rows["Accounts"] = [tuple(account)]
195 +
196 + assert "CLOSING_DELTA_MISMATCH" in issue_codes(workbook_bytes(rows))
197 +
198 +
199 +def test_code_formulas_are_rejected():
200 + rows = valid_rows()
201 + account = list(rows["Accounts"][0])
202 + account[14] = '=TEXT(10,"0000")'
203 + rows["Accounts"] = [tuple(account)]
204 +
205 + assert "CODE_FORMULA_FORBIDDEN" in issue_codes(workbook_bytes(rows))
206 +
207 +
208 +def test_reviewed_and_approved_mappings_require_review_evidence():
209 + rows = valid_rows()
210 + mapping = list(rows["Mapping"][0])
211 + mapping[16] = "Approved"
212 + mapping[21] = "Pending"
213 + rows["Mapping"] = [tuple(mapping)]
214 +
215 + codes = issue_codes(workbook_bytes(rows))
216 + assert codes.count("REVIEW_EVIDENCE_REQUIRED") == 2
217 + assert "APPROVAL_REQUIRES_VALID_MAPPING" in codes
218 +
219 +
220 +def test_duplicate_note_target_is_rejected():
221 + rows = valid_rows()
222 + rows["Notes"].append(rows["Notes"][0])
223 +
224 + assert "DUPLICATE_NOTE_TARGET" in issue_codes(workbook_bytes(rows))
docs/PROJECT_LOG.md
+23
@@ -255,3 +255,26 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
255 - Recovery: close PR #20 without merge; the accepted branch remains at `77f9f595ccfe67a87b11024ff0f6143629dba438`
256 - Remaining risks: the accepted branch is unprotected; role assignments do not replace evidence gates; Gate 3 Mapping and all later V1 gates remain incomplete
257 - Next action: finish the five-file remote candidate, independently review PR #20, and record one acceptance decision
258 +
259 +### 2026-08-26T15:36:29Z — V1-01 safety-gate hardening prepared
260 +
261 +- Actor: Codex Work authorized maintainer / implementation agent for the critical fix
262 +- Task/phase: V1-01 safety-gate hardening before Gate 3 Mapping
263 +- Base: `source-data-cleanup@b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`
264 +- Working branch: `codex/v1-01-safety-gate-hardening`
265 +- PR: Draft [#21](https://github.com/davoodmehraban89/Aram/pull/21)
266 +- Initial implementation commit SHA: `6d774e5dd7afb00b04e523ba255aeee4f13bfccc`; final reviewed head remains remote-state dependent
267 +- Exact planned changed files: `index.html`, `PROJECT_STATUS.md`, `backend/src/aram_backend/models.py`, `backend/src/aram_backend/pilot_workbook.py`, `backend/tests/test_models.py`, `backend/tests/test_pilot_workbook.py`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`
268 +- Implementation: prevent approved/locked fiscal-year identity mutation and deletion; prevent parent-company mutation/deletion when protected years exist; reject targetless, hierarchy-invalid, formula-code, review-evidence-deficient, and closing-delta-mismatched Pilot rows; replace the disconnected hard-coded root UI with an explicit quarantine page
269 +- Local tests: `cd backend && .venv/bin/pytest -q` -> 67 passed, 1 third-party deprecation warning
270 +- Focused static checks: `.venv/bin/ruff check src/aram_backend/models.py src/aram_backend/pilot_workbook.py` -> passed; `.venv/bin/mypy src/aram_backend/models.py src/aram_backend/pilot_workbook.py` -> passed
271 +- Migration / compile: isolated SQLite `alembic upgrade head` and `alembic downgrade base` passed; `python -m compileall -q src tests scripts` passed
272 +- Adversarial verification: the previously accepted targetless/`account_level=99`/`closing_delta=999` workbook is rejected; locked-year identity mutation and deletion are blocked
273 +- GitHub Actions: pending for Draft PR #21
274 +- Artifacts/releases: `NONE`
275 +- Protected data: no canonical XLSX/PDF, `data/`, database, financial-source value, ZIP, EXE, tag, or release is changed
276 +- Acceptance: `IN_PROGRESS`; implementation author must not merge this PR
277 +- Reviewer: independent reviewer pending
278 +- Recovery: close the candidate PR without merge; accepted branch remains at the recorded base
279 +- Remaining risks: comprehensive Mapping, note/sub-note workflow, real Pilot UI/output, Windows packaging, and user acceptance remain incomplete
280 +- Next action: publish the focused PR and obtain independent remote review after CI
docs/handoff/LATEST_HANDOFF.md
+18 -1
@@ -88,6 +88,23 @@
88 - Green CI on an unmerged PR is not acceptance evidence.
89 - No Gate 3 implementation candidate is accepted or active.
90
91 +## Active V1-01 safety-gate candidate
92 +
93 +- Verified base: `source-data-cleanup@b1ddee87d31ee73b3a5aeac8f9953d0a604c206a`
94 +- Working branch: `codex/v1-01-safety-gate-hardening`
95 +- Draft PR: [#21](https://github.com/davoodmehraban89/Aram/pull/21)
96 +- Independently reviewed implementation head: `700d800dbd9c657f6bd510faafedcbde4847fafd`.
97 +- Earlier exact-head candidate: `aba10b61c770ce319b1b67d960a4f0a1057e25f6`; [Backend CI #36](https://github.com/davoodmehraban89/Aram/actions/runs/32989551021) succeeded.
98 +- A later documentation-triggered [Backend CI #38](https://github.com/davoodmehraban89/Aram/actions/runs/33015151139) exposed a flaky message-specific reparent assertion: protection fired correctly, but through the equally valid parent-company invariant.
99 +- Stabilized candidate: `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; the single test assertion now accepts either valid `cannot be mutated` protection message without changing product behavior.
100 +- Latest verified CI: [Backend CI #39](https://github.com/davoodmehraban89/Aram/actions/runs/33015277194), success on `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`; 67 tests passed, migration upgrade/downgrade and compile succeeded.
101 +- Purpose: close the independently reproduced protected-year deletion/mutation and Pilot-preflight false-negative defects before any Mapping/UI expansion.
102 +- Planned changed files: `index.html`, `PROJECT_STATUS.md`, `backend/src/aram_backend/models.py`, `backend/src/aram_backend/pilot_workbook.py`, `backend/tests/test_models.py`, `backend/tests/test_pilot_workbook.py`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`.
103 +- Local evidence at preparation: 67 pytest tests passed; isolated Alembic upgrade/downgrade and compileall passed; focused Ruff and mypy checks passed.
104 +- Protected boundary: no canonical financial data, workbook, PDF, database, financial value, binary, ZIP, EXE, tag, or release is in scope.
105 +- Independent-review decision: code, scope, diff, and protected-data boundary passed. CI #38 later revealed only a nondeterministic error-message assertion; CI #39 passed after the one-line assertion stabilization.
106 +- Status: `IN_PROGRESS`; this durable-document reconciliation records the complete CI sequence. The resulting documentation-only head must be re-fetched and compared with `b3dc8b3a18934ffe63f615e4f650248be21a5f9c` before Ready/Squash Merge.
107 +
108 ## Single next action
109
93 -The Operational Coordinator fetches the live `source-data-cleanup` head and open-PR list, then prepares one focused Gate 3 / Gate 2B Mapping scope package for the Senior Technical Supervisor / Independent Reviewer. After scope review, Jules implements from that exact head through one focused Draft PR. Use PR #17 only as reference.
110 +Publish this requested two-document reconciliation on PR #21 and route the resulting documentation-only head back to the independent reviewer. The reviewer must confirm that only `PROJECT_STATUS.md` and `docs/handoff/LATEST_HANDOFF.md` changed after the CI-verified stabilized head `b3dc8b3a18934ffe63f615e4f650248be21a5f9c`, verify the final workflow result, then Ready/Squash Merge. Do not begin Gate 3 Mapping until V1-01 is accepted.
index.html
+57 -815
@@ -1,819 +1,61 @@
1 -<!DOCTYPE html>
1 +<!doctype html>
2 <html lang="fa" dir="rtl">
3 <head>
4 - <meta charset="UTF-8">
5 - <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 - <title>هسته یکپارچه صورت‌های مالی - آماده انتقال به دیتابیس</title>
7 - <script src="https://cdn.tailwindcss.com"></script>
8 - <style>
9 - @import url('https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/Vazirmatn-font-face.css');
10 - * { font-family: 'Vazirmatn', sans-serif; }
11 - ::-webkit-scrollbar { width: 6px; height: 6px; }
12 - ::-webkit-scrollbar-track { background: #0f172a; }
13 - ::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
14 -
15 - /* =========================================
16 - موتور پرینت اختصاصی و استاندارد (A4)
17 - ========================================= */
18 - @media print {
19 - @page { size: A4 portrait; margin: 12mm; }
20 - body { background-color: white !important; color: black !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; font-size: 11pt; }
21 - .no-print, #app-wrapper, .print-controls { display: none !important; }
22 - #print-wrapper { display: block !important; width: 100%; direction: rtl; background: white !important; }
23 -
24 - .print-page { page-break-after: always; clear: both; padding: 10mm 0; position: relative; min-height: 250mm; }
25 - .print-page:last-child { page-break-after: auto; }
26 -
27 - h2 { font-size: 16pt; text-align: center; font-weight: bold; margin-bottom: 15px; color: black !important; }
28 - h3 { font-size: 14pt; text-align: center; font-weight: bold; margin-bottom: 15px; color: black !important; border-bottom: 2px solid #000; padding-bottom: 10px;}
29 - h4 { font-size: 12pt; font-weight: bold; margin-bottom: 10px; color: black !important; }
30 -
31 - table { width: 100%; border-collapse: collapse; margin-bottom: 25px; font-size: 10pt; page-break-inside: avoid; }
32 - th, td { border: 1px solid #000 !important; padding: 8px !important; color: black !important; text-align: center;}
33 - th { background-color: #e5e7eb !important; font-weight: bold; }
34 - td:first-child { text-align: right; }
35 -
36 - .sign-grid { display: flex; justify-content: space-around; margin-top: 60px; text-align: center; font-size: 11pt; gap: 20px; flex-wrap: wrap;}
37 - .sign-box { border-top: 1px dashed #000; padding-top: 15px; flex: 1; min-width: 150px; font-weight: bold; margin-bottom: 30px;}
38 - .sign-role { font-size: 9pt; font-weight: normal; margin-top: 5px; display: block; color: #333 !important;}
39 -
40 - .ai-grid { display: flex; justify-content: space-between; gap: 15px; margin-bottom: 20px; margin-top: 20px;}
41 - .ai-card { border: 2px solid #4f46e5 !important; padding: 15px; flex: 1; text-align: center; border-radius: 8px; background-color: #f8fafc !important; }
42 - .ai-val { font-size: 16pt; font-weight: bold; margin-top: 10px; direction: ltr; color: #1e1b4b !important;}
43 - .ai-title { font-size: 10pt; font-weight: bold; color: #334155 !important;}
44 - .ai-analysis { border: 2px solid #10b981 !important; padding: 15px; border-radius: 8px; background-color: #f0fdf4 !important; text-align: justify; line-height: 2; font-size: 11pt;}
45 - }
46 -
47 - /* Preview Overlay Mode */
48 - .preview-mode #app-wrapper { display: none; }
49 - .preview-mode #print-wrapper { display: block; background: #525659; min-height: 100vh; padding-bottom: 50px; }
50 - #print-wrapper { display: none; }
51 - .paper-sheet { background: white; color: black; width: 210mm; min-height: 297mm; margin: 20px auto; padding: 20mm; box-shadow: 0 0 15px rgba(0,0,0,0.5); direction: rtl; }
52 - </style>
4 + <meta charset="utf-8">
5 + <meta name="viewport" content="width=device-width, initial-scale=1">
6 + <title>Aram — رابط قدیمی قرنطینه شده است</title>
7 + <style>
8 + :root {
9 + color-scheme: dark;
10 + font-family: Tahoma, Arial, sans-serif;
11 + background: #07111f;
12 + color: #e5edf8;
13 + }
14 + body {
15 + min-height: 100vh;
16 + margin: 0;
17 + display: grid;
18 + place-items: center;
19 + padding: 24px;
20 + box-sizing: border-box;
21 + }
22 + main {
23 + width: min(720px, 100%);
24 + padding: 32px;
25 + border: 2px solid #f59e0b;
26 + border-radius: 16px;
27 + background: #111c2e;
28 + box-shadow: 0 18px 60px rgb(0 0 0 / 35%);
29 + }
30 + h1 { color: #fbbf24; margin-top: 0; }
31 + p { line-height: 2; }
32 + .status {
33 + display: inline-block;
34 + margin-top: 12px;
35 + padding: 8px 12px;
36 + border-radius: 999px;
37 + background: #7f1d1d;
38 + color: #fecaca;
39 + font-weight: 700;
40 + }
41 + </style>
42 </head>
54 -<body class="bg-slate-950 text-slate-100 antialiased min-h-screen">
55 -
56 - <!-- ==========================================
57 - محیط کاربری اپلیکیشن (App Wrapper)
58 - ========================================== -->
59 - <div id="app-wrapper" class="flex flex-col min-h-screen">
60 - <header class="bg-slate-900 border-b border-slate-800 p-3 md:p-4 sticky top-0 z-50 shadow-2xl">
61 - <div class="max-w-7xl mx-auto space-y-3">
62 - <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-800/80 pb-2.5">
63 - <div class="flex items-center gap-2.5">
64 - <div class="p-2 bg-indigo-600 text-white rounded-lg shadow-md">
65 - <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
66 - </div>
67 - <div>
68 - <h1 class="font-bold text-white text-xs md:text-sm">هسته یکپارچه صدور صورت‌های مالی (Jules Ready)</h1>
69 - <p class="text-[10px] text-emerald-400">بستر قطعی ۱۴۰۲ تا ۱۴۰۴ - آماده اتصال API برای سال ۱۴۰۵</p>
70 - </div>
71 - </div>
72 - <div class="flex items-center gap-2">
73 - <span class="text-[11px] font-mono font-bold text-slate-300 bg-slate-800 border border-slate-700 px-2.5 py-1.5 rounded-lg">واحد: میلیون ریال</span>
74 - <button onclick="openPrintPreview()" class="flex items-center gap-1.5 bg-emerald-600 hover:bg-emerald-500 text-white text-[11px] font-bold px-4 py-2 rounded-lg transition-all shadow-md ring-2 ring-emerald-400/50">
75 - 🖨️ تولید پکیج چاپ (مدیریتی)
76 - </button>
77 - </div>
78 - </div>
79 -
80 - <div class="grid grid-cols-1 md:grid-cols-2 gap-2.5 bg-slate-950 p-2.5 rounded-xl border border-slate-800">
81 - <div class="space-y-1">
82 - <label class="text-[11px] font-bold text-blue-400">انتخاب شرکت:</label>
83 - <select id="companySelector" onchange="onCompanyChange(this.value)" class="bg-slate-900 border border-slate-700 text-white text-xs font-semibold rounded-lg px-2.5 py-2 w-full outline-none">
84 - <option value="C_GAS_TRANS">🏭 شرکت انتقال گاز ایران (سهامی خاص)</option>
85 - <option value="C_SISTAN">🏬 شرکت گاز استان سیستان و بلوچستان</option>
86 - </select>
87 - </div>
88 - <div class="space-y-1">
89 - <label class="text-[11px] font-bold text-emerald-400">انتخاب سال مالی (سورس قطعی):</label>
90 - <select id="yearSelector" onchange="onYearChange(this.value)" class="bg-slate-900 border border-slate-700 text-white text-xs font-semibold rounded-lg px-2.5 py-2 w-full outline-none font-mono">
91 - <option value="1404">📅 سال ۱۴۰۴ (گزارش نهایی حسابرسی شده)</option>
92 - <option value="1403">📅 سال ۱۴۰۳ (گزارش نهایی حسابرسی شده)</option>
93 - <option value="1402">📅 سال ۱۴۰۲ (گزارش نهایی حسابرسی شده)</option>
94 - </select>
95 - </div>
96 - </div>
97 -
98 - <div class="flex items-center gap-1.5 overflow-x-auto pb-1 pt-0.5 scrollbar-none border-t border-slate-800">
99 - <button onclick="switchTab('AUDITOR')" id="tab-AUDITOR" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap bg-indigo-600 text-white shadow-md">⚖️ گزارش حسابرس و AI</button>
100 - <button onclick="switchTab('BS')" id="tab-BS" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-slate-300 hover:bg-slate-800">📋 ترازنامه</button>
101 - <button onclick="switchTab('IS')" id="tab-IS" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-slate-300 hover:bg-slate-800">📈 سود و زیان</button>
102 - <button onclick="switchTab('EQUITY')" id="tab-EQUITY" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-slate-300 hover:bg-slate-800">📊 حقوق مالکانه</button>
103 - <button onclick="switchTab('CF')" id="tab-CF" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-slate-300 hover:bg-slate-800">🔄 جریان‌های نقدی</button>
104 - <button onclick="switchTab('MAPPING')" id="tab-MAPPING" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-purple-400 hover:bg-slate-800">🔗 موتور نگاشت (O/Oe/E)</button>
105 - <button onclick="switchTab('UPLOAD')" id="tab-UPLOAD" class="report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-emerald-400 hover:bg-slate-800">☁️ ایجاد سال جدید (1405)</button>
106 - </div>
107 - </div>
108 - </header>
109 -
110 - <main class="flex-1 p-3 md:p-6 max-w-7xl mx-auto w-full space-y-4">
111 - <div id="tabContent" class="min-h-[400px]"></div>
112 - </main>
113 - </div>
114 -
115 - <!-- ==========================================
116 - محیط پیش‌نمایش و چاپ (Print Wrapper)
117 - ========================================== -->
118 - <div id="print-wrapper">
119 - <div class="print-controls bg-slate-900 p-4 sticky top-0 z-50 flex justify-between items-center shadow-2xl border-b-4 border-emerald-500">
120 - <div class="text-white font-bold flex items-center gap-2">
121 - <span class="text-2xl">🖨️</span>
122 - <span>پیش‌نمایش پکیج نهایی - آماده ارسال به پرینتر</span>
123 - </div>
124 - <div class="flex gap-3">
125 - <button onclick="closePrintPreview()" class="bg-rose-600 hover:bg-rose-500 text-white px-5 py-2 rounded-lg font-bold transition-all">✖ لغو و بازگشت</button>
126 - <button onclick="window.print()" class="bg-emerald-600 hover:bg-emerald-500 text-white px-6 py-2 rounded-lg font-bold transition-all shadow-lg ring-2 ring-emerald-400">✓ چاپ نهایی (Print)</button>
127 - </div>
128 - </div>
129 - <div id="print-pages-container"></div>
130 - </div>
131 -
132 - <!-- ==========================================
133 - Core JavaScript & Database
134 - ========================================== -->
135 - <script>
136 - // State
137 - let currentCompanyId = 'C_GAS_TRANS';
138 - let currentYear = '1404';
139 - let currentTab = 'AUDITOR';
140 -
141 - // ---------------------------------------------------------
142 - // DATABASE (The Single Source of Truth from PDFs & CSVs)
143 - // ---------------------------------------------------------
144 - const DB = {
145 - 'C_GAS_TRANS': {
146 - '1404': {
147 - hasRealData: true,
148 - auditorOpinion: 'مقبول (با بندهای تاکید بر مطلب خاص)',
149 - auditorClauses: [
150 - { type: 'تاکید بر مطلب خاص', title: 'بند ۴: مطالبات و بدهی‌ها', desc: 'همانگونه که در یادداشت ۱۸ منعکس است، تعیین تکلیف قطعی صورت‌حساب‌های متقابل با شرکت ملی گاز نیازمند تسویه نهایی است.' },
151 - { type: 'تاکید بر مطلب خاص', title: 'بند ۵: وضعیت مالیاتی', desc: 'برگ تشخیص مالیات عملکرد و ارزش افزوده سال‌های ۱۴۰۰ و ۱۴۰۱ صادر شده و شرکت در حال پیگیری در هیات‌های حل اختلاف مالیاتی می‌باشد.' },
152 - { type: 'تاکید بر مطلب خاص', title: 'بند ۶: اموال طرح‌های عمرانی', desc: 'انتقال اموال مرتبط با خط لوله ششم سراسری (BOT) از طرف شرکت مهندسی توسعه گاز قطعی شده و به عنوان تعدیلات سنواتی در حقوق مالکانه اعمال گردید.' }
153 - ],
154 - signatures: [
155 - { name: 'پیمان خضرایی', role: 'نایب رئیس هیئت مدیره و مدیرعامل' },
156 - { name: 'مسعود زردویان', role: 'رئیس هیئت مدیره' },
157 - { name: 'سعید نفری اقدم', role: 'عضو هیئت مدیره و مدیر مالی' }
158 - ],
159 - BS: {
160 - '101': { title: 'دارایی‌های ثابت مشهود', ycur: 673740637, ycomp1: 502938206, ycomp2: 429540560 },
161 - '102': { title: 'دارایی‌های نامشهود', ycur: 242194, ycomp1: 216237, ycomp2: 214276 },
162 - '103': { title: 'دریافتنی‌های بلندمدت', ycur: 8310168, ycomp1: 10811230, ycomp2: 6652479 },
163 - '201': { title: 'پیش‌پرداخت‌ها', ycur: 6839535, ycomp1: 3354446, ycomp2: 8000766 },
164 - '202': { title: 'موجودی مواد و کالا', ycur: 11273650, ycomp1: 8305043, ycomp2: 6818189 },
165 - '203': { title: 'دریافتنی‌های کوتاه‌مدت', ycur: 13386398, ycomp1: 14980468, ycomp2: 15993056 },
166 - '204': { title: 'موجودی نقد', ycur: 19951136, ycomp1: 3368287, ycomp2: 2134188 },
167 - '301': { title: 'سرمایه ثبت شده', ycur: 20000000, ycomp1: 20000000, ycomp2: 20000000 },
168 - '302': { title: 'افزایش سرمایه در جریان', ycur: 0, ycomp1: 0, ycomp2: 14069826 },
169 - '303': { title: 'اندوخته قانونی', ycur: 1614, ycomp1: 1614, ycomp2: 1614 },
170 - '304': { title: 'زیان انباشته', ycur: -203887074, ycomp1: -124518176, ycomp2: -110226573 },
171 - '401': { title: 'پرداختنی‌های بلندمدت', ycur: 630414220, ycomp1: 466724525, ycomp2: 419375071 },
172 - '402': { title: 'ذخیره مزایای پایان خدمت', ycur: 133078121, ycomp1: 94199107, ycomp2: 77644296 },
173 - '501': { title: 'پرداختنی‌های جاری', ycur: 145341976, ycomp1: 83315373, ycomp2: 46997254 },
174 - '502': { title: 'مالیات پرداختنی', ycur: 8833412, ycomp1: 4285509, ycomp2: 1363294 },
175 - '503': { title: 'پیش‌دریافت‌ها', ycur: 61449, ycomp1: 65965, ycomp2: 135627 }
176 - },
177 - IS: {
178 - '601': { title: 'درآمدهای عملیاتی', cur: 243097686, comp: 174585508 },
179 - '602': { title: 'بهای تمام شده درآمدهای عملیاتی', cur: -245897444, comp: -176383618 },
180 - '603': { title: 'هزینه‌های فروش، اداری و عمومی', cur: -62814143, comp: -25354498 },
181 - '604': { title: 'سایر درآمدهای عملیاتی', cur: 1543514, comp: 1085594 },
182 - '605': { title: 'سایر درآمدها و هزینه‌های غیرعملیاتی', cur: -10601182, comp: 627800 },
183 - '606': { title: 'هزینه مالیات بر درآمد', cur: -4697329, comp: -2922215 }
184 - },
185 - CF: {
186 - '701': { title: 'نقد حاصل از عملیات', cur: 99230533, comp: 83057773 },
187 - '702': { title: 'پرداخت‌های نقدی بابت مالیات', cur: -149426, comp: 0 },
188 - '801': { title: 'خرید دارایی‌های ثابت مشهود', cur: -82458602, comp: -81875240 },
189 - '802': { title: 'خرید دارایی‌های نامشهود', cur: -52212, comp: -23890 }
190 - },
191 - EQ: [
192 - { title: 'مانده در ۱۴۰۳/۰۱/۰۱', c1: '-', c2: 14069826, c3: -38949540, total: -23264098 },
193 - { title: 'اصلاح اشتباهات (خط ۶ BOT)', c1: '-', c2: '-', c3: -73020980, total: -73020980 },
194 - { title: 'مانده تجدید ارائه شده در ۱۴۰۳/۰۱/۰۱', c1: '-', c2: 14069826, c3: -110226573, total: -76155133, highlight: true },
195 - { title: 'زیان خالص تجدید ارائه شده سال ۱۴۰۳', c1: '-', c2: '-', c3: -28361429, total: -28361429 },
196 - { title: 'ثبت افزایش سرمایه', c1: 20000000, c2: -14069826, c3: '-', total: 5930174 },
197 - { title: 'مانده در ۱۴۰۳/۱۲/۳۰', c1: 20000000, c2: '-', c3: -124518176, total: -104516562, highlight: true },
198 - { title: 'زیان خالص سال مالی ۱۴۰۴', c1: '-', c2: '-', c3: -79368898, total: -79368898 },
199 - { title: 'مانده در پایان سال مالی ۱۴۰۴/۱۲/۲۹', c1: 20000000, c2: '-', c3: -203887074, total: -183885460, highlight: true }
200 - ]
201 - },
202 - '1403': {
203 - hasRealData: true,
204 - auditorOpinion: 'مقبول (با بند تاکید)',
205 - auditorClauses: [{ type: 'تاکید بر مطلب خاص', title: 'بند ۴', desc: 'مغایرت حساب‌های فی‌مابین با شرکت ملی گاز نیازمند رفع می‌باشد.' }],
206 - signatures: [
207 - { name: 'مسعود زردویان', role: 'رئیس هیئت مدیره' },
208 - { name: 'پیمان خضرایی', role: 'نایب رئیس هیئت مدیره و مدیرعامل' },
209 - { name: 'سعید نفری اقدم', role: 'عضو هیئت مدیره و مدیر مالی' }
210 - ],
211 - BS: {
212 - '101': { title: 'دارایی‌های ثابت مشهود', ycur: 502938206, ycomp1: 429540560, ycomp2: 380000000 },
213 - '102': { title: 'دارایی‌های نامشهود', ycur: 216237, ycomp1: 214276, ycomp2: 200000 },
214 - '103': { title: 'دریافتنی‌های بلندمدت', ycur: 10811230, ycomp1: 6652479, ycomp2: 5000000 },
215 - '201': { title: 'پیش‌پرداخت‌ها', ycur: 3354446, ycomp1: 8000766, ycomp2: 6000000 },
216 - '202': { title: 'موجودی مواد و کالا', ycur: 8305043, ycomp1: 6818189, ycomp2: 5500000 },
217 - '203': { title: 'دریافتنی‌های کوتاه‌مدت', ycur: 14980468, ycomp1: 15993056, ycomp2: 12000000 },
218 - '204': { title: 'موجودی نقد', ycur: 3368287, ycomp1: 2134188, ycomp2: 1800000 },
219 - '301': { title: 'سرمایه ثبت شده', ycur: 20000000, ycomp1: 20000000, ycomp2: 20000000 },
220 - '302': { title: 'افزایش سرمایه در جریان', ycur: 0, ycomp1: 14069826, ycomp2: 0 },
221 - '303': { title: 'اندوخته قانونی', ycur: 1614, ycomp1: 1614, ycomp2: 1614 },
222 - '304': { title: 'زیان انباشته', ycur: -124518176, ycomp1: -110226573, ycomp2: -95000000 },
223 - '401': { title: 'پرداختنی‌های بلندمدت', ycur: 466724525, ycomp1: 419375071, ycomp2: 380000000 },
224 - '402': { title: 'ذخیره مزایای پایان خدمت', ycur: 94199107, ycomp1: 77644296, ycomp2: 65000000 },
225 - '501': { title: 'پرداختنی‌های جاری', ycur: 83315373, ycomp1: 46997254, ycomp2: 38000000 },
226 - '502': { title: 'مالیات پرداختنی', ycur: 4285509, ycomp1: 1363294, ycomp2: 1000000 },
227 - '503': { title: 'پیش‌دریافت‌ها', ycur: 65965, ycomp1: 135627, ycomp2: 100000 }
228 - },
229 - IS: {
230 - '601': { title: 'درآمدهای عملیاتی', cur: 174585508, comp: 123297650 },
231 - '602': { title: 'بهای تمام شده درآمدهای عملیاتی', cur: -157476581, comp: -123355486 },
232 - '603': { title: 'هزینه‌های فروش، اداری و عمومی', cur: -25354498, comp: -19618654 },
233 - '604': { title: 'سایر درآمدهای عملیاتی', cur: 1085594, comp: 1421110 },
234 - '605': { title: 'سایر درآمدها و هزینه‌های غیرعملیاتی', cur: 1713394, comp: 2545735 },
235 - '606': { title: 'هزینه مالیات بر درآمد', cur: -2922215, comp: 0 }
236 - },
237 - CF: {
238 - '701': { title: 'نقد حاصل از عملیات', cur: 83057772, comp: 29242666 },
239 - '801': { title: 'خرید دارایی‌های ثابت مشهود', cur: -81875239, comp: -33462659 }
240 - },
241 - EQ: [
242 - { title: 'مانده در ۱۴۰۲/۰۱/۰۱', c1: 20000000, c2: '-', c3: -57311335, total: -37309721 },
243 - { title: 'مانده در ۱۴۰۲/۱۲/۲۹', c1: 20000000, c2: 14069826, c3: -110226573, total: -76156747, highlight: true },
244 - { title: 'زیان خالص سال ۱۴۰۳', c1: '-', c2: '-', c3: -9454392, total: -9454392 },
245 - { title: 'مانده پایان سال ۱۴۰۳/۱۲/۳۰', c1: 20000000, c2: '-', c3: -124518176, total: -104518176, highlight: true }
246 - ]
247 - },
248 - '1402': {
249 - hasRealData: true,
250 - auditorOpinion: 'مقبول',
251 - signatures: [
252 - { name: 'ابوالفضل وروانی فراهانی', role: 'رئیس هیئت مدیره' },
253 - { name: 'غلامعباس حسینی', role: 'نایب رئیس هیئت مدیره و مدیرعامل' }
254 - ],
255 - BS: {
256 - '101': { title: 'دارایی‌های ثابت مشهود', ycur: 429540560, ycomp1: 380000000, ycomp2: null },
257 - '102': { title: 'دارایی‌های نامشهود', ycur: 214276, ycomp1: 200000, ycomp2: null },
258 - '103': { title: 'دریافتنی‌های بلندمدت', ycur: 6652479, ycomp1: 5000000, ycomp2: null },
259 - '201': { title: 'پیش‌پرداخت‌ها', ycur: 8000766, ycomp1: 6000000, ycomp2: null },
260 - '202': { title: 'موجودی مواد و کالا', ycur: 6818189, ycomp1: 5500000, ycomp2: null },
261 - '203': { title: 'دریافتنی‌های کوتاه‌مدت', ycur: 15993056, ycomp1: 12000000, ycomp2: null },
262 - '204': { title: 'موجودی نقد', ycur: 2134188, ycomp1: 1800000, ycomp2: null },
263 - '301': { title: 'سرمایه ثبت شده', ycur: 20000000, ycomp1: 20000000, ycomp2: null },
264 - '302': { title: 'افزایش سرمایه در جریان', ycur: 14069826, ycomp1: 0, ycomp2: null },
265 - '303': { title: 'اندوخته قانونی', ycur: 1614, ycomp1: 1614, ycomp2: null },
266 - '304': { title: 'زیان انباشته', ycur: -110226573, ycomp1: -95000000, ycomp2: null },
267 - '401': { title: 'پرداختنی‌های بلندمدت', ycur: 419375071, ycomp1: 380000000, ycomp2: null },
268 - '402': { title: 'ذخیره مزایای پایان خدمت', ycur: 77644296, ycomp1: 65000000, ycomp2: null },
269 - '501': { title: 'پرداختنی‌های جاری', ycur: 46997254, ycomp1: 38000000, ycomp2: null },
270 - '502': { title: 'مالیات پرداختنی', ycur: 1363294, ycomp1: 1000000, ycomp2: null },
271 - '503': { title: 'پیش‌دریافت‌ها', ycur: 135627, ycomp1: 100000, ycomp2: null }
272 - },
273 - IS: {
274 - '601': { title: 'درآمدهای عملیاتی', cur: 123297650, comp: 110816554 },
275 - '602': { title: 'بهای تمام شده درآمدهای عملیاتی', cur: -123355486, comp: -105604143 },
276 - '603': { title: 'هزینه‌های فروش، اداری و عمومی', cur: -19618654, comp: -16066043 },
277 - '604': { title: 'سایر درآمدهای عملیاتی', cur: 1421110, comp: 222669 },
278 - '605': { title: 'سایر درآمدها و هزینه‌های غیرعملیاتی', cur: 2545735, comp: 1109158 },
279 - '606': { title: 'هزینه مالیات بر درآمد', cur: 0, comp: -1068664 }
280 - },
281 - CF: {
282 - '701': { title: 'نقد حاصل از عملیات', cur: 29242666, comp: 26068197 },
283 - '801': { title: 'خرید دارایی‌های ثابت مشهود', cur: -33462659, comp: -21323048 }
284 - },
285 - EQ: [
286 - { title: 'مانده در ۱۴۰۱/۰۱/۰۱', c1: 20000000, c2: '-', c3: -13252899, total: 6748715 },
287 - { title: 'زیان خالص سال ۱۴۰۲', c1: '-', c2: '-', c3: -15709645, total: -15709645 },
288 - { title: 'مانده در ۱۴۰۲/۱۲/۲۹', c1: 20000000, c2: 14069826, c3: -110226573, total: -90226573, highlight: true }
289 - ]
290 - }
291 - },
292 - 'C_SISTAN': {
293 - '1402': {
294 - hasRealData: true,
295 - auditorOpinion: 'مقبول',
296 - auditorClauses: [{ type: 'تاکید بر مطلب', title: 'بند ۴', desc: 'عدم تحقق بودجه تخصیصی گازرسانی چابهار.' }],
297 - signatures: [
298 - { name: 'حسین سلیمی', role: 'رئیس هیئت مدیره' },
299 - { name: 'محمدرضا میرشکاری', role: 'نایب رئیس هیئت مدیره و مدیرعامل' },
300 - { name: 'علی خسروی', role: 'عضو هیئت مدیره' }
301 - ],
302 - BS: {
303 - '101': { title: 'دارایی‌های ثابت مشهود', ycur: 6785191, ycomp1: 5214080, ycomp2: null },
304 - '102': { title: 'دارایی‌های نامشهود', ycur: 210, ycomp1: 210, ycomp2: null },
305 - '103': { title: 'دریافتنی‌های بلندمدت', ycur: 0, ycomp1: 0, ycomp2: null },
306 - '201': { title: 'پیش‌پرداخت‌ها', ycur: 399120, ycomp1: 280000, ycomp2: null },
307 - '202': { title: 'موجودی مواد و کالا', ycur: 74200, ycomp1: 65000, ycomp2: null },
308 - '203': { title: 'دریافتنی‌های کوتاه‌مدت', ycur: 2765672, ycomp1: 2100000, ycomp2: null },
309 - '204': { title: 'موجودی نقد', ycur: 43730, ycomp1: 31000, ycomp2: null },
310 - '301': { title: 'سرمایه ثبت شده', ycur: 10000, ycomp1: 10000, ycomp2: null },
311 - '302': { title: 'افزایش سرمایه در جریان', ycur: 0, ycomp1: 0, ycomp2: null },
312 - '303': { title: 'اندوخته قانونی', ycur: 0, ycomp1: 0, ycomp2: null },
313 - '304': { title: 'زیان انباشته', ycur: -1949156, ycomp1: -1529841, ycomp2: null },
314 - '401': { title: 'پرداختنی‌های بلندمدت', ycur: 5319747, ycomp1: 4100000, ycomp2: null },
315 - '402': { title: 'ذخیره مزایای پایان خدمت', ycur: 111860, ycomp1: 85000, ycomp2: null },
316 - '501': { title: 'پرداختنی‌های جاری', ycur: 6575672, ycomp1: 5025131, ycomp2: null },
317 - '502': { title: 'مالیات پرداختنی', ycur: 0, ycomp1: 0, ycomp2: null },
318 - '503': { title: 'پیش‌دریافت‌ها', ycur: 0, ycomp1: 0, ycomp2: null }
319 - },
320 - IS: {
321 - '601': { title: 'درآمدهای عملیاتی', cur: 1880816, comp: 1420000 },
322 - '602': { title: 'بهای تمام شده درآمدهای عملیاتی', cur: -1950000, comp: -1480000 },
323 - '603': { title: 'هزینه‌های عمومی و اداری', cur: -350131, comp: -280000 },
324 - '604': { title: 'سایر درآمدهای عملیاتی', cur: 0, comp: 0 },
325 - '605': { title: 'سایر درآمدها و هزینه‌های غیرعملیاتی', cur: 0, comp: 0 },
326 - '606': { title: 'هزینه مالیات بر درآمد', cur: 0, comp: 0 }
327 - },
328 - CF: {
329 - '701': { title: 'نقد حاصل از عملیات', cur: 80000, comp: 50000 },
330 - '801': { title: 'خرید دارایی‌های ثابت مشهود', cur: -60000, comp: -40000 }
331 - },
332 - EQ: [
333 - { title: 'مانده در ۱۴۰۱/۱۲/۲۹', c1: 10000, c2: '-', c3: -1529841, total: -1519841 },
334 - { title: 'زیان خالص سال ۱۴۰۲', c1: '-', c2: '-', c3: -419315, total: -419315 },
335 - { title: 'مانده پایان سال ۱۴۰۲/۱۲/۲۹', c1: 10000, c2: '-', c3: -1949156, total: -1939156, highlight: true }
336 - ]
337 - }
338 - }
339 - };
340 -
341 - const MAPPING_RULES = [
342 - { code: '1101', name: 'بهای تمام شده درآمدهای عملیاتی', note: '6', type: 'O (مبدأ)' },
343 - { code: '8348', name: 'پرداختنی های تجاری و غیر تجاری (جاری)', note: '19-1', type: 'E (ورود)' },
344 - { code: '8348', name: 'پرداختنی بلند مدت (اشخاص وابسته)', note: '19-2', type: 'Oe (خروج)' },
345 - { code: '8161', name: 'پیش پرداخت های سرمایه ای', note: '10', type: 'O (مبدأ)' },
346 - { code: '118901', name: 'پروژه‌های در جریان تکمیل (BOT)', note: '22', type: 'E (ورود)' }
347 - ];
348 -
349 - const COMPANIES_INFO = {
350 - 'C_GAS_TRANS': 'شرکت انتقال گاز ایران (سهامی خاص)',
351 - 'C_SISTAN': 'شرکت گاز استان سیستان و بلوچستان'
352 - };
353 -
354 - // --- UTILS ---
355 - function fmt(num) {
356 - if (num === null || num === undefined || num === '-' || num === 0) return num === 0 ? '۰' : '-';
357 - const absFormatted = Math.abs(num).toLocaleString('fa-IR');
358 - return num < 0 ? `(${absFormatted})` : absFormatted;
359 - }
360 -
361 - function checkDataAvailable(compId, year) {
362 - return !!(DB[compId] && DB[compId][year] && DB[compId][year].hasRealData);
363 - }
364 -
365 - // ---------------------------------------------------------
366 - // UI RENDER ENGINE
367 - // ---------------------------------------------------------
368 - function render() {
369 - document.getElementById('companySelector').value = currentCompanyId;
370 - document.getElementById('yearSelector').value = currentYear;
371 -
372 - const tabs = ['AUDITOR', 'BS', 'IS', 'EQUITY', 'CF', 'MAPPING', 'UPLOAD'];
373 - tabs.forEach(t => {
374 - const btn = document.getElementById(`tab-${t}`);
375 - if (!btn) return;
376 -
377 - if (t === currentTab) {
378 - btn.className = "report-tab px-3 py-1.5 rounded-lg text-[11px] font-bold transition-all whitespace-nowrap text-white shadow-md " +
379 - (t === 'AUDITOR' ? 'bg-indigo-600' : (t === 'MAPPING' ? 'bg-purple-600' : (t === 'UPLOAD' ? 'bg-emerald-600' : 'bg-blue-600')));
380 - } else {
381 - btn.className = "report-tab px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all whitespace-nowrap hover:bg-slate-800 border border-transparent " +
382 - (t === 'MAPPING' ? 'text-purple-400 bg-purple-950/20' : (t === 'UPLOAD' ? 'text-emerald-400 bg-emerald-950/20' : 'text-slate-300'));
383 - }
384 - });
385 -
386 - const target = document.getElementById('tabContent');
387 - const isDataVerified = checkDataAvailable(currentCompanyId, currentYear);
388 -
389 - if (!isDataVerified && currentTab !== 'UPLOAD' && currentTab !== 'MAPPING') {
390 - target.innerHTML = `
391 - <div class="bg-slate-900 border border-slate-800 rounded-2xl p-8 text-center space-y-4 my-6 shadow-2xl">
392 - <div class="p-4 bg-amber-500/10 rounded-2xl text-amber-400 w-16 h-16 mx-auto flex items-center justify-center text-3xl">⚠️</div>
393 - <h3 class="font-bold text-white">گزارش نهایی سال ${currentYear} بارگذاری نشده است!</h3>
394 - <p class="text-xs text-slate-400">سیستم تنها گزارشات قطعی حسابرسی شده را نمایش می‌دهد. لطفا در محیط Jules تراز خام را ایمپورت کنید.</p>
395 - <button onclick="switchTab('UPLOAD')" class="bg-emerald-600 text-white px-4 py-2 rounded-lg font-bold text-xs mt-3">آپلود تراز خام (ایجاد سال جدید)</button>
396 - </div>
397 - `;
398 - return;
399 - }
400 -
401 - const data = DB[currentCompanyId]?.[currentYear];
402 -
403 - if (currentTab === 'AUDITOR') renderAuditorAndAI(target, data);
404 - else if (currentTab === 'BS') renderBS(target, data);
405 - else if (currentTab === 'IS') renderIS(target, data);
406 - else if (currentTab === 'EQUITY') renderEquity(target, data);
407 - else if (currentTab === 'CF') renderCF(target, data);
408 - else if (currentTab === 'MAPPING') renderMapping(target);
409 - else if (currentTab === 'UPLOAD') renderUploadForm(target);
410 - }
411 -
412 - // --- WEB VIEWS ---
413 -
414 - function renderAuditorAndAI(target, data) {
415 - const bs = data.BS; const is = data.IS;
416 - const curAssets = (bs['201'].ycur||0) + (bs['202'].ycur||0) + (bs['203'].ycur||0) + (bs['204'].ycur||0);
417 - const curLiab = (bs['501'].ycur||0) + (bs['502'].ycur||0) + (bs['503'].ycur||0);
418 - const totalAssets = curAssets + (bs['101'].ycur||0) + (bs['102'].ycur||0) + (bs['103'].ycur||0);
419 - const totalLiab = curLiab + (bs['401'].ycur||0) + (bs['402'].ycur||0);
420 - const revenue = is['601'].cur + (is['604'].cur||0);
421 - const netProfit = revenue + is['602'].cur + is['603'].cur + (is['605']?.cur||0) + (is['606']?.cur||0);
422 -
423 - const currentRatio = curLiab ? (curAssets / curLiab).toFixed(2) : 0;
424 - const debtRatio = totalAssets ? ((totalLiab / totalAssets) * 100).toFixed(1) : 0;
425 - const netMargin = revenue ? ((netProfit / revenue) * 100).toFixed(1) : 0;
426 -
427 - const crColor = currentRatio >= 1 ? 'emerald' : 'rose';
428 - const drColor = debtRatio < 60 ? 'emerald' : (debtRatio < 80 ? 'amber' : 'rose');
429 - const nmColor = netMargin > 0 ? 'emerald' : 'rose';
430 -
431 - let aiText = `بر اساس پایش هوشمند ترازنامه، نسبت جاری شرکت معادل <b>${currentRatio}</b> می‌باشد که نشان‌دهنده ${currentRatio >= 1 ? 'پوشش مناسب' : 'ریسک در'} نقدینگی است. نسبت بدهی به دارایی <b>${debtRatio}٪</b> است که بیانگر سطح ${debtRatio > 80 ? 'بالای' : 'متعادل'} اهرم مالی می‌باشد. حاشیه سود خالص <b>${netMargin}٪</b> برآورد شده که نیازمند ${netMargin < 0 ? 'مدیریت هزینه‌ها' : 'حفظ ثبات رویه'} است.`;
432 -
433 - target.innerHTML = `
434 - <div class="grid grid-cols-1 lg:grid-cols-12 gap-4">
435 - <div class="lg:col-span-7 bg-slate-900 border border-slate-800 rounded-xl p-5 shadow-xl">
436 - <div class="border-b border-slate-800 pb-4 mb-4 flex items-center justify-between">
437 - <div>
438 - <h2 class="font-bold text-white text-sm">گزارش حسابرس مستقل و بازرس قانونی</h2>
439 - <h3 class="text-[11px] text-slate-400 mt-1">به مجمع عمومی صاحبان سهام ${COMPANIES_INFO[currentCompanyId]}</h3>
440 - </div>
441 - <span class="text-xs font-mono bg-indigo-950 text-indigo-300 px-2 py-1 rounded">سال ${currentYear}</span>
442 - </div>
443 - <div class="bg-slate-950 border border-slate-800 p-4 rounded-lg mb-4">
444 - <h4 class="font-bold text-indigo-400 text-xs mb-2">اظهارنظر حسابرس:</h4>
445 - <p class="text-[11px] leading-6 text-slate-300 text-justify">به نظر این سازمان، صورت‌های مالی یاد شده، وضعیت مالی شرکت را در تاریخ پایان اسفند ${currentYear}، از تمام جنبه‌های بااهمیت، طبق استانداردهای حسابداری به نحو مطلوب نشان می‌دهد.</p>
446 - <div class="mt-3 inline-block bg-emerald-950/40 border border-emerald-800 text-emerald-400 px-3 py-1.5 rounded font-bold text-xs">
447 - نتیجه نهایی: ${data.auditorOpinion}
448 - </div>
449 - </div>
450 - ${data.auditorClauses ? `
451 - <div class="space-y-2">
452 - <h4 class="font-bold text-amber-400 text-xs mb-2">تاکید بر مطلب خاص:</h4>
453 - ${data.auditorClauses.map(c => `
454 - <div class="border-r-2 border-amber-500 bg-slate-950/50 p-3 rounded-l-lg">
455 - <h5 class="font-bold text-white text-[11px] mb-1">${c.title}</h5>
456 - <p class="text-[11px] text-slate-400 leading-5 text-justify">${c.desc}</p>
457 - </div>
458 - `).join('')}
459 - </div>
460 - ` : ''}
461 - </div>
462 -
463 - <!-- AI Dashboard -->
464 - <div class="lg:col-span-5 bg-slate-900 border border-slate-800 rounded-xl p-5 shadow-xl flex flex-col">
465 - <div class="border-b border-slate-800 pb-3 mb-4 flex items-center gap-2">
466 - <div class="p-1.5 bg-purple-600/20 text-purple-400 rounded-lg">🤖</div>
467 - <h2 class="font-bold text-white text-sm">داشبورد تحلیلی هوش مصنوعی (AI)</h2>
468 - </div>
469 - <div class="space-y-4 flex-1">
470 - <div class="bg-slate-950 p-3 rounded-lg border border-slate-800/50 flex justify-between items-center">
471 - <span class="text-[11px] text-slate-300 font-bold">نسبت نقدینگی (جاری)</span>
472 - <span class="text-lg font-mono font-bold text-${crColor}-400">${currentRatio}</span>
473 - </div>
474 - <div class="bg-slate-950 p-3 rounded-lg border border-slate-800/50 flex justify-between items-center">
475 - <span class="text-[11px] text-slate-300 font-bold">نسبت بدهی به دارایی</span>
476 - <span class="text-lg font-mono font-bold text-${drColor}-400">${debtRatio}٪</span>
477 - </div>
478 - <div class="bg-slate-950 p-3 rounded-lg border border-slate-800/50 flex justify-between items-center">
479 - <span class="text-[11px] text-slate-300 font-bold">حاشیه سود خالص</span>
480 - <span class="text-lg font-mono font-bold text-${nmColor}-400">${netMargin}٪</span>
481 - </div>
482 - <div class="bg-purple-950/20 border border-purple-900/30 p-3.5 rounded-lg mt-4 flex-1">
483 - <p class="text-[11px] text-slate-300 leading-6 text-justify">${aiText}</p>
484 - </div>
485 - </div>
486 - </div>
487 - </div>
488 - `;
489 - }
490 -
491 - function renderBS(target, data) {
492 - const bs = data.BS;
493 - const is3Col = bs['101'].ycomp2 !== null && bs['101'].ycomp2 !== undefined;
494 - const sumGr = (keys, col) => keys.reduce((a, k) => a + (bs[k][col] || 0), 0);
495 - const ncAs = ['101','102','103']; const cAs = ['201','202','203','204'];
496 - const eq = ['301','302','303','304']; const ncLi = ['401','402']; const cLi = ['501','502','503'];
497 -
498 - target.innerHTML = `
499 - <div class="space-y-4">
500 - <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
501 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-4 shadow-xl overflow-x-auto">
502 - <div class="border-b border-slate-800 pb-2 mb-3 flex justify-between min-w-[320px]">
503 - <h3 class="font-bold text-blue-400 text-sm">دارایی‌ها</h3>
504 - <div class="flex gap-2 text-[10px] font-mono text-slate-400 text-center">
505 - <span class="w-20 text-emerald-400">سال ${currentYear}</span><span class="w-20 text-amber-300">سال قبل</span>${is3Col ? `<span class="w-20">دو سال قبل</span>` : ''}
506 - </div>
507 - </div>
508 - <div class="text-[10px] font-bold text-slate-500 bg-slate-950 px-2 py-1 mb-1 rounded min-w-[320px]">دارایی‌های غیرجاری</div>
509 - ${ncAs.map(k => renderBSRow(bs[k], is3Col)).join('')}
510 - <div class="flex justify-between text-xs font-bold text-blue-400 mt-1 mb-3 bg-blue-950/20 p-2 rounded min-w-[320px]">
511 - <span>جمع دارایی غیرجاری</span>
512 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr(ncAs, 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr(ncAs, 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr(ncAs, 'ycomp2'))}</span>` : ''}</div>
513 - </div>
514 - <div class="text-[10px] font-bold text-slate-500 bg-slate-950 px-2 py-1 mb-1 rounded min-w-[320px]">دارایی‌های جاری</div>
515 - ${cAs.map(k => renderBSRow(bs[k], is3Col)).join('')}
516 - <div class="flex justify-between text-xs font-bold text-blue-400 mt-1 bg-blue-950/20 p-2 rounded min-w-[320px]">
517 - <span>جمع دارایی جاری</span>
518 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr(cAs, 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr(cAs, 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr(cAs, 'ycomp2'))}</span>` : ''}</div>
519 - </div>
520 - <div class="flex justify-between text-sm font-bold text-emerald-400 mt-4 bg-emerald-950/20 border border-emerald-900/50 p-3 rounded-lg min-w-[320px]">
521 - <span>جمع کل دارایی‌ها</span>
522 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr([...ncAs, ...cAs], 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr([...ncAs, ...cAs], 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr([...ncAs, ...cAs], 'ycomp2'))}</span>` : ''}</div>
523 - </div>
524 - </div>
525 -
526 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-4 shadow-xl overflow-x-auto">
527 - <div class="border-b border-slate-800 pb-2 mb-3 flex justify-between min-w-[320px]">
528 - <h3 class="font-bold text-indigo-400 text-sm">حقوق مالکانه و بدهی‌ها</h3>
529 - <div class="flex gap-2 text-[10px] font-mono text-slate-400 text-center">
530 - <span class="w-20 text-emerald-400">سال ${currentYear}</span><span class="w-20 text-amber-300">سال قبل</span>${is3Col ? `<span class="w-20">دو سال قبل</span>` : ''}
531 - </div>
532 - </div>
533 - <div class="text-[10px] font-bold text-slate-500 bg-slate-950 px-2 py-1 mb-1 rounded min-w-[320px]">حقوق مالکانه</div>
534 - ${eq.map(k => renderBSRow(bs[k], is3Col)).join('')}
535 - <div class="flex justify-between text-xs font-bold text-rose-400 mt-1 mb-3 bg-rose-950/20 p-2 rounded min-w-[320px]">
536 - <span>جمع حقوق مالکانه</span>
537 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr(eq, 'ycur'))}</span><span class="w-20 text-rose-400/80">${fmt(sumGr(eq, 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-rose-400/60">${fmt(sumGr(eq, 'ycomp2'))}</span>` : ''}</div>
538 - </div>
539 - <div class="text-[10px] font-bold text-slate-500 bg-slate-950 px-2 py-1 mb-1 rounded min-w-[320px]">بدهی‌های غیرجاری</div>
540 - ${ncLi.map(k => renderBSRow(bs[k], is3Col)).join('')}
541 - <div class="flex justify-between text-xs font-bold text-indigo-400 mt-1 mb-3 bg-indigo-950/20 p-2 rounded min-w-[320px]">
542 - <span>جمع بدهی غیرجاری</span>
543 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr(ncLi, 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr(ncLi, 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr(ncLi, 'ycomp2'))}</span>` : ''}</div>
544 - </div>
545 - <div class="text-[10px] font-bold text-slate-500 bg-slate-950 px-2 py-1 mb-1 rounded min-w-[320px]">بدهی‌های جاری</div>
546 - ${cLi.map(k => renderBSRow(bs[k], is3Col)).join('')}
547 - <div class="flex justify-between text-xs font-bold text-indigo-400 mt-1 bg-indigo-950/20 p-2 rounded min-w-[320px]">
548 - <span>جمع بدهی جاری</span>
549 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr(cLi, 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr(cLi, 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr(cLi, 'ycomp2'))}</span>` : ''}</div>
550 - </div>
551 - <div class="flex justify-between text-sm font-bold text-emerald-400 mt-4 bg-emerald-950/20 border border-emerald-900/50 p-3 rounded-lg min-w-[320px]">
552 - <span>جمع حقوق و بدهی‌ها</span>
553 - <div class="flex gap-2 text-center font-mono"><span class="w-20">${fmt(sumGr([...eq, ...ncLi, ...cLi], 'ycur'))}</span><span class="w-20 text-amber-300">${fmt(sumGr([...eq, ...ncLi, ...cLi], 'ycomp1'))}</span>${is3Col ? `<span class="w-20 text-slate-300">${fmt(sumGr([...eq, ...ncLi, ...cLi], 'ycomp2'))}</span>` : ''}</div>
554 - </div>
555 - </div>
556 - </div>
557 - </div>
558 - `;
559 - }
560 -
561 - function renderBSRow(row, is3Col) {
562 - if (!row) return '';
563 - return `
564 - <div class="flex justify-between text-[11px] py-1.5 px-1 border-b border-slate-800/50 min-w-[320px]">
565 - <span class="text-slate-300">${row.title}</span>
566 - <div class="flex gap-2 text-center font-mono font-bold">
567 - <span class="w-20 ${row.ycur < 0 ? 'text-rose-400' : 'text-white'}">${fmt(row.ycur)}</span>
568 - <span class="w-20 ${row.ycomp1 < 0 ? 'text-rose-400/80' : 'text-amber-300/90'}">${fmt(row.ycomp1)}</span>
569 - ${is3Col ? `<span class="w-20 ${row.ycomp2 < 0 ? 'text-rose-400/60' : 'text-slate-400'}">${fmt(row.ycomp2)}</span>` : ''}
570 - </div>
571 - </div>
572 - `;
573 - }
574 -
575 - function renderIS(target, data) {
576 - const is = data.IS;
577 - const grossCur = is['601'].cur + is['602'].cur;
578 - const grossComp = is['601'].comp + is['602'].comp;
579 - const opCur = grossCur + is['603'].cur + (is['604'].cur||0);
580 - const opComp = grossComp + is['603'].comp + (is['604'].comp||0);
581 - const netCur = opCur + (is['605']?.cur||0) + (is['606']?.cur||0);
582 - const netComp = opComp + (is['605']?.comp||0) + (is['606']?.comp||0);
583 -
584 - target.innerHTML = `
585 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-4 md:p-6 max-w-3xl mx-auto shadow-xl">
586 - <div class="border-b border-slate-800 pb-3 mb-4 flex justify-between">
587 - <h3 class="font-bold text-white text-sm">صورت سود و زیان جامع</h3>
588 - <div class="flex gap-4 text-xs font-mono text-slate-400"><span class="w-24 text-emerald-400 text-left">سال ${currentYear}</span><span class="w-24 text-amber-300 text-left">سال قبل</span></div>
589 - </div>
590 - <div class="space-y-2 text-xs">
591 - <div class="flex justify-between py-2 border-b border-slate-800"><span>${is['601'].title}</span><div class="flex gap-4 font-mono font-bold"><span class="w-24 text-left text-emerald-400">${fmt(is['601'].cur)}</span><span class="w-24 text-left text-amber-300">${fmt(is['601'].comp)}</span></div></div>
592 - <div class="flex justify-between py-2 border-b border-slate-800"><span>${is['602'].title}</span><div class="flex gap-4 font-mono font-bold"><span class="w-24 text-left text-rose-400">${fmt(is['602'].cur)}</span><span class="w-24 text-left text-rose-400/80">${fmt(is['602'].comp)}</span></div></div>
593 - <div class="flex justify-between py-2.5 bg-slate-950 px-3 rounded-lg border border-slate-800 font-bold"><span class="text-blue-400">سود (زیان) ناخالص</span><div class="flex gap-4 font-mono"><span class="w-24 text-left ${grossCur<0?'text-rose-400':'text-blue-400'}">${fmt(grossCur)}</span><span class="w-24 text-left ${grossComp<0?'text-rose-400/80':'text-amber-300'}">${fmt(grossComp)}</span></div></div>
594 - <div class="flex justify-between py-2 border-b border-slate-800 mt-2"><span>${is['603'].title}</span><div class="flex gap-4 font-mono font-bold"><span class="w-24 text-left text-rose-400">${fmt(is['603'].cur)}</span><span class="w-24 text-left text-rose-400/80">${fmt(is['603'].comp)}</span></div></div>
595 - <div class="flex justify-between py-2 border-b border-slate-800"><span>${is['604']?.title||'-'}</span><div class="flex gap-4 font-mono font-bold"><span class="w-24 text-left text-emerald-400">${fmt(is['604']?.cur)}</span><span class="w-24 text-left text-amber-300">${fmt(is['604']?.comp)}</span></div></div>
596 - <div class="flex justify-between py-2.5 bg-blue-950/30 px-3 rounded-lg border border-blue-900/50 font-bold"><span class="text-blue-300">سود (زیان) عملیاتی</span><div class="flex gap-4 font-mono"><span class="w-24 text-left ${opCur<0?'text-rose-400':'text-blue-300'}">${fmt(opCur)}</span><span class="w-24 text-left ${opComp<0?'text-rose-400/80':'text-amber-300'}">${fmt(opComp)}</span></div></div>
597 - <div class="flex justify-between py-4 bg-rose-950/30 px-4 rounded-xl border border-rose-500/40 font-bold mt-4 text-sm"><span class="text-rose-400">زیان خالص سال مالی</span><div class="flex gap-4 font-mono"><span class="w-24 text-left text-rose-400">${fmt(netCur)}</span><span class="w-24 text-left text-rose-400/80">${fmt(netComp)}</span></div></div>
598 - </div>
599 - </div>
600 - `;
601 - }
602 -
603 - function renderEquity(target, data) {
604 - const eqData = data.EQ;
605 - target.innerHTML = `
606 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-5 max-w-5xl mx-auto shadow-xl overflow-x-auto">
607 - <h3 class="font-bold text-white text-sm mb-4">صورت تغییرات در حقوق مالکانه (سال ${currentYear})</h3>
608 - <table class="w-full text-right text-xs min-w-[600px]">
609 - <thead class="bg-slate-950 text-slate-400 border-b border-slate-800 font-bold">
610 - <tr><th class="p-2">شرح</th><th class="p-2">سرمایه</th><th class="p-2">در جریان</th><th class="p-2">زیان انباشته</th><th class="p-2 text-emerald-400">جمع کل</th></tr>
611 - </thead>
612 - <tbody class="divide-y divide-slate-800 font-mono text-slate-300">
613 - ${eqData.map(row => `
614 - <tr class="${row.highlight ? 'bg-slate-950/80 font-bold text-white' : ''}">
615 - <td class="p-2 font-sans ${row.highlight ? 'text-amber-400' : ''}">${row.title}</td>
616 - <td class="p-2 ${row.c1 !== '-' ? 'text-emerald-400' : ''}">${fmt(row.c1)}</td>
617 - <td class="p-2">${fmt(row.c2)}</td>
618 - <td class="p-2 text-rose-400">${fmt(row.c3)}</td>
619 - <td class="p-2 ${row.total < 0 ? 'text-rose-400' : 'text-emerald-400'} font-bold">${fmt(row.total)}</td>
620 - </tr>
621 - `).join('')}
622 - </tbody>
623 - </table>
624 - </div>
625 - `;
626 - }
627 -
628 - function renderCF(target, data) {
629 - const cf = data.CF;
630 - const netOpCur = cf['701'].cur + (cf['702']?.cur||0);
631 - const netOpComp = cf['701'].comp + (cf['702']?.comp||0);
632 -
633 - target.innerHTML = `
634 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-6 max-w-3xl mx-auto shadow-xl">
635 - <h3 class="font-bold text-white text-sm mb-4 border-b border-slate-800 pb-2">صورت جریان‌های نقدی</h3>
636 - <div class="space-y-4 text-xs">
637 - <div class="space-y-2">
638 - <div class="font-bold text-blue-400 bg-slate-950 p-2 rounded">فعالیت‌های عملیاتی</div>
639 - <div class="flex justify-between py-1 px-2 border-b border-slate-800/50"><span>${cf['701'].title}</span><div class="flex gap-4 font-mono font-bold"><span class="w-24 text-left">${fmt(cf['701'].cur)}</span><span class="w-24 text-left text-amber-300/80">${fmt(cf['701'].comp)}</span></div></div>
640 - <div class="flex justify-between py-2 px-2 bg-blue-950/20 font-bold text-emerald-400 rounded"><span>خالص جریان عملیاتی</span><div class="flex gap-4 font-mono"><span class="w-24 text-left">${fmt(netOpCur)}</span><span class="w-24 text-left">${fmt(netOpComp)}</span></div></div>
641 - </div>
642 - <div class="flex justify-between py-3 px-4 bg-emerald-950/30 border border-emerald-800/50 rounded-lg mt-4 font-bold text-sm">
643 - <span class="text-white">مانده موجودی نقد در پایان سال</span>
644 - <div class="flex gap-4 font-mono text-emerald-400"><span class="w-24 text-left">${fmt(data.BS['204'].ycur)}</span><span class="w-24 text-left text-amber-300">${fmt(data.BS['204'].ycomp1)}</span></div>
645 - </div>
646 - </div>
647 - </div>
648 - `;
649 - }
650 -
651 - function renderMapping(target) {
652 - target.innerHTML = `
653 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-6 max-w-4xl mx-auto space-y-6 shadow-xl">
654 - <div class="text-center space-y-2 border-b border-slate-800 pb-4">
655 - <div class="text-4xl">🔗</div>
656 - <h2 class="font-bold text-purple-400 text-lg">کدینگ و منطق نگاشت برای سال ۱۴۰۵</h2>
657 - <p class="text-xs text-slate-400 max-w-xl mx-auto leading-6">این فرمول‌ها جهت پردازش O، Oe و E از فایل Data.csv استخراج و برای محیط Jules قفل شده‌اند.</p>
658 - </div>
659 - <table class="w-full text-right text-xs border border-slate-800">
660 - <thead class="bg-slate-950 text-slate-400">
661 - <tr><th class="p-3">کد حساب</th><th class="p-3">شرح</th><th class="p-3">نوع نگاشت</th><th class="p-3">یادداشت مقصد</th></tr>
662 - </thead>
663 - <tbody class="divide-y divide-slate-800 font-mono text-slate-300">
664 - ${MAPPING_RULES.map(m => `
665 - <tr>
666 - <td class="p-3 font-bold text-blue-400">${m.code}</td>
667 - <td class="p-3 font-sans">${m.name}</td>
668 - <td class="p-3 text-purple-400 font-bold">${m.type}</td>
669 - <td class="p-3 text-amber-400">${m.note}</td>
670 - </tr>
671 - `).join('')}
672 - </tbody>
673 - </table>
674 - </div>
675 - `;
676 - }
677 -
678 - function renderUploadForm(target) {
679 - target.innerHTML = `
680 - <div class="bg-slate-900 border border-slate-800 rounded-xl p-8 max-w-lg mx-auto shadow-xl text-center">
681 - <h3 class="font-bold text-emerald-400 text-base mb-6">➕ ساخت صورت‌های مالی ۱۴۰۵ در محیط Jules</h3>
682 - <div class="border-2 border-dashed border-slate-600 bg-slate-950/50 rounded-xl p-10 cursor-pointer hover:border-emerald-500 transition-colors" onclick="alert('برنامه‌نویس: در محیط Jules اینجا را به تابع file upload متصل کنید.')">
683 - <div class="text-5xl mb-4">📂</div>
684 - <h4 class="font-bold text-white mb-2">تراز آزمایشی ۱۴۰۵ را انتخاب کنید</h4>
685 - <p class="text-[10px] text-slate-400 mt-2 leading-5">پس از آپلود، توابع نگاشت (Mapping) فراخوانی شده و خروجی به آبجکت DB تزریق می‌شود.</p>
686 - </div>
687 - </div>
688 - `;
689 - }
690 -
691 - // --- ACTIONS ---
692 - function switchTab(tab) { currentTab = tab; render(); }
693 - function onCompanyChange(val) { currentCompanyId = val; render(); }
694 - function onYearChange(yr) { currentYear = yr; render(); }
695 -
696 - // ---------------------------------------------------------
697 - // FLAWLESS PRINT ENGINE (In-App Preview Overlay)
698 - // ---------------------------------------------------------
699 - function openPrintPreview() {
700 - const data = DB[currentCompanyId]?.[currentYear];
701 - if(!data || !data.hasRealData) return alert('خطا: گزارش مالی این سال هنوز قطعی و بارگذاری نشده است.');
702 -
703 - const container = document.getElementById('print-pages-container');
704 - const bs = data.BS; const is = data.IS; const cf = data.CF;
705 - const is3Col = bs['101'].ycomp2 !== null && bs['101'].ycomp2 !== undefined;
706 -
707 - const sumGr = (keys, col) => keys.reduce((a, k) => a + (bs[k][col] || 0), 0);
708 - const curAssets = sumGr(['201','202','203','204'], 'ycur');
709 - const curLiab = sumGr(['501','502','503'], 'ycur');
710 - const totalAssets = curAssets + sumGr(['101','102','103'], 'ycur');
711 - const totalLiab = curLiab + sumGr(['401','402'], 'ycur');
712 - const revenue = is['601'].cur + (is['604']?.cur||0);
713 - const netProfit = revenue + is['602'].cur + is['603'].cur + (is['605']?.cur||0) + (is['606']?.cur||0);
714 - const currentRatio = curLiab ? (curAssets / curLiab).toFixed(2) : 0;
715 - const debtRatio = totalAssets ? ((totalLiab / totalAssets) * 100).toFixed(1) : 0;
716 - const netMargin = revenue ? ((netProfit / revenue) * 100).toFixed(1) : 0;
717 -
718 - let html = ``;
719 -
720 - // PAGE 1: Signatures
721 - html += `
722 - <div class="paper-sheet print-page first-page">
723 - <div style="text-align:center; margin-bottom:50px;">
724 - <h2>مجمع عمومی عادی صاحبان سهام</h2>
725 - <h2 style="font-size: 18pt;">${COMPANIES_INFO[currentCompanyId]}</h2>
726 - <h3 style="border:none;">صورت‌های مالی سال مالی منتهی به اسفند ${currentYear}</h3>
727 - </div>
728 - <p style="text-align:justify; line-height:2.5; font-size:12pt; margin-bottom: 50px;">
729 - <b>با احترام،</b><br>
730 - به پیوست صورت‌های مالی ${COMPANIES_INFO[currentCompanyId]} مربوط به سال مالی منتهی به ۲۹ اسفند ${currentYear} تقدیم می‌شود.
731 - اجزای تشکیل‌دهنده صورت‌های مالی شامل ترازنامه، صورت سود و زیان جامع، صورت تغییرات در حقوق مالکانه و صورت جریان‌های نقدی می‌باشد.
732 - این صورت‌های مالی طبق استانداردهای حسابداری تهیه شده و به تایید هیئت مدیره شرکت رسیده است.
733 - </p>
734 - <div class="sign-grid">
735 - ${data.signatures ? data.signatures.map(s => `
736 - <div class="sign-box">
737 - ${s.name}
738 - <span class="sign-role">${s.role}</span>
739 - </div>
740 - `).join('') : '<div class="sign-box">امضا محفوظ</div>'}
741 - </div>
742 - </div>
743 - `;
744 -
745 - // PAGE 2: Auditor Report
746 - html += `
747 - <div class="paper-sheet print-page">
748 - <h3>گزارش حسابرس مستقل و بازرس قانونی</h3>
749 - <p style="text-align:center; font-size:11pt; margin-bottom: 30px;">شرکت ${COMPANIES_INFO[currentCompanyId]} - منتهی به اسفند ${currentYear}</p>
750 - <p style="line-height:2.5; text-align:justify; font-size:12pt;">
751 - <b>اظهارنظر:</b> به نظر این سازمان، صورت‌های مالی یاد شده، وضعیت مالی شرکت را در تاریخ پایان اسفند ${currentYear}، و عملکرد مالی و جریان‌های نقدی آن را از تمام جنبه‌های بااهمیت، طبق استانداردهای حسابداری به نحو مطلوب نشان می‌دهد. <b>(${data.auditorOpinion})</b>
752 - </p>
753 - `;
754 - if(data.auditorClauses) {
755 - data.auditorClauses.forEach(c => { html += `<p style="margin-top:20px; text-align:justify; line-height:2; font-size:11pt;"><b>${c.title}:</b> ${c.desc}</p>`; });
756 - }
757 - html += `</div>`;
758 -
759 - // PAGE 3: AI Dashboard Infographic
760 - html += `
761 - <div class="paper-sheet print-page">
762 - <h3 style="margin-bottom:30px;">داشبورد تحلیلی هوش مصنوعی (AI)</h3>
763 - <div class="ai-grid">
764 - <div class="ai-card">
765 - <div class="ai-title">نسبت جاری (نقدینگی)</div>
766 - <div class="ai-val">${currentRatio}</div>
767 - </div>
768 - <div class="ai-card">
769 - <div class="ai-title">نسبت بدهی به دارایی</div>
770 - <div class="ai-val">${debtRatio} ٪</div>
771 - </div>
772 - <div class="ai-card">
773 - <div class="ai-title">حاشیه سود خالص</div>
774 - <div class="ai-val">${netMargin} ٪</div>
775 - </div>
776 - </div>
777 - <div class="ai-analysis">
778 - <b>تحلیل سیستم مدیریتی:</b><br>
779 - بر اساس ارقام حسابرسی شده سال ${currentYear}، شاخص نقدینگی شرکت معادل ${currentRatio} ارزیابی می‌گردد.
780 - سطح اهرم مالی معادل ${debtRatio} درصد از کل دارایی‌هاست. عملکرد سودآوری شرکت پس از کسر تمامی هزینه‌ها، نشان‌دهنده حاشیه سود خالص ${netMargin} درصدی نسبت به درآمدهای عملیاتی می‌باشد.
781 - </div>
782 - </div>
783 - `;
784 -
785 - // PAGE 4: Balance Sheet
786 - html += `<div class="paper-sheet print-page"><h3>صورت وضعیت مالی (ترازنامه)</h3><table style="width:100%; text-align:right;"><tr><th>دارایی‌ها</th><th>سال ${currentYear}</th><th>سال قبل</th>${is3Col ? '<th>دو سال قبل</th>' : ''}<th>حقوق و بدهی‌ها</th><th>سال ${currentYear}</th><th>سال قبل</th>${is3Col ? '<th>دو سال قبل</th>' : ''}</tr>`;
787 - html += `<tr><td>جمع دارایی غیرجاری</td><td>${fmt(sumGr(['101','102','103'],'ycur'))}</td><td>${fmt(sumGr(['101','102','103'],'ycomp1'))}</td>${is3Col ? `<td>${fmt(sumGr(['101','102','103'],'ycomp2'))}</td>` : ''}<td>جمع حقوق مالکانه</td><td>${fmt(sumGr(['301','302','303','304'],'ycur'))}</td><td>${fmt(sumGr(['301','302','303','304'],'ycomp1'))}</td>${is3Col ? `<td>${fmt(sumGr(['301','302','303','304'],'ycomp2'))}</td>` : ''}</tr>`;
788 - html += `<tr><td>جمع دارایی جاری</td><td>${fmt(sumGr(['201','202','203','204'],'ycur'))}</td><td>${fmt(sumGr(['201','202','203','204'],'ycomp1'))}</td>${is3Col ? `<td>${fmt(sumGr(['201','202','203','204'],'ycomp2'))}</td>` : ''}<td>جمع بدهی‌ها</td><td>${fmt(sumGr(['401','402','501','502','503'],'ycur'))}</td><td>${fmt(sumGr(['401','402','501','502','503'],'ycomp1'))}</td>${is3Col ? `<td>${fmt(sumGr(['401','402','501','502','503'],'ycomp2'))}</td>` : ''}</tr>`;
789 - html += `<tr><td><b>جمع کل دارایی‌ها</b></td><td><b>${fmt(totalAssets)}</b></td><td><b>${fmt(sumGr(['101','102','103','201','202','203','204'],'ycomp1'))}</b></td>${is3Col ? `<td><b>${fmt(sumGr(['101','102','103','201','202','203','204'],'ycomp2'))}</b></td>` : ''}<td><b>جمع حقوق و بدهی‌ها</b></td><td><b>${fmt(sumGr(['301','302','303','304','401','402','501','502','503'],'ycur'))}</b></td><td><b>${fmt(sumGr(['301','302','303','304','401','402','501','502','503'],'ycomp1'))}</b></td>${is3Col ? `<td><b>${fmt(sumGr(['301','302','303','304','401','402','501','502','503'],'ycomp2'))}</b></td>` : ''}</tr></table></div>`;
790 -
791 - // PAGE 5: IS & CF
792 - const netComp = is['601'].comp+is['602'].comp+is['603'].comp+(is['604']?.comp||0)+(is['605']?.comp||0)+(is['606']?.comp||0);
793 - html += `<div class="paper-sheet print-page"><h3>صورت سود و زیان جامع</h3><table><tr><th>شرح</th><th>سال ${currentYear}</th><th>سال قبل</th></tr>`;
794 - html += `<tr><td>درآمدهای عملیاتی</td><td>${fmt(is['601'].cur)}</td><td>${fmt(is['601'].comp)}</td></tr>`;
795 - html += `<tr><td>بهای تمام شده درآمدهای عملیاتی</td><td>${fmt(is['602'].cur)}</td><td>${fmt(is['602'].comp)}</td></tr>`;
796 - html += `<tr><td>سود (زیان) ناخالص</td><td>${fmt(is['601'].cur+is['602'].cur)}</td><td>${fmt(is['601'].comp+is['602'].comp)}</td></tr>`;
797 - html += `<tr><td><b>زیان خالص سال مالی</b></td><td><b>${fmt(netProfit)}</b></td><td><b>${fmt(netComp)}</b></td></tr></table>`;
798 -
799 - html += `<h3 style="margin-top:40px;">صورت جریان‌های نقدی</h3><table><tr><th>شرح</th><th>سال ${currentYear}</th><th>سال قبل</th></tr>`;
800 - html += `<tr><td>نقد حاصل از عملیات</td><td>${fmt(cf['701'].cur)}</td><td>${fmt(cf['701'].comp)}</td></tr>`;
801 - html += `<tr><td><b>مانده موجودی نقد پایان سال</b></td><td><b>${fmt(bs['204'].ycur)}</b></td><td><b>${fmt(bs['204'].ycomp1)}</b></td></tr></table></div>`;
802 -
803 - container.innerHTML = html;
804 -
805 - // Switch UI to Print Preview state
806 - document.body.classList.add('preview-mode');
807 - }
808 -
809 - function closePrintPreview() {
810 - document.body.classList.remove('preview-mode');
811 - }
812 -
813 - // --- INIT ---
814 - function bootstrap() { render(); }
815 - if (document.readyState === 'complete') bootstrap();
816 - else document.addEventListener('DOMContentLoaded', bootstrap);
817 - </script>
43 +<body>
44 + <main role="alert">
45 + <h1>این رابط قدیمی قرنطینه شده است</h1>
46 + <p>
47 + این فایل قبلاً یک نمونهٔ نمایشی با داده‌های سخت‌کدنویسی‌شده بود و به
48 + بک‌اند Aram متصل نبود. استفاده از آن برای تهیه، بررسی یا چاپ صورت‌های
49 + مالی ممنوع است.
50 + </p>
51 + <p>
52 + رابط واقعی پایلوت باید فقط از مسیر کنترل‌شدهٔ V1، پس از ورود داده،
53 + Preflight، نگاشت تأییدشده و تطبیق خروجی اجرا شود.
54 + </p>
55 + <p lang="en" dir="ltr">
56 + LEGACY PROTOTYPE — QUARANTINED — NOT FOR PILOT OR FINANCIAL REPORTING
57 + </p>
58 + <span class="status">V1 Pilot UI: NOT YET RELEASED</span>
59 + </main>
60 </body>
819 -</html>
\ No newline at end of file
61 +</html>