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

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

Synced Dec 4, 08:00 UTC

codex/aram-windows-detail-review-20261031
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 793 lines 34.5 KB
Raw
1 """Native, offline Windows pilot for five nonofficial ARAM statement candidates.
2
3 No official statements, accounting approvals, database writes, or report exports.
4 Tk is a presentation layer over the existing bounded local preview pipeline.
5 """
6 from __future__ import annotations
7
8 from queue import Empty, Queue
9 import json
10 import sys
11 import tempfile
12 from threading import Thread
13 import tkinter as tk
14 from tkinter import filedialog, messagebox, ttk
15 from pathlib import Path
16 from typing import Callable
17
18 from aram_backend.desktop_five_statement_core import (
19 DesktopFiveInputError, DesktopFiveStatementController,
20 )
21 from aram_backend.desktop_five_statement_figures import build_preview_figures
22 from aram_backend.desktop_five_statement_details import PreviewDetail, build_preview_details
23 from aram_backend.coverage_preview import CoverageError
24 from aram_backend.synthetic_five_statement_demo import (
25 pipeline_manifest, source_workbook,
26 )
27
28 TITLE = "آرام | پنج صورت مالی — پیش‌نمایش آزمایشی و غیررسمی"
29 ACTIONS = {
30 "file.workbook": "select_workbook",
31 "file.manifest": "select_manifest",
32 "file.run": "run_review",
33 "file.clear": "clear_selection",
34 "file.exit": "exit_application",
35 "help.about": "show_about",
36 }
37 MAX_VISIBLE_FINDINGS = 2000
38 TAB_NAMES = ("بررسی پنج صورت مالی", "خلاصه مبالغ", "ریز اقلام", "محدودیت‌ها", "راهنما")
39 CANDIDATE_NAMES = (
40 ("balance_sheet", "ترازنامه"),
41 ("income_statement", "سود و زیان"),
42 ("equity_changes", "تغییرات حقوق مالکانه"),
43 ("cash_flow", "جریان وجوه نقد"),
44 ("trial_balance", "تراز آزمایشی"),
45 )
46
47
48 class FiveStatementWindow(tk.Tk):
49 """Only implemented native controls are enabled and clickable."""
50
51 def __init__(
52 self, *,
53 picker: Callable[[str], str] | None = None,
54 info: Callable[[str, str], None] | None = None,
55 ) -> None:
56 super().__init__()
57 self.controller = DesktopFiveStatementController()
58 self._picker = picker or self._pick_file
59 self._info = info or (
60 lambda heading, msg: messagebox.showinfo(heading, msg, parent=self)
61 )
62 self._events: Queue[tuple[int, object, str | None]] = Queue()
63 self._busy = False
64 self._detail_rows: tuple[PreviewDetail, ...] = ()
65 self._filtered_detail_rows: tuple[PreviewDetail, ...] = ()
66 self._detail_page = 0
67 self._detail_page_size = 200
68 self.title(TITLE)
69 self.geometry("1060x730")
70 self.minsize(840, 610)
71 self.configure(bg="#f3f6fa")
72 self.workbook_label = tk.StringVar(value="فایل اکسل انتخاب نشده است")
73 self.manifest_label = tk.StringVar(value="فایل سیاست‌ها/اسناد انتخاب نشده است")
74 self.overview = tk.StringVar(value="ابتدا هر دو فایل را انتخاب کنید")
75 self.status = tk.StringVar(value="آفلاین | فقط خواندن | بدون صدور یا تأیید")
76 self.amount_units = tk.StringVar(value="واحد: طبق داده‌های ورودی | هنوز محاسبه نشده")
77 self._configure_styles()
78 self._build_menu()
79 self._build_tabs()
80 self._register_shortcuts()
81 self._refresh()
82
83 def _configure_styles(self) -> None:
84 style = ttk.Style(self)
85 if "clam" in style.theme_names():
86 style.theme_use("clam")
87 style.configure("Aram.Title.TLabel", font=("Tahoma", 18, "bold"))
88 style.configure("Aram.Banner.TLabel", font=("Tahoma", 10, "bold"),
89 background="#fff4d6", foreground="#76480d", padding=12)
90 style.configure("Aram.TButton", font=("Tahoma", 10), padding=(12, 8))
91 style.configure("Aram.Treeview", font=("Tahoma", 10), rowheight=28)
92 style.configure("Aram.Treeview.Heading", font=("Tahoma", 10, "bold"))
93
94 def _pick_file(self, kind: str) -> str:
95 if kind == "workbook":
96 return filedialog.askopenfilename(
97 parent=self, title="انتخاب اکسل پایلوت",
98 filetypes=[("Excel Workbook", "*.xlsx")],
99 )
100 return filedialog.askopenfilename(
101 parent=self, title="انتخاب JSON سیاست‌ها و اسناد",
102 filetypes=[("Pipeline JSON", "*.json")],
103 )
104
105 def _build_menu(self) -> None:
106 menu = tk.Menu(self)
107 self.file_menu = tk.Menu(menu, tearoff=0)
108 self.file_menu.add_command(
109 label="انتخاب اکسل", command=self.select_workbook, accelerator="Ctrl+O",
110 )
111 self.file_menu.add_command(
112 label="انتخاب فایل تنظیمات", command=self.select_manifest, accelerator="Ctrl+M",
113 )
114 self.file_menu.add_command(
115 label="اجرای کنترل", command=self.run_review, accelerator="Ctrl+R",
116 )
117 self.file_menu.add_command(
118 label="پاک‌کردن انتخاب", command=self.clear_selection,
119 accelerator="Ctrl+L",
120 )
121 self.file_menu.add_separator()
122 self.file_menu.add_command(
123 label="خروج", command=self.exit_application, accelerator="Ctrl+Q",
124 )
125 menu.add_cascade(label="فایل", menu=self.file_menu)
126 self.help_menu = tk.Menu(menu, tearoff=0)
127 self.help_menu.add_command(
128 label="درباره", command=self.show_about, accelerator="F1",
129 )
130 menu.add_cascade(label="راهنما", menu=self.help_menu)
131 self.config(menu=menu)
132
133 def _build_tabs(self) -> None:
134 outer = ttk.Frame(self, padding=18)
135 outer.pack(fill="both", expand=True)
136 ttk.Label(
137 outer, text="آرام — بررسی آزمایشی پنج صورت مالی",
138 style="Aram.Title.TLabel", anchor="e",
139 ).pack(fill="x")
140 ttk.Label(
141 outer,
142 text=(
143 "آزمایشی و فاقد مجوز انتشار | فقط پیش‌نمایش حسابداری "
144 "بر مبنای فایل‌های ارائه‌شده | بدون ثبت، تأیید یا خروجی رسمی"
145 ),
146 style="Aram.Banner.TLabel", anchor="e",
147 ).pack(fill="x", pady=(12, 16))
148 self.tabs = ttk.Notebook(outer)
149 self.tabs.pack(fill="both", expand=True)
150 main = ttk.Frame(self.tabs, padding=12)
151 figures = ttk.Frame(self.tabs, padding=12)
152 details = ttk.Frame(self.tabs, padding=12)
153 limitations = ttk.Frame(self.tabs, padding=18)
154 help_tab = ttk.Frame(self.tabs, padding=18)
155 for tab, title in zip((main, figures, details, limitations, help_tab), TAB_NAMES):
156 self.tabs.add(tab, text=title)
157
158 ttk.Label(main, textvariable=self.workbook_label, anchor="e").pack(
159 fill="x", pady=(0, 8),
160 )
161 ttk.Label(main, textvariable=self.manifest_label, anchor="e").pack(
162 fill="x", pady=(0, 8),
163 )
164 buttons = ttk.Frame(main)
165 buttons.pack(fill="x", pady=(4, 12))
166 self.workbook_button = ttk.Button(
167 buttons, text="انتخاب اکسل", command=self.select_workbook,
168 style="Aram.TButton",
169 )
170 self.workbook_button.pack(side="right", padx=4)
171 self.manifest_button = ttk.Button(
172 buttons, text="انتخاب تنظیمات", command=self.select_manifest,
173 style="Aram.TButton",
174 )
175 self.manifest_button.pack(side="right", padx=4)
176 self.run_button = ttk.Button(
177 buttons, text="اجرای کنترل پنج صورت مالی", command=self.run_review,
178 style="Aram.TButton",
179 )
180 self.run_button.pack(side="right", padx=4)
181 self.clear_button = ttk.Button(
182 buttons, text="پاک‌کردن انتخاب", command=self.clear_selection,
183 style="Aram.TButton",
184 )
185 self.clear_button.pack(side="right", padx=4)
186
187 ttk.Label(
188 main, textvariable=self.overview, anchor="e",
189 font=("Tahoma", 11, "bold"),
190 ).pack(fill="x", pady=(0, 8))
191 area = ttk.Frame(main)
192 area.pack(fill="both", expand=True)
193 columns = ("kind", "state", "detail")
194 self.outcome_tree = ttk.Treeview(
195 area, columns=columns, show="headings", style="Aram.Treeview",
196 )
197 for key, heading, width in (
198 ("kind", "خروجی", 230),
199 ("state", "وضعیت", 135),
200 ("detail", "توضیح / کد مغایرت", 560),
201 ):
202 self.outcome_tree.heading(key, text=heading)
203 self.outcome_tree.column(
204 key, width=width, anchor="e",
205 stretch=(key == "detail"),
206 )
207 scrollbar = ttk.Scrollbar(
208 area, orient="vertical", command=self.outcome_tree.yview,
209 )
210 self.outcome_tree.configure(yscrollcommand=scrollbar.set)
211 self.outcome_tree.grid(row=0, column=0, sticky="nsew")
212 scrollbar.grid(row=0, column=1, sticky="ns")
213 area.grid_columnconfigure(0, weight=1)
214 area.grid_rowconfigure(0, weight=1)
215
216 ttk.Label(
217 figures,
218 text="مبالغ خام پنج صورت مالی — صرفاً نامزد بررسی کارشناسی",
219 font=("Tahoma", 11, "bold"), anchor="e",
220 ).pack(fill="x", pady=(0, 7))
221 ttk.Label(
222 figures, textvariable=self.amount_units, anchor="e",
223 ).pack(fill="x", pady=(0, 8))
224 figure_area = ttk.Frame(figures)
225 figure_area.pack(fill="both", expand=True)
226 self.figures_tree = ttk.Treeview(
227 figure_area, columns=("statement", "label", "amount", "state"),
228 show="headings", style="Aram.Treeview",
229 )
230 for key, title, width in (
231 ("statement", "صورت مالی", 190),
232 ("label", "شاخص", 220),
233 ("amount", "مبلغ (بدون گردکردن)", 200),
234 ("state", "اعتبار نتیجه", 230),
235 ):
236 self.figures_tree.heading(key, text=title)
237 self.figures_tree.column(key, width=width, anchor="e")
238 figures_scrollbar = ttk.Scrollbar(
239 figure_area, orient="vertical", command=self.figures_tree.yview,
240 )
241 self.figures_tree.configure(yscrollcommand=figures_scrollbar.set)
242 self.figures_tree.grid(row=0, column=0, sticky="nsew")
243 figures_scrollbar.grid(row=0, column=1, sticky="ns")
244 figure_area.grid_columnconfigure(0, weight=1)
245 figure_area.grid_rowconfigure(0, weight=1)
246
247 ttk.Label(
248 details,
249 text="ریز اقلام و ردگیری منبع — فقط خواندنی و غیررسمی",
250 font=("Tahoma", 11, "bold"), anchor="e",
251 ).pack(fill="x", pady=(0, 7))
252 controls = ttk.Frame(details)
253 controls.pack(fill="x", pady=(0, 8))
254 self.detail_filter_var = tk.StringVar(value="همه")
255 self.detail_filter_combo = ttk.Combobox(
256 controls, textvariable=self.detail_filter_var, state="readonly",
257 values=(
258 "همه", "ترازنامه", "سود و زیان",
259 "تغییرات حقوق مالکانه", "جریان وجوه نقد", "تراز آزمایشی",
260 ),
261 width=22,
262 )
263 self.detail_filter_combo.pack(side="right", padx=4)
264 self.detail_filter_combo.bind(
265 "<<ComboboxSelected>>", lambda event: self._apply_detail_filter(),
266 )
267 self.detail_search_var = tk.StringVar(value="")
268 self.detail_search_entry = ttk.Entry(
269 controls, textvariable=self.detail_search_var, width=28,
270 )
271 self.detail_search_entry.pack(side="right", padx=4)
272 self.detail_search_entry.bind(
273 "<Return>", lambda event: self._apply_detail_filter(),
274 )
275 self.detail_search_button = ttk.Button(
276 controls, text="جستجو", command=self._apply_detail_filter,
277 )
278 self.detail_search_button.pack(side="right", padx=4)
279 self.detail_status = tk.StringVar(value="پس از اجرای کنترل، ریز اقلام نمایش داده می‌شود")
280 ttk.Label(details, textvariable=self.detail_status, anchor="e").pack(
281 fill="x", pady=(0, 6),
282 )
283 detail_area = ttk.Frame(details)
284 detail_area.pack(fill="both", expand=True)
285 detail_columns = (
286 "statement", "item", "reference", "source", "opening",
287 "debit", "credit", "movement", "closing", "trace", "state",
288 )
289 self.detail_tree = ttk.Treeview(
290 detail_area, columns=detail_columns, show="headings",
291 style="Aram.Treeview",
292 )
293 detail_headers = (
294 ("statement", "صورت مالی", 150),
295 ("item", "شرح / حساب / فعالیت", 190),
296 ("reference", "یادداشت / شناسه", 190),
297 ("source", "مواجهه / ردیف منبع", 180),
298 ("opening", "افتتاحیه / منبع", 130),
299 ("debit", "بدهکار / ورودی", 130),
300 ("credit", "بستانکار / خروجی", 130),
301 ("movement", "تغییر", 130),
302 ("closing", "اختتامیه / ارائه", 150),
303 ("trace", "مدرک / سیاست / ردگیری", 330),
304 ("state", "وضعیت", 160),
305 )
306 for key, heading, width in detail_headers:
307 self.detail_tree.heading(key, text=heading)
308 self.detail_tree.column(key, width=width, minwidth=80, anchor="e")
309 detail_y = ttk.Scrollbar(
310 detail_area, orient="vertical", command=self.detail_tree.yview,
311 )
312 detail_x = ttk.Scrollbar(
313 detail_area, orient="horizontal", command=self.detail_tree.xview,
314 )
315 self.detail_tree.configure(
316 yscrollcommand=detail_y.set, xscrollcommand=detail_x.set,
317 )
318 self.detail_tree.grid(row=0, column=0, sticky="nsew")
319 detail_y.grid(row=0, column=1, sticky="ns")
320 detail_x.grid(row=1, column=0, sticky="ew")
321 detail_area.grid_columnconfigure(0, weight=1)
322 detail_area.grid_rowconfigure(0, weight=1)
323 paging = ttk.Frame(details)
324 paging.pack(fill="x", pady=(7, 0))
325 self.detail_prev_button = ttk.Button(
326 paging, text="صفحه قبل", command=lambda: self._change_detail_page(-1),
327 state="disabled",
328 )
329 self.detail_prev_button.pack(side="right", padx=4)
330 self.detail_next_button = ttk.Button(
331 paging, text="صفحه بعد", command=lambda: self._change_detail_page(1),
332 state="disabled",
333 )
334 self.detail_next_button.pack(side="right", padx=4)
335
336 for item in (
337 "• موفقیت آزمون به‌معنای کامل‌بودن سندها، مانده‌ها یا نگاشت‌های حسابداری نیست.",
338 "• طبقه‌بندی جریان نقد به ریزاسناد جفت‌شده و فهرست حساب‌های نقد نیاز دارد.",
339 "• انتخاب یادداشت‌های نقد و سیاست‌های ارائه در JSON، صرفاً ادعای فایل است.",
340 "• تأیید مدیر مالی، کنترل مستقل C1/C2/C3 و قابلیت استناد رسمی وجود ندارد.",
341 "• تهیه، امضای دیجیتال، چاپ و صدور PDF/Excel رسمی در این پایلوت غیرفعال است.",
342 "• برای اجرای واقعی، کارشناس مسئول باید محرمانگی فایل‌ها را بررسی کند.",
343 ):
344 ttk.Label(
345 limitations, text=item, anchor="e", justify="right",
346 wraplength=900, font=("Tahoma", 11),
347 ).pack(fill="x", pady=9)
348 ttk.Label(
349 help_tab, anchor="e", justify="right", wraplength=920,
350 font=("Tahoma", 11),
351 text=(
352 "۱. یک فایل XLSX منطبق با قرارداد Pilot و یک manifest.json "
353 "مطابق docs/FIVE_STATEMENT_PIPELINE_CLI.md انتخاب کنید.\n\n"
354 "۲. کنترل را اجرا کنید. نتیجه‌ها و کدهای مغایرت فقط در حافظه "
355 "نمایش داده می‌شوند و در هیچ فایلی ذخیره نمی‌شوند.\n\n"
356 "۳. پاک‌کردن انتخاب، تمام نتایج قبلی را از پنجره پاک می‌کند.\n\n"
357 "۴. اجرای موفق فقط مجوز بررسی کارشناسی است؛ "
358 "نه صورت مالی قانونی، نه تأیید، نه مجوز چاپ یا صدور."
359 ),
360 ).pack(fill="x")
361 ttk.Label(outer, textvariable=self.status, anchor="e").pack(
362 fill="x", pady=(12, 0),
363 )
364
365 def _register_shortcuts(self) -> None:
366 keys = {
367 "<Control-o>": self.select_workbook,
368 "<Control-m>": self.select_manifest,
369 "<Control-r>": self.run_review,
370 "<Control-l>": self.clear_selection,
371 "<Control-q>": self.exit_application,
372 "<F1>": self.show_about,
373 }
374 for key, action in keys.items():
375 self.bind_all(key, lambda event, callback=action: callback())
376
377 def _refresh(self) -> None:
378 if not self.winfo_exists():
379 return
380 selectable = "disabled" if self._busy else "normal"
381 executable = (
382 "normal" if self.controller.can_run and not self._busy else "disabled"
383 )
384 self.workbook_button.configure(state=selectable)
385 self.manifest_button.configure(state=selectable)
386 self.clear_button.configure(state=selectable)
387 self.run_button.configure(state=executable)
388 self.detail_filter_combo.configure(state="disabled" if self._busy else "readonly")
389 self.detail_search_entry.configure(state=selectable)
390 self.detail_search_button.configure(state=selectable)
391 for i in (0, 1, 3):
392 self.file_menu.entryconfigure(i, state=selectable)
393 self.file_menu.entryconfigure(2, state=executable)
394 self._render_detail_page()
395
396 def _apply_detail_filter(self) -> None:
397 statement = self.detail_filter_var.get()
398 query = self.detail_search_var.get().strip().casefold()
399 self._filtered_detail_rows = tuple(
400 row for row in self._detail_rows
401 if (statement == "همه" or row.statement == statement)
402 and (not query or query in " ".join(row.values()).casefold())
403 )
404 self._detail_page = 0
405 self._render_detail_page()
406
407 def _render_detail_page(self) -> None:
408 if not hasattr(self, "detail_tree") or not self.detail_tree.winfo_exists():
409 return
410 children = self.detail_tree.get_children()
411 if children:
412 self.detail_tree.delete(*children)
413 total = len(self._filtered_detail_rows)
414 pages = max(1, (total + self._detail_page_size - 1) // self._detail_page_size)
415 self._detail_page = min(max(0, self._detail_page), pages - 1)
416 start = self._detail_page * self._detail_page_size
417 end = min(start + self._detail_page_size, total)
418 for row in self._filtered_detail_rows[start:end]:
419 self.detail_tree.insert("", "end", values=row.values())
420 if total:
421 self.detail_status.set(
422 f"نمایش {start + 1} تا {end} از {total} ردیف | "
423 f"صفحه {self._detail_page + 1} از {pages} | هر صفحه حداکثر ۲۰۰ ردیف"
424 )
425 else:
426 self.detail_status.set("ردیفی با این فیلتر پیدا نشد")
427 button_state = "disabled" if self._busy else "normal"
428 self.detail_prev_button.configure(
429 state=(button_state if self._detail_page > 0 else "disabled"),
430 )
431 self.detail_next_button.configure(
432 state=(button_state if self._detail_page + 1 < pages else "disabled"),
433 )
434
435 def _change_detail_page(self, delta: int) -> None:
436 if self._busy:
437 return
438 self._detail_page += delta
439 self._render_detail_page()
440
441 def _clear_rows(self) -> None:
442 for tree in (self.outcome_tree, self.figures_tree, self.detail_tree):
443 children = tree.get_children()
444 if children:
445 tree.delete(*children)
446 self._detail_rows = ()
447 self._filtered_detail_rows = ()
448 self._detail_page = 0
449 self.detail_filter_var.set("همه")
450 self.detail_search_var.set("")
451 self.detail_status.set("پس از اجرای کنترل، ریز اقلام نمایش داده می‌شود")
452 self.amount_units.set("واحد: طبق داده‌های ورودی | هنوز محاسبه نشده")
453 self._render_detail_page()
454
455 def select_workbook(self) -> None:
456 if self._busy:
457 return
458 selected = self._picker("workbook")
459 if not selected:
460 return
461 try:
462 self.controller.select_workbook(selected)
463 except DesktopFiveInputError as exc:
464 self.workbook_label.set("فایل اکسل معتبر انتخاب نشده است")
465 self.status.set(str(exc))
466 else:
467 self.workbook_label.set(str(self.controller.workbook_path))
468 self.status.set("اکسل انتخاب شد؛ کنترل مالی هنوز انجام نشده است")
469 self._clear_rows()
470 self.overview.set("نتیجه قبلی نامعتبر شد؛ کنترل را دوباره اجرا کنید")
471 self._refresh()
472
473 def select_manifest(self) -> None:
474 if self._busy:
475 return
476 selected = self._picker("manifest")
477 if not selected:
478 return
479 try:
480 self.controller.select_manifest(selected)
481 except DesktopFiveInputError as exc:
482 self.manifest_label.set("فایل JSON معتبر انتخاب نشده است")
483 self.status.set(str(exc))
484 else:
485 self.manifest_label.set(str(self.controller.manifest_path))
486 self.status.set("تنظیمات انتخاب شد؛ صحت آن هنوز تأیید نشده است")
487 self._clear_rows()
488 self.overview.set("نتیجه قبلی نامعتبر شد؛ کنترل را دوباره اجرا کنید")
489 self._refresh()
490
491 def run_review(self) -> None:
492 if self._busy or not self.controller.can_run:
493 return
494 self._busy = True
495 self._clear_rows()
496 self.overview.set("کنترل پنج صورت مالی در حال اجراست")
497 self.status.set("در حال خواندن امن فایل‌ها؛ هیچ داده‌ای نوشته نمی‌شود")
498 generation = self.controller.generation
499 self._refresh()
500
501 def worker() -> None:
502 try:
503 outcome = self.controller.validate()
504 figures = build_preview_figures(outcome)
505 details = build_preview_details(outcome)
506 except (DesktopFiveInputError, CoverageError) as exc:
507 self._events.put((generation, None, str(exc)))
508 except Exception:
509 # Do not disclose a private filesystem or financial traceback.
510 self._events.put((generation, None, "INTERNAL_REVIEW_FAILED"))
511 else:
512 self._events.put((generation, (outcome, figures, details), None))
513
514 Thread(target=worker, daemon=True).start()
515 self.after(80, self._poll)
516
517 def _poll(self) -> None:
518 try:
519 generation, result, error = self._events.get_nowait()
520 except Empty:
521 if self._busy:
522 self.after(80, self._poll)
523 return
524 if generation != self.controller.generation:
525 self._busy = False
526 self._refresh()
527 return
528 self._busy = False
529 if error is not None:
530 self.controller.result = None
531 self.controller.state = "INPUT_ERROR"
532 self._clear_rows()
533 self.overview.set("ورودی نامعتبر یا کنترل ناموفق")
534 self.status.set("کد خطا: " + error)
535 else:
536 outcome, figure_rows, detail_rows = result
537 self._detail_rows = detail_rows
538 self._apply_detail_filter()
539 self.amount_units.set(
540 "شرکت " + outcome.company_code
541 + " | سال " + str(outcome.fiscal_year)
542 + " | واحد " + outcome.cash_flow.unit
543 + " | ارز " + outcome.cash_flow.currency
544 + " | غیررسمی"
545 )
546 for figure in figure_rows:
547 self.figures_tree.insert(
548 "", "end",
549 values=(figure.statement, figure.label,
550 figure.value, figure.state),
551 )
552 eligible = outcome.eligible_for_analyst_review
553 self.overview.set(
554 "تطبیق حسابی مناسب بررسی کارشناسی؛ نه تأیید رسمی"
555 if eligible else "تطبیق مسدود شد؛ مغایرت‌ها را بررسی کنید"
556 )
557 for key, label in CANDIDATE_NAMES:
558 candidate = getattr(outcome, key)
559 approved = (
560 candidate.balanced_for_analyst_review if key == "trial_balance"
561 else candidate.eligible_for_analyst_review
562 )
563 self.outcome_tree.insert(
564 "", "end", values=(
565 label, "قابل بررسی" if approved else "مسدود",
566 "صرفاً کنترل‌های تحلیلی؛ نه صدور صورت مالی",
567 ),
568 )
569 for code in outcome.findings[:MAX_VISIBLE_FINDINGS]:
570 self.outcome_tree.insert("", "end", values=("مغایرت", "مسدود", code))
571 overflow = len(outcome.findings) - MAX_VISIBLE_FINDINGS
572 self.status.set(
573 ("منبع SHA256: " + outcome.source_sha256[:16] + "… | "
574 + ("نتایج کامل نمایش داده شد" if overflow <= 0
575 else f"{overflow} مغایرت دیگر نمایش داده نشده"))
576 )
577 self._refresh()
578
579 def clear_selection(self) -> None:
580 if self._busy:
581 return
582 self.controller.clear()
583 self.workbook_label.set("فایل اکسل انتخاب نشده است")
584 self.manifest_label.set("فایل سیاست‌ها/اسناد انتخاب نشده است")
585 self.overview.set("ابتدا هر دو فایل را انتخاب کنید")
586 self.status.set("انتخاب و نمایش پاک شد؛ فایل‌های ورودی تغییر نکردند")
587 self._clear_rows()
588 self._refresh()
589
590 def exit_application(self) -> None:
591 self.destroy()
592
593 def show_about(self) -> None:
594 self._info(
595 "درباره آرام",
596 "ARAM Five-Statement Pilot — UNSIGNED / UNRELEASED\n"
597 "Read-only local analyst preview. No accounting posting or approval.\n"
598 "Not an official financial statement, signed release, or audited source.",
599 )
600
601
602 def self_test() -> int:
603 ctrl = DesktopFiveStatementController()
604 if ctrl.state != "EMPTY" or ctrl.can_run or ctrl.result is not None:
605 return 3
606 if len(ACTIONS) != 6 or len(CANDIDATE_NAMES) != 5:
607 return 4
608 return 0
609
610
611 def ui_smoke_test() -> int:
612 """Windows-only actual Tk widget smoke against synthetic invalid inputs."""
613 with tempfile.TemporaryDirectory() as directory:
614 folder = Path(directory)
615 xlsx = folder / "synthetic.xlsx"
616 manifest = folder / "synthetic.json"
617 xlsx.write_bytes(b"not a valid workbook")
618 manifest.write_bytes(b"not valid json")
619 files = {"workbook": str(xlsx), "manifest": str(manifest)}
620 dialogs = []
621 window = FiveStatementWindow(
622 picker=lambda kind: files[kind],
623 info=lambda title, msg: dialogs.append(title),
624 )
625 try:
626 window.withdraw()
627 window.update_idletasks()
628 if str(window.run_button.cget("state")) != "disabled":
629 return 10
630 if window.tabs.index("end") != len(TAB_NAMES):
631 return 11
632 for key in ("<Control-o>", "<Control-m>", "<Control-r>",
633 "<Control-l>", "<Control-q>", "<F1>"):
634 if not window.bind_all(key):
635 return 12
636 window.workbook_button.invoke()
637 window.manifest_button.invoke()
638 if not window.controller.can_run:
639 return 13
640 if str(window.run_button.cget("state")) != "normal":
641 return 14
642 window.run_button.invoke()
643 import time
644 for _ in range(400):
645 window.update()
646 if not window._busy:
647 break
648 time.sleep(0.02)
649 if window._busy or window.controller.state != "INPUT_ERROR":
650 return 15
651 window.help_menu.invoke(0)
652 if dialogs != ["درباره آرام"]:
653 return 16
654 window.clear_button.invoke()
655 if window.controller.can_run or window.outcome_tree.get_children():
656 return 17
657 window.file_menu.invoke(5)
658 return 0
659 finally:
660 try:
661 if window.winfo_exists():
662 window.destroy()
663 except tk.TclError:
664 pass
665
666
667 def ui_valid_smoke_test() -> int:
668 """Exercise frozen Tk with a truly valid synthetic five-statement input.
669
670 This is an automated widget check, not human review or official approval.
671 """
672 import time
673 with tempfile.TemporaryDirectory() as directory:
674 folder = Path(directory)
675 workbook = folder / "ARAM-SYNTHETIC-ONLY.xlsx"
676 manifest = folder / "ARAM-SYNTHETIC-ONLY.json"
677 workbook.write_bytes(source_workbook())
678 manifest.write_text(
679 json.dumps(pipeline_manifest(), ensure_ascii=True), encoding="utf-8",
680 )
681 selected = {"workbook": str(workbook), "manifest": str(manifest)}
682 window = FiveStatementWindow(picker=lambda kind: selected[kind])
683 try:
684 window.withdraw()
685 window.update_idletasks()
686 if str(window.run_button.cget("state")) != "disabled":
687 return 20
688 window.workbook_button.invoke()
689 window.manifest_button.invoke()
690 if not window.controller.can_run:
691 return 21
692 window.run_button.invoke()
693 for _ in range(500):
694 window.update()
695 if not window._busy:
696 break
697 time.sleep(0.02)
698 if window._busy or window.controller.state != "ELIGIBLE":
699 return 22
700 if not window.controller.result or not window.controller.result.eligible_for_analyst_review:
701 return 23
702 rows = window.outcome_tree.get_children()
703 if len(rows) != 5:
704 return 24
705 amount_rows = [
706 window.figures_tree.item(row, "values")
707 for row in window.figures_tree.get_children()
708 ]
709 if len(amount_rows) != 28:
710 return 28
711 if not any(
712 row[0] == "سود و زیان" and row[1] == "سود خالص"
713 and row[2] == "20" for row in amount_rows
714 ):
715 return 29
716 detail_rows = window.detail_tree.get_children()
717 if not window._detail_rows or not detail_rows:
718 return 30
719 if not any(
720 row.item == "Revenue" and row.statement == "سود و زیان"
721 for row in window._detail_rows
722 ):
723 return 31
724 window.detail_filter_var.set("سود و زیان")
725 window.detail_search_var.set("یادداشت R01")
726 window._apply_detail_filter()
727 filtered = window.detail_tree.get_children()
728 if len(filtered) != 1:
729 return 32
730 values = window.detail_tree.item(filtered[0], "values")
731 if values[1] != "Revenue" or values[0] != "سود و زیان":
732 return 33
733 window.detail_filter_var.set("همه")
734 window.detail_search_var.set("")
735 original_details = window._detail_rows
736 if not original_details:
737 return 34
738 repeats = 200 // len(original_details) + 1
739 window._detail_rows = original_details * repeats
740 window._apply_detail_filter()
741 if len(window.detail_tree.get_children()) != 200:
742 return 35
743 if str(window.detail_next_button.cget("state")) != "normal":
744 return 36
745 window._change_detail_page(1)
746 if len(window.detail_tree.get_children()) != len(window._detail_rows) - 200:
747 return 37
748 if str(window.detail_prev_button.cget("state")) != "normal":
749 return 38
750 window._change_detail_page(-1)
751 if len(window.detail_tree.get_children()) != 200:
752 return 39
753 window._detail_rows = original_details
754 window._apply_detail_filter()
755 if any(
756 window.outcome_tree.item(row, "values")[1] != "قابل بررسی"
757 for row in rows
758 ):
759 return 25
760 window.clear_button.invoke()
761 if (window.controller.result is not None or window.outcome_tree.get_children()
762 or window.figures_tree.get_children() or window.detail_tree.get_children()
763 or window._detail_rows):
764 return 26
765 if str(window.run_button.cget("state")) != "disabled":
766 return 27
767 return 0
768 finally:
769 try:
770 if window.winfo_exists():
771 window.destroy()
772 except tk.TclError:
773 pass
774
775
776 def main(argv: list[str] | None = None) -> int:
777 args = list(sys.argv[1:] if argv is None else argv)
778 if args == ["--self-test"]:
779 return self_test()
780 if args == ["--ui-smoke"]:
781 return ui_smoke_test()
782 if args == ["--ui-valid-smoke"]:
783 return ui_valid_smoke_test()
784 if args:
785 print("Supported: --self-test, --ui-smoke, --ui-valid-smoke, or no arguments", file=sys.stderr)
786 return 2
787 window = FiveStatementWindow()
788 window.mainloop()
789 return 0
790
791
792 if __name__ == "__main__":
793 raise SystemExit(main())