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.0.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
+
92
+
93
+@dataclass(frozen=True)
94
+class NoteTarget:
95
+ statement: str
96
+ section: str
97
+ note_number: str
98
+ note_title: str
99
+ subnote_code: str
100
+ subnote_title: str
101
+
102
+ @property
103
+ def key(self) -> tuple[str, str, str, str]:
104
+ return (self.statement, self.section, self.note_number, self.subnote_code)
105
+
106
+
107
+@dataclass(frozen=True)
108
+class MappingEntry:
109
+ account_code: str
110
+ statement: str
111
+ section: str
112
+ note_number: str
113
+ subnote_code: str
114
+ approval_status: str
115
+ reviewer: str
116
+ source: str
117
+ mapping_id: str
118
+
119
+ @property
120
+ def target_key(self) -> tuple[str, str, str, str]:
121
+ return (self.statement, self.section, self.note_number, self.subnote_code)
122
+
123
+
124
+@dataclass(frozen=True)
125
+class PilotModel:
126
+ company: PilotCompany
127
+ accounts: dict[str, PilotAccount]
128
+ notes: dict[tuple[str, str, str, str], NoteTarget]
129
+ mappings: dict[str, MappingEntry]
130
+ conflicts: dict[str, tuple[MappingEntry, ...]]
131
+ source_sha256: str
132
+
133
+
134
+def _rows(sheet: Any, headers: tuple[str, ...]) -> list[dict[str, Any]]:
135
+ result = []
136
+ for values in sheet.iter_rows(min_row=2, values_only=True):
137
+ row = dict(zip(headers, values))
138
+ if any(v is not None and not (isinstance(v, str) and not v.strip()) for v in row.values()):
139
+ result.append(row)
140
+ return result
141
+
142
+
143
+def _text(value: Any) -> str:
144
+ return value.strip() if isinstance(value, str) else ""
145
+
146
+
147
+def _decimal(value: Any) -> Decimal:
148
+ return Decimal(str(value).strip())
149
+
150
+
151
+def parse_pilot_model(workbook_bytes: bytes) -> PilotModel:
152
+ """Parse a preflight-valid workbook into a typed, immutable model."""
153
+ preflight = preflight_pilot_workbook(workbook_bytes)
154
+ if not preflight.valid:
155
+ raise PilotModelError(list(preflight.issues))
156
+
157
+ workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=True)
158
+ parsed = {
159
+ name: _rows(workbook[name], headers) for name, headers in SHEET_HEADERS.items()
160
+ }
161
+ workbook.close()
162
+
163
+ company_rows = parsed["Company"]
164
+ if len(company_rows) != 1:
165
+ raise PilotModelError([PilotIssue(
166
+ "ERROR", "WORKBENCH_SINGLE_COMPANY_REQUIRED", "Company", 0, "__sheet__",
167
+ "The workbench renders exactly one company/fiscal year per workbook; "
168
+ f"found {len(company_rows)} company rows.",
169
+ )])
170
+ crow = company_rows[0]
171
+ company = PilotCompany(
172
+ code=_text(crow["company_code"]),
173
+ name=_text(crow["company_name"]),
174
+ fiscal_year=int(crow["fiscal_year"]),
175
+ currency=_text(crow["currency"]),
176
+ unit=_text(crow["unit"]),
177
+ prepared_by=_text(crow["prepared_by"]),
178
+ status=_text(crow["status"]),
179
+ )
180
+
181
+ accounts: dict[str, PilotAccount] = {}
182
+ for row in parsed["Accounts"]:
183
+ account = PilotAccount(
184
+ full_code=_text(row["account_full_code"]),
185
+ name=_text(row["account_name"]),
186
+ general_code=_text(row["general_code"]),
187
+ general_name=_text(row["general_name"]),
188
+ opening=_decimal(row["opening"]),
189
+ debit=_decimal(row["debit"]),
190
+ credit=_decimal(row["credit"]),
191
+ closing=_decimal(row["closing"]),
192
+ source_row=int(row["source_row"]),
193
+ row_status=_text(row["row_status"]),
194
+ )
195
+ accounts[account.full_code] = account
196
+ accounts = dict(sorted(accounts.items()))
197
+
198
+ notes: dict[tuple[str, str, str, str], NoteTarget] = {}
199
+ for row in parsed["Notes"]:
200
+ note = NoteTarget(
201
+ statement=_text(row["statement"]),
202
+ section=_text(row["statement_section"]),
203
+ note_number=_text(row["note_number"]),
204
+ note_title=_text(row["note_title"]),
205
+ subnote_code=_text(row["subnote_code"]),
206
+ subnote_title=_text(row["subnote_title"]),
207
+ )
208
+ notes[note.key] = note
209
+
210
+ mappings: dict[str, MappingEntry] = {}
211
+ conflicts: dict[str, tuple[MappingEntry, ...]] = {}
212
+ for row in parsed["Mapping"]:
213
+ entry = MappingEntry(
214
+ account_code=_text(row["account_full_code"]),
215
+ statement=_text(row["target_statement"]),
216
+ section=_text(row["statement_section"]),
217
+ note_number=_text(row["note_number"]),
218
+ subnote_code=_text(row["subnote_code"]),
219
+ approval_status=_text(row["approval_status"]),
220
+ reviewer=_text(row["reviewer"]),
221
+ source=_text(row["source"]),
222
+ mapping_id=_text(row["mapping_id"]),
223
+ )
224
+ existing = mappings.get(entry.account_code)
225
+ if entry.account_code in conflicts:
226
+ conflicts[entry.account_code] += (entry,)
227
+ elif existing is None:
228
+ mappings[entry.account_code] = entry
229
+ elif existing.target_key != entry.target_key:
230
+ conflicts[entry.account_code] = (existing, entry)
231
+ del mappings[entry.account_code]
232
+ # Identical duplicate targets are deduplicated deterministically.
233
+
234
+ return PilotModel(
235
+ company=company,
236
+ accounts=accounts,
237
+ notes=notes,
238
+ mappings=mappings,
239
+ conflicts=conflicts,
240
+ source_sha256=hashlib.sha256(workbook_bytes).hexdigest(),
241
+ )
242
+
243
+
244
+def _amount(value: Decimal) -> str:
245
+ """Exact decimal as string; JSON never loses precision through floats."""
246
+ return format(value, "f")
247
+
248
+
249
+def _account_json(account: PilotAccount, mapping: MappingEntry | None, sign: int | None) -> dict:
250
+ payload = {
251
+ "code": account.full_code,
252
+ "name": account.name,
253
+ "closing": _amount(account.closing),
254
+ "source_row": account.source_row,
255
+ "row_status": account.row_status,
256
+ }
257
+ if sign is not None:
258
+ payload["display"] = _amount(sign * account.closing)
259
+ if mapping is not None:
260
+ payload["approval_status"] = mapping.approval_status
261
+ return payload
262
+
263
+
264
+def build_report(model: PilotModel, mappings: dict[str, MappingEntry]) -> dict:
265
+ """Compute coverage, exceptions, checks and BS/IS drafts deterministically."""
266
+ exceptions: list[dict] = []
267
+ buckets: dict[tuple[str, str, str, str], list[tuple[PilotAccount, MappingEntry]]] = {}
268
+ mapped_count = 0
269
+
270
+ for code, account in model.accounts.items():
271
+ resolved = mappings.get(code)
272
+ if code in model.conflicts and not (resolved and resolved.source == "workbench"):
273
+ exceptions.append({
274
+ "code": "MAPPING_CONFLICT",
275
+ "account_code": code,
276
+ "account_name": account.name,
277
+ "closing": _amount(account.closing),
278
+ "source_row": account.source_row,
279
+ "details": "چند نگاشت با مقصدهای متفاوت برای این حساب وجود دارد؛ "
280
+ "تا رفع تعارض، حساب در صورتها منظور نمیشود.",
281
+ })
282
+ continue
283
+ mapping = mappings.get(code)
284
+ if mapping is None:
285
+ exceptions.append({
286
+ "code": "UNMAPPED_ACCOUNT",
287
+ "account_code": code,
288
+ "account_name": account.name,
289
+ "closing": _amount(account.closing),
290
+ "source_row": account.source_row,
291
+ "details": "حساب نگاشت نشده است؛ مقصد آن را در زبانهٔ نگاشت تعیین کنید.",
292
+ })
293
+ continue
294
+ mapped_count += 1
295
+ if mapping.statement in DEFERRED_STATEMENTS:
296
+ exceptions.append({
297
+ "code": "DEFERRED_STATEMENT",
298
+ "account_code": code,
299
+ "account_name": account.name,
300
+ "closing": _amount(account.closing),
301
+ "source_row": account.source_row,
302
+ "details": f"مقصد {mapping.statement} در این نسخه رندر نمیشود؛ "
303
+ "موتور جریان نقدی/تغییرات حقوق مالکانه در گام بعدی است.",
304
+ })
305
+ continue
306
+ policy = SECTION_POLICY.get(mapping.statement, {})
307
+ if mapping.section not in policy:
308
+ exceptions.append({
309
+ "code": "UNSUPPORTED_SECTION",
310
+ "account_code": code,
311
+ "account_name": account.name,
312
+ "closing": _amount(account.closing),
313
+ "source_row": account.source_row,
314
+ "details": f"بخش «{mapping.section}» در سیاست علامت صریح تعریف نشده است؛ "
315
+ "حدس زدن ممنوع است.",
316
+ })
317
+ continue
318
+ buckets.setdefault(mapping.target_key, []).append((account, mapping))
319
+
320
+ statements: dict[str, dict] = {}
321
+ section_totals: dict[tuple[str, str], Decimal] = {}
322
+ for statement in RENDERED_STATEMENTS:
323
+ sections = []
324
+ for section, sign in SECTION_POLICY[statement].items():
325
+ lines = []
326
+ for key in sorted(k for k in buckets if k[0] == statement and k[1] == section):
327
+ members = buckets[key]
328
+ note = model.notes.get(key)
329
+ line_total = sum((sign * a.closing for a, _ in members), _ZERO)
330
+ lines.append({
331
+ "note_number": key[2],
332
+ "note_title": note.note_title if note else "",
333
+ "subnote_code": key[3],
334
+ "subnote_title": note.subnote_title if note else "",
335
+ "total": _amount(line_total),
336
+ "accounts": [
337
+ _account_json(a, m, sign)
338
+ for a, m in sorted(members, key=lambda item: item[0].full_code)
339
+ ],
340
+ })
341
+ total = sum((Decimal(line["total"]) for line in lines), _ZERO)
342
+ section_totals[(statement, section)] = total
343
+ sections.append({
344
+ "name": section,
345
+ "label_fa": SECTION_LABELS_FA.get(section, section),
346
+ "total": _amount(total),
347
+ "lines": lines,
348
+ })
349
+ statements[statement] = {"label_fa": STATEMENT_LABELS_FA[statement], "sections": sections}
350
+
351
+ assets = section_totals[("BS", "Assets")]
352
+ liabilities = section_totals[("BS", "Liabilities")]
353
+ equity = section_totals[("BS", "Equity")]
354
+ revenue = section_totals[("IS", "Revenue")]
355
+ expenses = section_totals[("IS", "Expenses")]
356
+ profit = revenue - expenses
357
+ trial_balance_sum = sum((a.closing for a in model.accounts.values()), _ZERO)
358
+ equation_residual = assets - liabilities - equity - profit
359
+ all_approved = bool(mappings) and all(
360
+ m.approval_status == "Approved" for m in mappings.values()
361
+ )
362
+
363
+ checks = [
364
+ {
365
+ "code": "NON_EMPTY_ACCOUNTS",
366
+ "name_fa": "وجود حسابهای منبع",
367
+ "passed": bool(model.accounts),
368
+ "amount": None,
369
+ "details": f"{len(model.accounts)} حساب در فایل ورودی ثبت شده است.",
370
+ },
371
+ {
372
+ "code": "TRIAL_BALANCE_CLOSED",
373
+ "name_fa": "تراز بودن ماندههای دفتر کل",
374
+ "passed": trial_balance_sum == _ZERO,
375
+ "amount": _amount(trial_balance_sum),
376
+ "details": "جمع ماندههای پایان دوره (بدهکار مثبت) باید صفر باشد.",
377
+ },
378
+ {
379
+ "code": "FULL_COVERAGE",
380
+ "name_fa": "پوشش کامل نگاشت",
381
+ "passed": not exceptions,
382
+ "amount": None,
383
+ "details": f"{len(exceptions)} استثنا باقی مانده است." if exceptions
384
+ else "همهٔ حسابها نگاشت معتبر دارند.",
385
+ },
386
+ {
387
+ "code": "ACCOUNTING_EQUATION",
388
+ "name_fa": "معادلهٔ حسابداری",
389
+ "passed": equation_residual == _ZERO,
390
+ "amount": _amount(equation_residual),
391
+ "details": "داراییها − بدهیها − حقوق مالکانه − سود دوره باید صفر باشد.",
392
+ },
393
+ {
394
+ "code": "MAPPINGS_APPROVED",
395
+ "name_fa": "تأیید همهٔ نگاشتها",
396
+ "passed": all_approved,
397
+ "amount": None,
398
+ "details": "همهٔ نگاشتهای مؤثر وضعیت Approved دارند." if all_approved
399
+ else "برخی نگاشتها هنوز Approved نیستند؛ خروجی پیشنویس میماند.",
400
+ },
401
+ ]
402
+ complete = all(c["passed"] for c in checks if c["code"] != "MAPPINGS_APPROVED")
403
+ label = (
404
+ "COMPLETE_APPROVED" if complete and all_approved
405
+ else "COMPLETE_DRAFT" if complete
406
+ else "INCOMPLETE"
407
+ )
408
+
409
+ return {
410
+ "engine_version": ENGINE_VERSION,
411
+ "company": {
412
+ "code": model.company.code,
413
+ "name": model.company.name,
414
+ "fiscal_year": model.company.fiscal_year,
415
+ "currency": model.company.currency,
416
+ "unit": model.company.unit,
417
+ "prepared_by": model.company.prepared_by,
418
+ "status": model.company.status,
419
+ },
420
+ "source_sha256": model.source_sha256,
421
+ "status": {"label": label, "complete": complete, "all_mappings_approved": all_approved},
422
+ "coverage": {
423
+ "total_accounts": len(model.accounts),
424
+ "mapped_accounts": mapped_count,
425
+ "exception_count": len(exceptions),
426
+ },
427
+ "totals": {
428
+ "assets": _amount(assets),
429
+ "liabilities": _amount(liabilities),
430
+ "equity": _amount(equity),
431
+ "liabilities_and_equity": _amount(liabilities + equity),
432
+ "revenue": _amount(revenue),
433
+ "expenses": _amount(expenses),
434
+ "profit": _amount(profit),
435
+ },
436
+ "checks": checks,
437
+ "statements": statements,
438
+ "exceptions": exceptions,
439
+ }
440
+
441
+
442
+def accounts_table(model: PilotModel, mappings: dict[str, MappingEntry]) -> list[dict]:
443
+ rows = []
444
+ for code, account in model.accounts.items():
445
+ mapping = mappings.get(code)
446
+ rows.append({
447
+ **_account_json(account, mapping, None),
448
+ "general_code": account.general_code,
449
+ "general_name": account.general_name,
450
+ "conflict": code in model.conflicts
451
+ and not (mapping and mapping.source == "workbench"),
452
+ "mapping": None if mapping is None else {
453
+ "statement": mapping.statement,
454
+ "section": mapping.section,
455
+ "note_number": mapping.note_number,
456
+ "subnote_code": mapping.subnote_code,
457
+ "approval_status": mapping.approval_status,
458
+ "reviewer": mapping.reviewer,
459
+ "source": mapping.source,
460
+ "mapping_id": mapping.mapping_id,
461
+ },
462
+ })
463
+ return rows
464
+
465
+
466
+def notes_table(model: PilotModel) -> list[dict]:
467
+ return [
468
+ {
469
+ "statement": note.statement,
470
+ "section": note.section,
471
+ "note_number": note.note_number,
472
+ "note_title": note.note_title,
473
+ "subnote_code": note.subnote_code,
474
+ "subnote_title": note.subnote_title,
475
+ }
476
+ for note in sorted(model.notes.values(), key=lambda n: n.key)
477
+ ]
478
+
479
+
480
+def export_report_workbook(
481
+ model: PilotModel,
482
+ mappings: dict[str, MappingEntry],
483
+ report: dict,
484
+ audit_trail: list[dict],
485
+ source_label: str,
486
+) -> bytes:
487
+ """Render the reviewable Excel output. Values are derived, never invented."""
488
+ workbook = Workbook()
489
+ workbook.remove(workbook.active)
490
+ header_font = Font(bold=True, color="FFFFFF")
491
+ header_fill = PatternFill("solid", fgColor="1F4E78")
492
+ title_font = Font(bold=True, size=13)
493
+
494
+ def sheet(name: str, headers: tuple[str, ...]) -> Any:
495
+ ws = workbook.create_sheet(name)
496
+ ws.append(headers)
497
+ for cell in ws[1]:
498
+ cell.font = header_font
499
+ cell.fill = header_fill
500
+ ws.freeze_panes = "A2"
501
+ ws.sheet_view.rightToLeft = True
502
+ for column in range(1, len(headers) + 1):
503
+ ws.column_dimensions[ws.cell(1, column).column_letter].width = 22
504
+ return ws
505
+
506
+ info = sheet("Info", ("field", "value"))
507
+ company = report["company"]
508
+ for field_name, value in (
509
+ ("company_code", company["code"]),
510
+ ("company_name", company["name"]),
511
+ ("fiscal_year", company["fiscal_year"]),
512
+ ("unit", company["unit"]),
513
+ ("source", source_label),
514
+ ("source_sha256", report["source_sha256"]),
515
+ ("engine_version", ENGINE_VERSION),
516
+ ("generated_at_utc", datetime.now(UTC).isoformat(timespec="seconds")),
517
+ ("status", report["status"]["label"]),
518
+ ("disclaimer", "خروجی پیشنویس کاری برای بررسی است؛ صورت مالی رسمی نیست. "
519
+ "هیچ مبلغی حدس زده یا جایگزین نشده است."),
520
+ ):
521
+ info.append((field_name, value))
522
+ if source_label == "demo":
523
+ info.append(("synthetic_data", "TRUE — دادههای دمو کاملاً ساختگی و غیرواقعی هستند."))
524
+ info.column_dimensions["B"].width = 80
525
+
526
+ checks = sheet("Checks", ("check_code", "name_fa", "passed", "amount", "details"))
527
+ for check in report["checks"]:
528
+ checks.append((
529
+ check["code"], check["name_fa"], "PASS" if check["passed"] else "FAIL",
530
+ float(check["amount"]) if check["amount"] is not None else None,
531
+ check["details"],
532
+ ))
533
+
534
+ for statement in RENDERED_STATEMENTS:
535
+ data = report["statements"][statement]
536
+ ws = sheet(
537
+ "BalanceSheet" if statement == "BS" else "IncomeStatement",
538
+ ("level", "section", "note", "title", "amount", "account_code", "source_row"),
539
+ )
540
+ ws.append(("title", "", "", f"{data['label_fa']} — {company['name']} — {company['fiscal_year']}", None, "", None))
541
+ ws.cell(ws.max_row, 4).font = title_font
542
+ for section in data["sections"]:
543
+ ws.append(("section", section["name"], "", section["label_fa"], float(section["total"]), "", None))
544
+ ws.cell(ws.max_row, 5).font = Font(bold=True)
545
+ for line in section["lines"]:
546
+ title = line["note_title"]
547
+ if line["subnote_code"]:
548
+ title += f" / {line['subnote_code']} {line['subnote_title']}".rstrip()
549
+ ws.append(("note", section["name"], line["note_number"], title, float(line["total"]), "", None))
550
+ for account in line["accounts"]:
551
+ ws.append((
552
+ "account", section["name"], line["note_number"], account["name"],
553
+ float(account["display"]), account["code"], account["source_row"],
554
+ ))
555
+ ws.cell(ws.max_row, 4).alignment = Alignment(indent=1)
556
+ if statement == "IS":
557
+ ws.append(("total", "", "", "سود (زیان) دوره", float(report["totals"]["profit"]), "", None))
558
+ ws.cell(ws.max_row, 5).font = Font(bold=True)
559
+ ws.column_dimensions["D"].width = 48
560
+
561
+ coverage = sheet("Coverage", (
562
+ "account_code", "account_name", "closing", "source_row", "statement",
563
+ "section", "note_number", "subnote_code", "approval_status", "mapping_source",
564
+ ))
565
+ for row in accounts_table(model, mappings):
566
+ mapping = row["mapping"] or {}
567
+ coverage.append((
568
+ row["code"], row["name"], float(row["closing"]), row["source_row"],
569
+ mapping.get("statement"), mapping.get("section"), mapping.get("note_number"),
570
+ mapping.get("subnote_code"), mapping.get("approval_status"), mapping.get("source"),
571
+ ))
572
+
573
+ exceptions = sheet("Exceptions", ("code", "account_code", "account_name", "closing", "source_row", "details"))
574
+ for item in report["exceptions"]:
575
+ exceptions.append((
576
+ item["code"], item["account_code"], item["account_name"],
577
+ float(item["closing"]), item["source_row"], item["details"],
578
+ ))
579
+ exceptions.column_dimensions["F"].width = 70
580
+
581
+ trail = sheet("AuditTrail", ("at_utc", "actor", "account_code", "action", "before", "after"))
582
+ for entry in audit_trail:
583
+ trail.append((
584
+ entry["at"], entry["actor"], entry["account_code"], entry["action"],
585
+ entry["before"], entry["after"],
586
+ ))
587
+ trail.column_dimensions["E"].width = 46
588
+ trail.column_dimensions["F"].width = 46
589
+
590
+ stream = BytesIO()
591
+ workbook.save(stream)
592
+ return stream.getvalue()