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

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

Synced Dec 4, 05:30 UTC

source-data-cleanup
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 190 lines 5.95 KB
Raw
1 """Domain rules for editing the Pilot working state.
2
3 Pure validators/constructors that raise typed errors. The session store calls
4 these under its lock and records every change in the audit trail. Nothing here
5 guesses a financial value: a manually added account's closing balance is
6 derived from the accounting identity opening + debit - credit, and any edit
7 that would break referential integrity is rejected.
8 """
9
10 from __future__ import annotations
11
12 from decimal import Decimal, InvalidOperation
13
14 from aram_backend.pilot_engine import (
15 DEFERRED_STATEMENTS,
16 RENDERED_STATEMENTS,
17 NoteTarget,
18 PilotAccount,
19 PilotCompany,
20 )
21
22 STATEMENTS = frozenset(RENDERED_STATEMENTS) | frozenset(DEFERRED_STATEMENTS)
23 APPROVAL_STATUSES = frozenset({"Draft", "Reviewed", "Approved"})
24 ROW_STATUSES = frozenset({"Draft", "Reviewed", "Approved"})
25 COMPANY_STATUSES = frozenset({"Draft", "Approved", "Locked"})
26
27 # Workbench-added accounts use a reserved synthetic source-row range so they
28 # are never confused with real general-ledger source rows.
29 SYNTHETIC_SOURCE_ROW_BASE = 900_000
30
31
32 class EditingError(ValueError):
33 """Base class for rejected edits; message is safe to show to the user."""
34
35
36 class DuplicateAccountError(EditingError):
37 pass
38
39
40 class DuplicateNoteError(EditingError):
41 pass
42
43
44 class InvalidAccountError(EditingError):
45 pass
46
47
48 class InvalidNoteError(EditingError):
49 pass
50
51
52 class InvalidCompanyError(EditingError):
53 pass
54
55
56 class UnknownNoteError(EditingError):
57 pass
58
59
60 class NoteInUseError(EditingError):
61 pass
62
63
64 def _clean_code(value: str) -> str:
65 code = (value or "").strip()
66 if not code:
67 raise InvalidAccountError("کد نمی‌تواند خالی باشد.")
68 if code.startswith("="):
69 raise InvalidAccountError("کد باید متن ساده باشد؛ فرمول ممنوع است.")
70 return code
71
72
73 def _clean_text(value: str, field_fa: str) -> str:
74 text = (value or "").strip()
75 if not text:
76 raise InvalidAccountError(f"{field_fa} نمی‌تواند خالی باشد.")
77 return text
78
79
80 def parse_decimal(value, field_fa: str) -> Decimal:
81 if isinstance(value, bool):
82 raise InvalidAccountError(f"{field_fa} باید عدد باشد.")
83 try:
84 parsed = Decimal(str(value).strip())
85 except (InvalidOperation, ValueError, AttributeError) as exc:
86 raise InvalidAccountError(f"{field_fa} یک عدد معتبر نیست.") from exc
87 if not parsed.is_finite():
88 raise InvalidAccountError(f"{field_fa} نمی‌تواند NaN یا بی‌نهایت باشد.")
89 return parsed
90
91
92 def make_account(
93 *,
94 full_code: str,
95 name: str,
96 general_code: str,
97 general_name: str,
98 opening,
99 debit,
100 credit,
101 source_row: int,
102 row_status: str = "Draft",
103 subsidiary_code: str = "",
104 subsidiary_name: str = "",
105 ) -> PilotAccount:
106 """Build a validated account. Closing is derived, never invented."""
107 code = _clean_code(full_code)
108 account_name = _clean_text(name, "نام حساب")
109 gen_code = _clean_code(general_code)
110 gen_name = _clean_text(general_name, "نام حساب کل")
111 if row_status not in ROW_STATUSES:
112 raise InvalidAccountError("وضعیت سطر باید Draft، Reviewed یا Approved باشد.")
113 if not isinstance(source_row, int) or isinstance(source_row, bool) or source_row <= 0:
114 raise InvalidAccountError("سطر منبع باید یک عدد صحیح مثبت باشد.")
115 opening_d = parse_decimal(opening, "مانده ابتدای دوره")
116 debit_d = parse_decimal(debit, "گردش بدهکار")
117 credit_d = parse_decimal(credit, "گردش بستانکار")
118 closing_d = opening_d + debit_d - credit_d
119 return PilotAccount(
120 full_code=code,
121 name=account_name,
122 general_code=gen_code,
123 general_name=gen_name,
124 opening=opening_d,
125 debit=debit_d,
126 credit=credit_d,
127 closing=closing_d,
128 source_row=source_row,
129 row_status=row_status,
130 subsidiary_code=(subsidiary_code or "").strip(),
131 subsidiary_name=(subsidiary_name or "").strip(),
132 )
133
134
135 def make_note(
136 *,
137 statement: str,
138 section: str,
139 note_number: str,
140 note_title: str,
141 subnote_code: str = "",
142 subnote_title: str = "",
143 ) -> NoteTarget:
144 statement = (statement or "").strip()
145 if statement not in STATEMENTS:
146 raise InvalidNoteError("صورت مالی باید BS، IS، CF یا EQ باشد.")
147 section = (section or "").strip()
148 if not section:
149 raise InvalidNoteError("بخش صورت مالی نمی‌تواند خالی باشد.")
150 number = _clean_code(note_number)
151 title = _clean_text(note_title, "عنوان یادداشت")
152 sub_code = (subnote_code or "").strip()
153 sub_title = (subnote_title or "").strip()
154 if sub_code and not sub_title:
155 raise InvalidNoteError("زیریادداشت دارای کد باید عنوان هم داشته باشد.")
156 return NoteTarget(
157 statement=statement,
158 section=section,
159 note_number=number,
160 note_title=title,
161 subnote_code=sub_code,
162 subnote_title=sub_title,
163 )
164
165
166 def make_company(
167 *,
168 code: str,
169 name: str,
170 fiscal_year,
171 currency: str = "",
172 unit: str = "",
173 prepared_by: str = "",
174 status: str = "Draft",
175 ) -> PilotCompany:
176 clean_code = _clean_code(code)
177 clean_name = _clean_text(name, "نام شرکت")
178 if isinstance(fiscal_year, bool) or not isinstance(fiscal_year, int) or fiscal_year <= 0:
179 raise InvalidCompanyError("سال مالی باید یک عدد صحیح مثبت باشد.")
180 if status not in COMPANY_STATUSES:
181 raise InvalidCompanyError("وضعیت شرکت باید Draft، Approved یا Locked باشد.")
182 return PilotCompany(
183 code=clean_code,
184 name=clean_name,
185 fiscal_year=fiscal_year,
186 currency=(currency or "").strip(),
187 unit=(unit or "").strip(),
188 prepared_by=(prepared_by or "").strip(),
189 status=status,
190 )