codex/aram-windows-five-statement-pilot-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 473 lines 20 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 sys
10 import tempfile
11 from threading import Thread
12 import tkinter as tk
13 from tkinter import filedialog, messagebox, ttk
14 from pathlib import Path
15 from typing import Callable
16
17 from aram_backend.desktop_five_statement_core import (
18 DesktopFiveInputError, DesktopFiveStatementController,
19 )
20
21 TITLE = "آرام | پنج صورت مالی — پیش‌نمایش آزمایشی و غیررسمی"
22 ACTIONS = {
23 "file.workbook": "select_workbook",
24 "file.manifest": "select_manifest",
25 "file.run": "run_review",
26 "file.clear": "clear_selection",
27 "file.exit": "exit_application",
28 "help.about": "show_about",
29 }
30 MAX_VISIBLE_FINDINGS = 2000
31 TAB_NAMES = ("بررسی پنج صورت مالی", "محدودیت‌ها", "راهنما")
32 CANDIDATE_NAMES = (
33 ("balance_sheet", "ترازنامه"),
34 ("income_statement", "سود و زیان"),
35 ("equity_changes", "تغییرات حقوق مالکانه"),
36 ("cash_flow", "جریان وجوه نقد"),
37 ("trial_balance", "تراز آزمایشی"),
38 )
39
40
41 class FiveStatementWindow(tk.Tk):
42 """Only implemented native controls are enabled and clickable."""
43
44 def __init__(
45 self, *,
46 picker: Callable[[str], str] | None = None,
47 info: Callable[[str, str], None] | None = None,
48 ) -> None:
49 super().__init__()
50 self.controller = DesktopFiveStatementController()
51 self._picker = picker or self._pick_file
52 self._info = info or (
53 lambda heading, msg: messagebox.showinfo(heading, msg, parent=self)
54 )
55 self._events: Queue[tuple[int, object, str | None]] = Queue()
56 self._busy = False
57 self.title(TITLE)
58 self.geometry("1060x730")
59 self.minsize(840, 610)
60 self.configure(bg="#f3f6fa")
61 self.workbook_label = tk.StringVar(value="فایل اکسل انتخاب نشده است")
62 self.manifest_label = tk.StringVar(value="فایل سیاست‌ها/اسناد انتخاب نشده است")
63 self.overview = tk.StringVar(value="ابتدا هر دو فایل را انتخاب کنید")
64 self.status = tk.StringVar(value="آفلاین | فقط خواندن | بدون صدور یا تأیید")
65 self._configure_styles()
66 self._build_menu()
67 self._build_tabs()
68 self._register_shortcuts()
69 self._refresh()
70
71 def _configure_styles(self) -> None:
72 style = ttk.Style(self)
73 if "clam" in style.theme_names():
74 style.theme_use("clam")
75 style.configure("Aram.Title.TLabel", font=("Tahoma", 18, "bold"))
76 style.configure("Aram.Banner.TLabel", font=("Tahoma", 10, "bold"),
77 background="#fff4d6", foreground="#76480d", padding=12)
78 style.configure("Aram.TButton", font=("Tahoma", 10), padding=(12, 8))
79 style.configure("Aram.Treeview", font=("Tahoma", 10), rowheight=28)
80 style.configure("Aram.Treeview.Heading", font=("Tahoma", 10, "bold"))
81
82 def _pick_file(self, kind: str) -> str:
83 if kind == "workbook":
84 return filedialog.askopenfilename(
85 parent=self, title="انتخاب اکسل پایلوت",
86 filetypes=[("Excel Workbook", "*.xlsx")],
87 )
88 return filedialog.askopenfilename(
89 parent=self, title="انتخاب JSON سیاست‌ها و اسناد",
90 filetypes=[("Pipeline JSON", "*.json")],
91 )
92
93 def _build_menu(self) -> None:
94 menu = tk.Menu(self)
95 self.file_menu = tk.Menu(menu, tearoff=0)
96 self.file_menu.add_command(
97 label="انتخاب اکسل", command=self.select_workbook, accelerator="Ctrl+O",
98 )
99 self.file_menu.add_command(
100 label="انتخاب فایل تنظیمات", command=self.select_manifest, accelerator="Ctrl+M",
101 )
102 self.file_menu.add_command(
103 label="اجرای کنترل", command=self.run_review, accelerator="Ctrl+R",
104 )
105 self.file_menu.add_command(
106 label="پاک‌کردن انتخاب", command=self.clear_selection,
107 accelerator="Ctrl+L",
108 )
109 self.file_menu.add_separator()
110 self.file_menu.add_command(
111 label="خروج", command=self.exit_application, accelerator="Ctrl+Q",
112 )
113 menu.add_cascade(label="فایل", menu=self.file_menu)
114 self.help_menu = tk.Menu(menu, tearoff=0)
115 self.help_menu.add_command(
116 label="درباره", command=self.show_about, accelerator="F1",
117 )
118 menu.add_cascade(label="راهنما", menu=self.help_menu)
119 self.config(menu=menu)
120
121 def _build_tabs(self) -> None:
122 outer = ttk.Frame(self, padding=18)
123 outer.pack(fill="both", expand=True)
124 ttk.Label(
125 outer, text="آرام — بررسی آزمایشی پنج صورت مالی",
126 style="Aram.Title.TLabel", anchor="e",
127 ).pack(fill="x")
128 ttk.Label(
129 outer,
130 text=(
131 "آزمایشی و فاقد مجوز انتشار | فقط پیش‌نمایش حسابداری "
132 "بر مبنای فایل‌های ارائه‌شده | بدون ثبت، تأیید یا خروجی رسمی"
133 ),
134 style="Aram.Banner.TLabel", anchor="e",
135 ).pack(fill="x", pady=(12, 16))
136 self.tabs = ttk.Notebook(outer)
137 self.tabs.pack(fill="both", expand=True)
138 main = ttk.Frame(self.tabs, padding=12)
139 limitations = ttk.Frame(self.tabs, padding=18)
140 help_tab = ttk.Frame(self.tabs, padding=18)
141 for tab, title in zip((main, limitations, help_tab), TAB_NAMES):
142 self.tabs.add(tab, text=title)
143
144 ttk.Label(main, textvariable=self.workbook_label, anchor="e").pack(
145 fill="x", pady=(0, 8),
146 )
147 ttk.Label(main, textvariable=self.manifest_label, anchor="e").pack(
148 fill="x", pady=(0, 8),
149 )
150 buttons = ttk.Frame(main)
151 buttons.pack(fill="x", pady=(4, 12))
152 self.workbook_button = ttk.Button(
153 buttons, text="انتخاب اکسل", command=self.select_workbook,
154 style="Aram.TButton",
155 )
156 self.workbook_button.pack(side="right", padx=4)
157 self.manifest_button = ttk.Button(
158 buttons, text="انتخاب تنظیمات", command=self.select_manifest,
159 style="Aram.TButton",
160 )
161 self.manifest_button.pack(side="right", padx=4)
162 self.run_button = ttk.Button(
163 buttons, text="اجرای کنترل پنج صورت مالی", command=self.run_review,
164 style="Aram.TButton",
165 )
166 self.run_button.pack(side="right", padx=4)
167 self.clear_button = ttk.Button(
168 buttons, text="پاک‌کردن انتخاب", command=self.clear_selection,
169 style="Aram.TButton",
170 )
171 self.clear_button.pack(side="right", padx=4)
172
173 ttk.Label(
174 main, textvariable=self.overview, anchor="e",
175 font=("Tahoma", 11, "bold"),
176 ).pack(fill="x", pady=(0, 8))
177 area = ttk.Frame(main)
178 area.pack(fill="both", expand=True)
179 columns = ("kind", "state", "detail")
180 self.outcome_tree = ttk.Treeview(
181 area, columns=columns, show="headings", style="Aram.Treeview",
182 )
183 for key, heading, width in (
184 ("kind", "خروجی", 230),
185 ("state", "وضعیت", 135),
186 ("detail", "توضیح / کد مغایرت", 560),
187 ):
188 self.outcome_tree.heading(key, text=heading)
189 self.outcome_tree.column(
190 key, width=width, anchor="e",
191 stretch=(key == "detail"),
192 )
193 scrollbar = ttk.Scrollbar(
194 area, orient="vertical", command=self.outcome_tree.yview,
195 )
196 self.outcome_tree.configure(yscrollcommand=scrollbar.set)
197 self.outcome_tree.grid(row=0, column=0, sticky="nsew")
198 scrollbar.grid(row=0, column=1, sticky="ns")
199 area.grid_columnconfigure(0, weight=1)
200 area.grid_rowconfigure(0, weight=1)
201
202 for item in (
203 "• موفقیت آزمون به‌معنای کامل‌بودن سندها، مانده‌ها یا نگاشت‌های حسابداری نیست.",
204 "• طبقه‌بندی جریان نقد به ریزاسناد جفت‌شده و فهرست حساب‌های نقد نیاز دارد.",
205 "• انتخاب یادداشت‌های نقد و سیاست‌های ارائه در JSON، صرفاً ادعای فایل است.",
206 "• تأیید مدیر مالی، کنترل مستقل C1/C2/C3 و قابلیت استناد رسمی وجود ندارد.",
207 "• تهیه، امضای دیجیتال، چاپ و صدور PDF/Excel رسمی در این پایلوت غیرفعال است.",
208 "• برای اجرای واقعی، کارشناس مسئول باید محرمانگی فایل‌ها را بررسی کند.",
209 ):
210 ttk.Label(
211 limitations, text=item, anchor="e", justify="right",
212 wraplength=900, font=("Tahoma", 11),
213 ).pack(fill="x", pady=9)
214 ttk.Label(
215 help_tab, anchor="e", justify="right", wraplength=920,
216 font=("Tahoma", 11),
217 text=(
218 "۱. یک فایل XLSX منطبق با قرارداد Pilot و یک manifest.json "
219 "مطابق docs/FIVE_STATEMENT_PIPELINE_CLI.md انتخاب کنید.\n\n"
220 "۲. کنترل را اجرا کنید. نتیجه‌ها و کدهای مغایرت فقط در حافظه "
221 "نمایش داده می‌شوند و در هیچ فایلی ذخیره نمی‌شوند.\n\n"
222 "۳. پاک‌کردن انتخاب، تمام نتایج قبلی را از پنجره پاک می‌کند.\n\n"
223 "۴. اجرای موفق فقط مجوز بررسی کارشناسی است؛ "
224 "نه صورت مالی قانونی، نه تأیید، نه مجوز چاپ یا صدور."
225 ),
226 ).pack(fill="x")
227 ttk.Label(outer, textvariable=self.status, anchor="e").pack(
228 fill="x", pady=(12, 0),
229 )
230
231 def _register_shortcuts(self) -> None:
232 keys = {
233 "<Control-o>": self.select_workbook,
234 "<Control-m>": self.select_manifest,
235 "<Control-r>": self.run_review,
236 "<Control-l>": self.clear_selection,
237 "<Control-q>": self.exit_application,
238 "<F1>": self.show_about,
239 }
240 for key, action in keys.items():
241 self.bind_all(key, lambda event, callback=action: callback())
242
243 def _refresh(self) -> None:
244 if not self.winfo_exists():
245 return
246 selectable = "disabled" if self._busy else "normal"
247 executable = (
248 "normal" if self.controller.can_run and not self._busy else "disabled"
249 )
250 self.workbook_button.configure(state=selectable)
251 self.manifest_button.configure(state=selectable)
252 self.clear_button.configure(state=selectable)
253 self.run_button.configure(state=executable)
254 for i in (0, 1, 3):
255 self.file_menu.entryconfigure(i, state=selectable)
256 self.file_menu.entryconfigure(2, state=executable)
257
258 def _clear_rows(self) -> None:
259 children = self.outcome_tree.get_children()
260 if children:
261 self.outcome_tree.delete(*children)
262
263 def select_workbook(self) -> None:
264 if self._busy:
265 return
266 selected = self._picker("workbook")
267 if not selected:
268 return
269 try:
270 self.controller.select_workbook(selected)
271 except DesktopFiveInputError as exc:
272 self.workbook_label.set("فایل اکسل معتبر انتخاب نشده است")
273 self.status.set(str(exc))
274 else:
275 self.workbook_label.set(str(self.controller.workbook_path))
276 self.status.set("اکسل انتخاب شد؛ کنترل مالی هنوز انجام نشده است")
277 self._clear_rows()
278 self.overview.set("نتیجه قبلی نامعتبر شد؛ کنترل را دوباره اجرا کنید")
279 self._refresh()
280
281 def select_manifest(self) -> None:
282 if self._busy:
283 return
284 selected = self._picker("manifest")
285 if not selected:
286 return
287 try:
288 self.controller.select_manifest(selected)
289 except DesktopFiveInputError as exc:
290 self.manifest_label.set("فایل JSON معتبر انتخاب نشده است")
291 self.status.set(str(exc))
292 else:
293 self.manifest_label.set(str(self.controller.manifest_path))
294 self.status.set("تنظیمات انتخاب شد؛ صحت آن هنوز تأیید نشده است")
295 self._clear_rows()
296 self.overview.set("نتیجه قبلی نامعتبر شد؛ کنترل را دوباره اجرا کنید")
297 self._refresh()
298
299 def run_review(self) -> None:
300 if self._busy or not self.controller.can_run:
301 return
302 self._busy = True
303 self._clear_rows()
304 self.overview.set("کنترل پنج صورت مالی در حال اجراست")
305 self.status.set("در حال خواندن امن فایل‌ها؛ هیچ داده‌ای نوشته نمی‌شود")
306 generation = self.controller.generation
307 self._refresh()
308
309 def worker() -> None:
310 try:
311 result = self.controller.validate()
312 except DesktopFiveInputError as exc:
313 self._events.put((generation, None, str(exc)))
314 except Exception:
315 # Do not disclose a private filesystem or financial traceback.
316 self._events.put((generation, None, "INTERNAL_REVIEW_FAILED"))
317 else:
318 self._events.put((generation, result, None))
319
320 Thread(target=worker, daemon=True).start()
321 self.after(80, self._poll)
322
323 def _poll(self) -> None:
324 try:
325 generation, result, error = self._events.get_nowait()
326 except Empty:
327 if self._busy:
328 self.after(80, self._poll)
329 return
330 if generation != self.controller.generation:
331 self._busy = False
332 self._refresh()
333 return
334 self._busy = False
335 if error is not None:
336 self.controller.result = None
337 self.controller.state = "INPUT_ERROR"
338 self._clear_rows()
339 self.overview.set("ورودی نامعتبر یا کنترل ناموفق")
340 self.status.set("کد خطا: " + error)
341 else:
342 outcome = result
343 eligible = outcome.eligible_for_analyst_review
344 self.overview.set(
345 "تطبیق حسابی مناسب بررسی کارشناسی؛ نه تأیید رسمی"
346 if eligible else "تطبیق مسدود شد؛ مغایرت‌ها را بررسی کنید"
347 )
348 for key, label in CANDIDATE_NAMES:
349 candidate = getattr(outcome, key)
350 approved = (
351 candidate.balanced_for_analyst_review if key == "trial_balance"
352 else candidate.eligible_for_analyst_review
353 )
354 self.outcome_tree.insert(
355 "", "end", values=(
356 label, "قابل بررسی" if approved else "مسدود",
357 "صرفاً کنترل‌های تحلیلی؛ نه صدور صورت مالی",
358 ),
359 )
360 for code in outcome.findings[:MAX_VISIBLE_FINDINGS]:
361 self.outcome_tree.insert("", "end", values=("مغایرت", "مسدود", code))
362 overflow = len(outcome.findings) - MAX_VISIBLE_FINDINGS
363 self.status.set(
364 ("منبع SHA256: " + outcome.source_sha256[:16] + "… | "
365 + ("نتایج کامل نمایش داده شد" if overflow <= 0
366 else f"{overflow} مغایرت دیگر نمایش داده نشده"))
367 )
368 self._refresh()
369
370 def clear_selection(self) -> None:
371 if self._busy:
372 return
373 self.controller.clear()
374 self.workbook_label.set("فایل اکسل انتخاب نشده است")
375 self.manifest_label.set("فایل سیاست‌ها/اسناد انتخاب نشده است")
376 self.overview.set("ابتدا هر دو فایل را انتخاب کنید")
377 self.status.set("انتخاب و نمایش پاک شد؛ فایل‌های ورودی تغییر نکردند")
378 self._clear_rows()
379 self._refresh()
380
381 def exit_application(self) -> None:
382 self.destroy()
383
384 def show_about(self) -> None:
385 self._info(
386 "درباره آرام",
387 "ARAM Five-Statement Pilot — UNSIGNED / UNRELEASED\n"
388 "Read-only local analyst preview. No accounting posting or approval.\n"
389 "Not an official financial statement, signed release, or audited source.",
390 )
391
392
393 def self_test() -> int:
394 ctrl = DesktopFiveStatementController()
395 if ctrl.state != "EMPTY" or ctrl.can_run or ctrl.result is not None:
396 return 3
397 if len(ACTIONS) != 6 or len(CANDIDATE_NAMES) != 5:
398 return 4
399 return 0
400
401
402 def ui_smoke_test() -> int:
403 """Windows-only actual Tk widget smoke against synthetic invalid inputs."""
404 with tempfile.TemporaryDirectory() as directory:
405 folder = Path(directory)
406 xlsx = folder / "synthetic.xlsx"
407 manifest = folder / "synthetic.json"
408 xlsx.write_bytes(b"not a valid workbook")
409 manifest.write_bytes(b"not valid json")
410 files = {"workbook": str(xlsx), "manifest": str(manifest)}
411 dialogs = []
412 window = FiveStatementWindow(
413 picker=lambda kind: files[kind],
414 info=lambda title, msg: dialogs.append(title),
415 )
416 try:
417 window.withdraw()
418 window.update_idletasks()
419 if str(window.run_button.cget("state")) != "disabled":
420 return 10
421 if window.tabs.index("end") != len(TAB_NAMES):
422 return 11
423 for key in ("<Control-o>", "<Control-m>", "<Control-r>",
424 "<Control-l>", "<Control-q>", "<F1>"):
425 if not window.bind_all(key):
426 return 12
427 window.workbook_button.invoke()
428 window.manifest_button.invoke()
429 if not window.controller.can_run:
430 return 13
431 if str(window.run_button.cget("state")) != "normal":
432 return 14
433 window.run_button.invoke()
434 import time
435 for _ in range(400):
436 window.update()
437 if not window._busy:
438 break
439 time.sleep(0.02)
440 if window._busy or window.controller.state != "INPUT_ERROR":
441 return 15
442 window.help_menu.invoke(0)
443 if dialogs != ["درباره آرام"]:
444 return 16
445 window.clear_button.invoke()
446 if window.controller.can_run or window.outcome_tree.get_children():
447 return 17
448 window.file_menu.invoke(5)
449 return 0
450 finally:
451 try:
452 if window.winfo_exists():
453 window.destroy()
454 except tk.TclError:
455 pass
456
457
458 def main(argv: list[str] | None = None) -> int:
459 args = list(sys.argv[1:] if argv is None else argv)
460 if args == ["--self-test"]:
461 return self_test()
462 if args == ["--ui-smoke"]:
463 return ui_smoke_test()
464 if args:
465 print("Supported: --self-test, --ui-smoke, or no arguments", file=sys.stderr)
466 return 2
467 window = FiveStatementWindow()
468 window.mainloop()
469 return 0
470
471
472 if __name__ == "__main__":
473 raise SystemExit(main())