1
-"""Deterministic, in-memory Pilot statement engine (V1 workbench slice).
2
-
3
-Scope and safety boundary
4
--------------------------
5
-- Input is a Pilot workbook v0.1 that has passed ``preflight_pilot_workbook``.
6
-- Everything is computed in memory. No source bytes, parsed rows, or reports
7
- are persisted, and no financial value is ever guessed or plugged.
8
-- Closing balances are debit-positive (``opening + debit - credit = closing``
9
- is enforced by preflight). Display signs come from the explicit
10
- ``SECTION_POLICY`` below; unknown sections fail closed as exceptions.
11
-- Only BS and IS are rendered in this slice. Mappings targeting CF/EQ are
12
- accepted by the contract but reported as deferred, never silently rendered.
13
-- Output is always a working draft for review, never an official statement.
14
-"""
15
-
16
-from __future__ import annotations
17
-
18
-import hashlib
19
-from dataclasses import dataclass
20
-from datetime import UTC, datetime
21
-from decimal import Decimal
22
-from io import BytesIO
23
-from typing import Any
24
-
25
-from openpyxl import Workbook, load_workbook
26
-from openpyxl.styles import Alignment, Font, PatternFill
27
-
28
-from aram_backend.pilot_workbook import (
29
- SHEET_HEADERS,
30
- PilotIssue,
31
- preflight_pilot_workbook,
32
-)
33
-
34
-ENGINE_VERSION = "1.1.0"
35
-
36
-# Explicit sign policy: display = sign * closing (closing is debit-positive).
37
-SECTION_POLICY: dict[str, dict[str, int]] = {
38
- "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1},
39
- "IS": {"Revenue": -1, "Expenses": 1},
40
-}
41
-RENDERED_STATEMENTS = ("BS", "IS")
42
-DEFERRED_STATEMENTS = ("CF", "EQ")
43
-STATEMENT_LABELS_FA = {
44
- "BS": "ترازنامه",
45
- "IS": "صورت سود و زیان",
46
- "CF": "صورت جریانهای نقدی",
47
- "EQ": "صورت تغییرات در حقوق مالکانه",
48
-}
49
-SECTION_LABELS_FA = {
50
- "Assets": "داراییها",
51
- "Liabilities": "بدهیها",
52
- "Equity": "حقوق مالکانه",
53
- "Revenue": "درآمدها",
54
- "Expenses": "هزینهها",
55
-}
56
-
57
-_ZERO = Decimal("0")
58
-
59
-
60
-class PilotModelError(ValueError):
61
- """Raised when a workbook cannot be represented as a Pilot model."""
62
-
63
- def __init__(self, issues: list[PilotIssue]) -> None:
64
- self.issues = tuple(issues)
65
- super().__init__("; ".join(f"{i.code}@{i.sheet}:{i.row}" for i in issues))
66
-
67
-
68
-@dataclass(frozen=True)
69
-class PilotCompany:
70
- code: str
71
- name: str
72
- fiscal_year: int
73
- currency: str
74
- unit: str
75
- prepared_by: str
76
- status: str
77
-
78
-
79
-@dataclass(frozen=True)
80
-class PilotAccount:
81
- full_code: str
82
- name: str
83
- general_code: str
84
- general_name: str
85
- opening: Decimal
86
- debit: Decimal
87
- credit: Decimal
88
- closing: Decimal
89
- source_row: int
90
- row_status: str
91
- subsidiary_code: str = ""
92
- subsidiary_name: str = ""
93
- detail1_code: str = ""
94
- detail1_name: str = ""
95
- detail2_code: str = ""
96
- detail2_name: str = ""
97
- detail3_code: str = ""
98
- detail3_name: str = ""
99
- detail4_code: str = ""
100
- detail4_name: str = ""
101
-
102
-
103
-@dataclass(frozen=True)
104
-class NoteTarget:
105
- statement: str
106
- section: str
107
- note_number: str
108
- note_title: str
109
- subnote_code: str
110
- subnote_title: str
111
-
112
- @property
113
- def key(self) -> tuple[str, str, str, str]:
114
- return (self.statement, self.section, self.note_number, self.subnote_code)
115
-
116
-
117
-@dataclass(frozen=True)
118
-class MappingEntry:
119
- account_code: str
120
- statement: str
121
- section: str
122
- note_number: str
123
- subnote_code: str
124
- approval_status: str
125
- reviewer: str
126
- source: str
127
- mapping_id: str
128
-
129
- @property
130
- def target_key(self) -> tuple[str, str, str, str]:
131
- return (self.statement, self.section, self.note_number, self.subnote_code)
132
-
133
-
134
-@dataclass(frozen=True)
135
-class PilotModel:
136
- company: PilotCompany
137
- accounts: dict[str, PilotAccount]
138
- notes: dict[tuple[str, str, str, str], NoteTarget]
139
- mappings: dict[str, MappingEntry]
140
- conflicts: dict[str, tuple[MappingEntry, ...]]
141
- source_sha256: str
142
-
143
-
144
-@dataclass
145
-class WorkingModel:
146
- """Mutable, in-session edit state. Same shape as PilotModel so every
147
- report/table/export function accepts it unchanged. Individual records
148
- remain frozen dataclasses; edits replace records, never mutate them."""
149
-
150
- company: PilotCompany
151
- accounts: dict[str, PilotAccount]
152
- notes: dict[tuple[str, str, str, str], NoteTarget]
153
- mappings: dict[str, MappingEntry]
154
- conflicts: dict[str, tuple[MappingEntry, ...]]
155
- source_sha256: str
156
-
157
- @classmethod
158
- def from_model(cls, model: PilotModel) -> "WorkingModel":
159
- return cls(
160
- company=model.company,
161
- accounts=dict(model.accounts),
162
- notes=dict(model.notes),
163
- mappings=dict(model.mappings),
164
- conflicts=dict(model.conflicts),
165
- source_sha256=model.source_sha256,
166
- )
167
-
168
- def copy(self) -> "WorkingModel":
169
- return WorkingModel(
170
- company=self.company,
171
- accounts=dict(self.accounts),
172
- notes=dict(self.notes),
173
- mappings=dict(self.mappings),
174
- conflicts=dict(self.conflicts),
175
- source_sha256=self.source_sha256,
176
- )
177
-
178
-
179
-_HIERARCHY_CODE_FIELDS = (
180
- "general_code", "subsidiary_code", "detail1_code",
181
- "detail2_code", "detail3_code", "detail4_code",
182
-)
183
-_LEVEL_NAMES = ("General", "Subsidiary", "Detail1", "Detail2", "Detail3", "Detail4")
184
-
185
-
186
-def hierarchy_codes(account: PilotAccount) -> tuple[str, ...]:
187
- return tuple(getattr(account, field) for field in _HIERARCHY_CODE_FIELDS)
188
-
189
-
190
-def account_level_of(account: PilotAccount) -> str:
191
- """Deepest populated hierarchy level; General is always present."""
192
- codes = hierarchy_codes(account)
193
- depth = 1
194
- for index in range(1, len(codes)):
195
- if codes[index]:
196
- depth = index + 1
197
- return _LEVEL_NAMES[depth - 1]
198
-
199
-
200
-def _rows(sheet: Any, headers: tuple[str, ...]) -> list[dict[str, Any]]:
201
- result = []
202
- for values in sheet.iter_rows(min_row=2, values_only=True):
203
- row = dict(zip(headers, values))
204
- if any(v is not None and not (isinstance(v, str) and not v.strip()) for v in row.values()):
205
- result.append(row)
206
- return result
207
-
208
-
209
-def _text(value: Any) -> str:
210
- return value.strip() if isinstance(value, str) else ""
211
-
212
-
213
-def _decimal(value: Any) -> Decimal:
214
- return Decimal(str(value).strip())
215
-
216
-
217
-def parse_pilot_model(workbook_bytes: bytes) -> PilotModel:
218
- """Parse a preflight-valid workbook into a typed, immutable model."""
219
- preflight = preflight_pilot_workbook(workbook_bytes)
220
- if not preflight.valid:
221
- raise PilotModelError(list(preflight.issues))
222
-
223
- workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=True)
224
- parsed = {
225
- name: _rows(workbook[name], headers) for name, headers in SHEET_HEADERS.items()
226
- }
227
- workbook.close()
228
-
229
- company_rows = parsed["Company"]
230
- if len(company_rows) != 1:
231
- raise PilotModelError([PilotIssue(
232
- "ERROR", "WORKBENCH_SINGLE_COMPANY_REQUIRED", "Company", 0, "__sheet__",
233
- "The workbench renders exactly one company/fiscal year per workbook; "
234
- f"found {len(company_rows)} company rows.",
235
- )])
236
- crow = company_rows[0]
237
- company = PilotCompany(
238
- code=_text(crow["company_code"]),
239
- name=_text(crow["company_name"]),
240
- fiscal_year=int(crow["fiscal_year"]),
241
- currency=_text(crow["currency"]),
242
- unit=_text(crow["unit"]),
243
- prepared_by=_text(crow["prepared_by"]),
244
- status=_text(crow["status"]),
245
- )
246
-
247
- accounts: dict[str, PilotAccount] = {}
248
- for row in parsed["Accounts"]:
249
- account = PilotAccount(
250
- full_code=_text(row["account_full_code"]),
251
- name=_text(row["account_name"]),
252
- general_code=_text(row["general_code"]),
253
- general_name=_text(row["general_name"]),
254
- opening=_decimal(row["opening"]),
255
- debit=_decimal(row["debit"]),
256
- credit=_decimal(row["credit"]),
257
- closing=_decimal(row["closing"]),
258
- source_row=int(row["source_row"]),
259
- row_status=_text(row["row_status"]),
260
- subsidiary_code=_text(row["subsidiary_code"]),
261
- subsidiary_name=_text(row["subsidiary_name"]),
262
- detail1_code=_text(row["detail1_code"]),
263
- detail1_name=_text(row["detail1_name"]),
264
- detail2_code=_text(row["detail2_code"]),
265
- detail2_name=_text(row["detail2_name"]),
266
- detail3_code=_text(row["detail3_code"]),
267
- detail3_name=_text(row["detail3_name"]),
268
- detail4_code=_text(row["detail4_code"]),
269
- detail4_name=_text(row["detail4_name"]),
270
- )
271
- accounts[account.full_code] = account
272
- accounts = dict(sorted(accounts.items()))
273
-
274
- notes: dict[tuple[str, str, str, str], NoteTarget] = {}
275
- for row in parsed["Notes"]:
276
- note = NoteTarget(
277
- statement=_text(row["statement"]),
278
- section=_text(row["statement_section"]),
279
- note_number=_text(row["note_number"]),
280
- note_title=_text(row["note_title"]),
281
- subnote_code=_text(row["subnote_code"]),
282
- subnote_title=_text(row["subnote_title"]),
283
- )
284
- notes[note.key] = note
285
-
286
- mappings: dict[str, MappingEntry] = {}
287
- conflicts: dict[str, tuple[MappingEntry, ...]] = {}
288
- for row in parsed["Mapping"]:
289
- entry = MappingEntry(
290
- account_code=_text(row["account_full_code"]),
291
- statement=_text(row["target_statement"]),
292
- section=_text(row["statement_section"]),
293
- note_number=_text(row["note_number"]),
294
- subnote_code=_text(row["subnote_code"]),
295
- approval_status=_text(row["approval_status"]),
296
- reviewer=_text(row["reviewer"]),
297
- source=_text(row["source"]),
298
- mapping_id=_text(row["mapping_id"]),
299
- )
300
- existing = mappings.get(entry.account_code)
301
- if entry.account_code in conflicts:
302
- conflicts[entry.account_code] += (entry,)
303
- elif existing is None:
304
- mappings[entry.account_code] = entry
305
- elif existing.target_key != entry.target_key:
306
- conflicts[entry.account_code] = (existing, entry)
307
- del mappings[entry.account_code]
308
- # Identical duplicate targets are deduplicated deterministically.
309
-
310
- return PilotModel(
311
- company=company,
312
- accounts=accounts,
313
- notes=notes,
314
- mappings=mappings,
315
- conflicts=conflicts,
316
- source_sha256=hashlib.sha256(workbook_bytes).hexdigest(),
317
- )
318
-
319
-
320
-def _amount(value: Decimal) -> str:
321
- """Exact decimal as string; JSON never loses precision through floats."""
322
- return format(value, "f")
323
-
324
-
325
-def _account_json(account: PilotAccount, mapping: MappingEntry | None, sign: int | None) -> dict:
326
- payload = {
327
- "code": account.full_code,
328
- "name": account.name,
329
- "closing": _amount(account.closing),
330
- "source_row": account.source_row,
331
- "row_status": account.row_status,
332
- }
333
- if sign is not None:
334
- payload["display"] = _amount(sign * account.closing)
335
- if mapping is not None:
336
- payload["approval_status"] = mapping.approval_status
337
- return payload
338
-
339
-
340
-def build_report(model: PilotModel, mappings: dict[str, MappingEntry]) -> dict:
341
- """Compute coverage, exceptions, checks and BS/IS drafts deterministically."""
342
- exceptions: list[dict] = []
343
- buckets: dict[tuple[str, str, str, str], list[tuple[PilotAccount, MappingEntry]]] = {}
344
- mapped_count = 0
345
-
346
- for code, account in model.accounts.items():
347
- resolved = mappings.get(code)
348
- if code in model.conflicts and not (resolved and resolved.source == "workbench"):
349
- exceptions.append({
350
- "code": "MAPPING_CONFLICT",
351
- "account_code": code,
352
- "account_name": account.name,
353
- "closing": _amount(account.closing),
354
- "source_row": account.source_row,
355
- "details": "چند نگاشت با مقصدهای متفاوت برای این حساب وجود دارد؛ "
356
- "تا رفع تعارض، حساب در صورتها منظور نمیشود.",
357
- })
358
- continue
359
- mapping = mappings.get(code)
360
- if mapping is None:
361
- exceptions.append({
362
- "code": "UNMAPPED_ACCOUNT",
363
- "account_code": code,
364
- "account_name": account.name,
365
- "closing": _amount(account.closing),
366
- "source_row": account.source_row,
367
- "details": "حساب نگاشت نشده است؛ مقصد آن را در زبانهٔ نگاشت تعیین کنید.",
368
- })
369
- continue
370
- mapped_count += 1
371
- if mapping.statement in DEFERRED_STATEMENTS:
372
- exceptions.append({
373
- "code": "DEFERRED_STATEMENT",
374
- "account_code": code,
375
- "account_name": account.name,
376
- "closing": _amount(account.closing),
377
- "source_row": account.source_row,
378
- "details": f"مقصد {mapping.statement} در این نسخه رندر نمیشود؛ "
379
- "موتور جریان نقدی/تغییرات حقوق مالکانه در گام بعدی است.",
380
- })
381
- continue
382
- policy = SECTION_POLICY.get(mapping.statement, {})
383
- if mapping.section not in policy:
384
- exceptions.append({
385
- "code": "UNSUPPORTED_SECTION",
386
- "account_code": code,
387
- "account_name": account.name,
388
- "closing": _amount(account.closing),
389
- "source_row": account.source_row,
390
- "details": f"بخش «{mapping.section}» در سیاست علامت صریح تعریف نشده است؛ "
391
- "حدس زدن ممنوع است.",
392
- })
393
- continue
394
- buckets.setdefault(mapping.target_key, []).append((account, mapping))
395
-
396
- statements: dict[str, dict] = {}
397
- section_totals: dict[tuple[str, str], Decimal] = {}
398
- for statement in RENDERED_STATEMENTS:
399
- sections = []
400
- for section, sign in SECTION_POLICY[statement].items():
401
- lines = []
402
- for key in sorted(k for k in buckets if k[0] == statement and k[1] == section):
403
- members = buckets[key]
404
- note = model.notes.get(key)
405
- line_total = sum((sign * a.closing for a, _ in members), _ZERO)
406
- lines.append({
407
- "note_number": key[2],
408
- "note_title": note.note_title if note else "",
409
- "subnote_code": key[3],
410
- "subnote_title": note.subnote_title if note else "",
411
- "total": _amount(line_total),
412
- "accounts": [
413
- _account_json(a, m, sign)
414
- for a, m in sorted(members, key=lambda item: item[0].full_code)
415
- ],
416
- })
417
- total = sum((Decimal(line["total"]) for line in lines), _ZERO)
418
- section_totals[(statement, section)] = total
419
- sections.append({
420
- "name": section,
421
- "label_fa": SECTION_LABELS_FA.get(section, section),
422
- "total": _amount(total),
423
- "lines": lines,
424
- })
425
- statements[statement] = {"label_fa": STATEMENT_LABELS_FA[statement], "sections": sections}
426
-
427
- assets = section_totals[("BS", "Assets")]
428
- liabilities = section_totals[("BS", "Liabilities")]
429
- equity = section_totals[("BS", "Equity")]
430
- revenue = section_totals[("IS", "Revenue")]
431
- expenses = section_totals[("IS", "Expenses")]
432
- profit = revenue - expenses
433
- trial_balance_sum = sum((a.closing for a in model.accounts.values()), _ZERO)
434
- equation_residual = assets - liabilities - equity - profit
435
- all_approved = bool(mappings) and all(
436
- m.approval_status == "Approved" for m in mappings.values()
437
- )
438
-
439
- checks = [
440
- {
441
- "code": "NON_EMPTY_ACCOUNTS",
442
- "name_fa": "وجود حسابهای منبع",
443
- "passed": bool(model.accounts),
444
- "amount": None,
445
- "details": f"{len(model.accounts)} حساب در فایل ورودی ثبت شده است.",
446
- },
447
- {
448
- "code": "TRIAL_BALANCE_CLOSED",
449
- "name_fa": "تراز بودن ماندههای دفتر کل",
450
- "passed": trial_balance_sum == _ZERO,
451
- "amount": _amount(trial_balance_sum),
452
- "details": "جمع ماندههای پایان دوره (بدهکار مثبت) باید صفر باشد.",
453
- },
454
- {
455
- "code": "FULL_COVERAGE",
456
- "name_fa": "پوشش کامل نگاشت",
457
- "passed": not exceptions,
458
- "amount": None,
459
- "details": f"{len(exceptions)} استثنا باقی مانده است." if exceptions
460
- else "همهٔ حسابها نگاشت معتبر دارند.",
461
- },
462
- {
463
- "code": "ACCOUNTING_EQUATION",
464
- "name_fa": "معادلهٔ حسابداری",
465
- "passed": equation_residual == _ZERO,
466
- "amount": _amount(equation_residual),
467
- "details": "داراییها − بدهیها − حقوق مالکانه − سود دوره باید صفر باشد.",
468
- },
469
- {
470
- "code": "MAPPINGS_APPROVED",
471
- "name_fa": "تأیید همهٔ نگاشتها",
472
- "passed": all_approved,
473
- "amount": None,
474
- "details": "همهٔ نگاشتهای مؤثر وضعیت Approved دارند." if all_approved
475
- else "برخی نگاشتها هنوز Approved نیستند؛ خروجی پیشنویس میماند.",
476
- },
477
- ]
478
- complete = all(c["passed"] for c in checks if c["code"] != "MAPPINGS_APPROVED")
479
- label = (
480
- "COMPLETE_APPROVED" if complete and all_approved
481
- else "COMPLETE_DRAFT" if complete
482
- else "INCOMPLETE"
483
- )
484
-
485
- return {
486
- "engine_version": ENGINE_VERSION,
487
- "company": {
488
- "code": model.company.code,
489
- "name": model.company.name,
490
- "fiscal_year": model.company.fiscal_year,
491
- "currency": model.company.currency,
492
- "unit": model.company.unit,
493
- "prepared_by": model.company.prepared_by,
494
- "status": model.company.status,
495
- },
496
- "source_sha256": model.source_sha256,
497
- "status": {"label": label, "complete": complete, "all_mappings_approved": all_approved},
498
- "coverage": {
499
- "total_accounts": len(model.accounts),
500
- "mapped_accounts": mapped_count,
501
- "exception_count": len(exceptions),
502
- },
503
- "totals": {
504
- "assets": _amount(assets),
505
- "liabilities": _amount(liabilities),
506
- "equity": _amount(equity),
507
- "liabilities_and_equity": _amount(liabilities + equity),
508
- "revenue": _amount(revenue),
509
- "expenses": _amount(expenses),
510
- "profit": _amount(profit),
511
- },
512
- "checks": checks,
513
- "statements": statements,
514
- "exceptions": exceptions,
515
- }
516
-
517
-
518
-def accounts_table(model: PilotModel, mappings: dict[str, MappingEntry]) -> list[dict]:
519
- rows = []
520
- for code, account in model.accounts.items():
521
- mapping = mappings.get(code)
522
- rows.append({
523
- **_account_json(account, mapping, None),
524
- "general_code": account.general_code,
525
- "general_name": account.general_name,
526
- "conflict": code in model.conflicts
527
- and not (mapping and mapping.source == "workbench"),
528
- "mapping": None if mapping is None else {
529
- "statement": mapping.statement,
530
- "section": mapping.section,
531
- "note_number": mapping.note_number,
532
- "subnote_code": mapping.subnote_code,
533
- "approval_status": mapping.approval_status,
534
- "reviewer": mapping.reviewer,
535
- "source": mapping.source,
536
- "mapping_id": mapping.mapping_id,
537
- },
538
- })
539
- return rows
540
-
541
-
542
-def notes_table(model: PilotModel) -> list[dict]:
543
- return [
544
- {
545
- "statement": note.statement,
546
- "section": note.section,
547
- "note_number": note.note_number,
548
- "note_title": note.note_title,
549
- "subnote_code": note.subnote_code,
550
- "subnote_title": note.subnote_title,
551
- }
552
- for note in sorted(model.notes.values(), key=lambda n: n.key)
553
- ]
554
-
555
-
556
-def export_report_workbook(
557
- model: PilotModel,
558
- mappings: dict[str, MappingEntry],
559
- report: dict,
560
- audit_trail: list[dict],
561
- source_label: str,
562
-) -> bytes:
563
- """Render the reviewable Excel output. Values are derived, never invented."""
564
- workbook = Workbook()
565
- workbook.remove(workbook.active)
566
- header_font = Font(bold=True, color="FFFFFF")
567
- header_fill = PatternFill("solid", fgColor="1F4E78")
568
- title_font = Font(bold=True, size=13)
569
-
570
- def sheet(name: str, headers: tuple[str, ...]) -> Any:
571
- ws = workbook.create_sheet(name)
572
- ws.append(headers)
573
- for cell in ws[1]:
574
- cell.font = header_font
575
- cell.fill = header_fill
576
- ws.freeze_panes = "A2"
577
- ws.sheet_view.rightToLeft = True
578
- for column in range(1, len(headers) + 1):
579
- ws.column_dimensions[ws.cell(1, column).column_letter].width = 22
580
- return ws
581
-
582
- info = sheet("Info", ("field", "value"))
583
- company = report["company"]
584
- for field_name, value in (
585
- ("company_code", company["code"]),
586
- ("company_name", company["name"]),
587
- ("fiscal_year", company["fiscal_year"]),
588
- ("unit", company["unit"]),
589
- ("source", source_label),
590
- ("source_sha256", report["source_sha256"]),
591
- ("engine_version", ENGINE_VERSION),
592
- ("generated_at_utc", datetime.now(UTC).isoformat(timespec="seconds")),
593
- ("status", report["status"]["label"]),
594
- ("disclaimer", "خروجی پیشنویس کاری برای بررسی است؛ صورت مالی رسمی نیست. "
595
- "هیچ مبلغی حدس زده یا جایگزین نشده است."),
596
- ):
597
- info.append((field_name, value))
598
- if source_label == "demo":
599
- info.append(("synthetic_data", "TRUE — دادههای دمو کاملاً ساختگی و غیرواقعی هستند."))
600
- info.column_dimensions["B"].width = 80
601
-
602
- checks = sheet("Checks", ("check_code", "name_fa", "passed", "amount", "details"))
603
- for check in report["checks"]:
604
- checks.append((
605
- check["code"], check["name_fa"], "PASS" if check["passed"] else "FAIL",
606
- float(check["amount"]) if check["amount"] is not None else None,
607
- check["details"],
608
- ))
609
-
610
- for statement in RENDERED_STATEMENTS:
611
- data = report["statements"][statement]
612
- ws = sheet(
613
- "BalanceSheet" if statement == "BS" else "IncomeStatement",
614
- ("level", "section", "note", "title", "amount", "account_code", "source_row"),
615
- )
616
- ws.append(("title", "", "", f"{data['label_fa']} — {company['name']} — {company['fiscal_year']}", None, "", None))
617
- ws.cell(ws.max_row, 4).font = title_font
618
- for section in data["sections"]:
619
- ws.append(("section", section["name"], "", section["label_fa"], float(section["total"]), "", None))
620
- ws.cell(ws.max_row, 5).font = Font(bold=True)
621
- for line in section["lines"]:
622
- title = line["note_title"]
623
- if line["subnote_code"]:
624
- title += f" / {line['subnote_code']} {line['subnote_title']}".rstrip()
625
- ws.append(("note", section["name"], line["note_number"], title, float(line["total"]), "", None))
626
- for account in line["accounts"]:
627
- ws.append((
628
- "account", section["name"], line["note_number"], account["name"],
629
- float(account["display"]), account["code"], account["source_row"],
630
- ))
631
- ws.cell(ws.max_row, 4).alignment = Alignment(indent=1)
632
- if statement == "IS":
633
- ws.append(("total", "", "", "سود (زیان) دوره", float(report["totals"]["profit"]), "", None))
634
- ws.cell(ws.max_row, 5).font = Font(bold=True)
635
- ws.column_dimensions["D"].width = 48
636
-
637
- coverage = sheet("Coverage", (
638
- "account_code", "account_name", "closing", "source_row", "statement",
639
- "section", "note_number", "subnote_code", "approval_status", "mapping_source",
640
- ))
641
- for row in accounts_table(model, mappings):
642
- mapping = row["mapping"] or {}
643
- coverage.append((
644
- row["code"], row["name"], float(row["closing"]), row["source_row"],
645
- mapping.get("statement"), mapping.get("section"), mapping.get("note_number"),
646
- mapping.get("subnote_code"), mapping.get("approval_status"), mapping.get("source"),
647
- ))
648
-
649
- exceptions = sheet("Exceptions", ("code", "account_code", "account_name", "closing", "source_row", "details"))
650
- for item in report["exceptions"]:
651
- exceptions.append((
652
- item["code"], item["account_code"], item["account_name"],
653
- float(item["closing"]), item["source_row"], item["details"],
654
- ))
655
- exceptions.column_dimensions["F"].width = 70
656
-
657
- trail = sheet("AuditTrail", ("at_utc", "actor", "account_code", "action", "before", "after"))
658
- for entry in audit_trail:
659
- trail.append((
660
- entry["at"], entry["actor"], entry["account_code"], entry["action"],
661
- entry["before"], entry["after"],
662
- ))
663
- trail.column_dimensions["E"].width = 46
664
- trail.column_dimensions["F"].width = 46
665
-
666
- stream = BytesIO()
667
- workbook.save(stream)
668
- return stream.getvalue()
669
-
670
-
671
-def export_working_workbook(model: WorkingModel) -> bytes:
672
- """Serialize the full working state back to a valid Pilot v0.1 workbook.
673
-
674
- This is the durable "save workspace" artifact: re-uploading it rebuilds
675
- the same accounts, notes, mappings and company. Codes are written as text
676
- and mapping hierarchy is derived from each account so preflight passes.
677
- """
678
- workbook = Workbook()
679
- workbook.remove(workbook.active)
680
- header_font = Font(bold=True, color="FFFFFF")
681
- header_fill = PatternFill("solid", fgColor="1F4E78")
682
- sheets: dict[str, Any] = {}
683
- for name, headers in SHEET_HEADERS.items():
684
- ws = workbook.create_sheet(name)
685
- ws.append(headers)
686
- for cell in ws[1]:
687
- cell.font = header_font
688
- cell.fill = header_fill
689
- ws.freeze_panes = "A2"
690
- ws.sheet_view.rightToLeft = True
691
- sheets[name] = ws
692
-
693
- def row(sheet: str, values: dict) -> None:
694
- sheets[sheet].append(tuple(values.get(h) for h in SHEET_HEADERS[sheet]))
695
-
696
- company = model.company
697
- row("Company", {
698
- "company_code": company.code, "company_name": company.name,
699
- "fiscal_year": company.fiscal_year, "currency": company.currency,
700
- "unit": company.unit, "prepared_by": company.prepared_by,
701
- "status": company.status or "Draft",
702
- })
703
-
704
- for account in model.accounts.values():
705
- codes = hierarchy_codes(account)
706
- names = (
707
- account.general_name, account.subsidiary_name, account.detail1_name,
708
- account.detail2_name, account.detail3_name, account.detail4_name,
709
- )
710
- values = {
711
- "company_code": company.code, "fiscal_year": company.fiscal_year,
712
- "account_full_code": account.full_code, "account_name": account.name,
713
- "opening": float(account.opening), "debit": float(account.debit),
714
- "credit": float(account.credit), "closing": float(account.closing),
715
- "source_row": account.source_row, "row_status": account.row_status or "Draft",
716
- "closing_delta": 0,
717
- }
718
- for index, field_name in enumerate(_HIERARCHY_CODE_FIELDS):
719
- values[field_name] = codes[index] or None
720
- values[field_name.replace("_code", "_name")] = names[index] or None
721
- row("Accounts", values)
722
-
723
- for note in model.notes.values():
724
- row("Notes", {
725
- "company_code": company.code, "fiscal_year": company.fiscal_year,
726
- "statement": note.statement, "statement_section": note.section,
727
- "note_number": note.note_number, "note_title": note.note_title,
728
- "subnote_code": note.subnote_code or None,
729
- "subnote_title": note.subnote_title or None,
730
- })
731
-
732
- today = datetime.now(UTC).date().isoformat()
733
- for mapping in model.mappings.values():
734
- account = model.accounts.get(mapping.account_code)
735
- if account is None:
736
- continue
737
- codes = hierarchy_codes(account)
738
- approved = mapping.approval_status == "Approved"
739
- reviewed = mapping.approval_status in {"Reviewed", "Approved"}
740
- values = {
741
- "mapping_id": mapping.mapping_id or f"WB-{mapping.account_code}",
742
- "company_code": company.code, "fiscal_year": company.fiscal_year,
743
- "account_full_code": mapping.account_code,
744
- "account_level": account_level_of(account),
745
- "target_statement": mapping.statement, "statement_section": mapping.section,
746
- "note_number": mapping.note_number, "subnote_code": mapping.subnote_code or None,
747
- "mapping_version": 1, "approval_status": mapping.approval_status or "Draft",
748
- "reviewer": mapping.reviewer or (company.prepared_by or "workbench"),
749
- "review_date": today if reviewed else None,
750
- "source": mapping.source or "workbench",
751
- "validation_status": "Valid" if approved else "Pending",
752
- }
753
- for index, field_name in enumerate(_HIERARCHY_CODE_FIELDS):
754
- values[field_name] = codes[index] or None
755
- row("Mapping", values)
756
-
757
- sheets["Guide_FA"].append(
758
- ("ذخیرهٔ کارگاه", "این فایل خروجی «ذخیرهٔ کارگاه» است؛ برای ادامهٔ کار دوباره آپلودش کنید.")
759
- )
760
- stream = BytesIO()
761
- workbook.save(stream)
762
- return stream.getvalue()