@davoodmehraban89 / Aram-1 / commits / 4ab54f4
Fork 0

feat(pilot): add workbook contract and read-only preflight (#15)

Accept Gate 2A Pilot workbook contract, reproducible template, and read-only preflight validation after independent review and verified CI.

davoodmehraban89 committed Aug 25, 2026 at 08:52 UTC 4ab54f4a3cf666827fa1ed30c4e43259ea79f2d4
9 files changed +653 -71
PROJECT_STATUS.md
+6 -4
@@ -6,7 +6,7 @@
6
7 - Repository: [davoodmehraban89/Aram](https://github.com/davoodmehraban89/Aram)
8 - Accepted branch: `source-data-cleanup`
9 -- Accepted baseline commit: [`7b5bd79b760d534dad34b3162f770e838616ebe9`](https://github.com/davoodmehraban89/Aram/commit/7b5bd79b760d534dad34b3162f770e838616ebe9)
9 +- Accepted baseline commit: [`7c7533ee87146dc8fc78b46ebf423be55532c7eb`](https://github.com/davoodmehraban89/Aram/commit/7c7533ee87146dc8fc78b46ebf423be55532c7eb)
10 - Product objective: a controlled, auditable accounting and financial-statement workflow that preserves canonical source data.
11
12 ## Status vocabulary
@@ -31,6 +31,8 @@
31 | Project control refactor | `VERIFIED_AND_MERGED` | [PR #10](https://github.com/davoodmehraban89/Aram/pull/10) |
32 | One-file model refactor | `VERIFIED_AND_MERGED` | [PR #8](https://github.com/davoodmehraban89/Aram/pull/8) |
33 | Phase 2B ingestion foundation | `VERIFIED_AND_MERGED` | [PR #12](https://github.com/davoodmehraban89/Aram/pull/12), squash merge `7b5bd79b760d534dad34b3162f770e838616ebe9` |
34 +| Phase 2B control reconciliation | `VERIFIED_AND_MERGED` | [PR #13](https://github.com/davoodmehraban89/Aram/pull/13), squash merge `7c7533ee87146dc8fc78b46ebf423be55532c7eb` |
35 +| Gate 2A Pilot workbook contract/preflight | `IN_PROGRESS` | Draft [PR #15](https://github.com/davoodmehraban89/Aram/pull/15); Backend CI run #23 passed with 52 tests |
36 | Parallel V1 prototype | `VERIFIED_BUT_UNMERGED` | Closed, unmerged [PR #7](https://github.com/davoodmehraban89/Aram/pull/7); reference/recovery source only |
37 | PR #7 test/release claims | `CLAIMED_BUT_NOT_PROVEN` | No independent acceptance evidence recorded |
38 | Official V1 release | `NOT_IMPLEMENTED` | No accepted user-ready release |
@@ -49,9 +51,9 @@ The accepted branch does not include PR #7's `desktop/`, `dist/`, ZIP/EXE, or V1
51
52 ## Next approved action
53
52 -1. Independently review and merge documentation-only [PR #13](https://github.com/davoodmehraban89/Aram/pull/13), which records the post-merge control state.
53 -2. Reconfirm the accepted branch head and project records.
54 -3. Select the next focused task from the V1 Pilot roadmap in [Issue #11](https://github.com/davoodmehraban89/Aram/issues/11); do not revive PR #9 or merge PR #7 directly.
54 +1. Independently review the focused Gate 2A Draft PR implementing [Issue #14](https://github.com/davoodmehraban89/Aram/issues/14).
55 +2. Require a green full Backend CI run and verify the generated blank template checksum.
56 +3. Do not merge without a separate acceptance decision; do not revive PR #9 or merge PR #7 directly.
57
58 ## Control documents
59
backend/README.md
+15
@@ -1,5 +1,20 @@
1 # Aram backend
2
3 +## Pilot workbook preflight
4 +
5 +Gate 2A adds a strictly in-memory validator for the governed Pilot workbook.
6 +Generate the approved blank template from the repository root with:
7 +
8 +```bash
9 +cd backend
10 +PYTHONPATH=src python scripts/generate_pilot_template.py
11 +```
12 +
13 +Call `preflight_pilot_workbook(workbook_bytes)` from
14 +`aram_backend.pilot_workbook`. The result reports every detectable error with
15 +an exact sheet, Excel row, and field. The function does not persist inputs,
16 +parsed values, mappings, or reports and never guesses a financial value.
17 +
18 Phase 2A provides the persistent, audit-safe data foundation. It deliberately
19 does not ingest spreadsheets, calculate financial values, or alter canonical
20 source files.
backend/scripts/generate_pilot_template.py new
+84
@@ -0,0 +1,84 @@
1 +from __future__ import annotations
2 +
3 +from pathlib import Path
4 +
5 +from openpyxl import Workbook
6 +from openpyxl.formatting.rule import FormulaRule
7 +from openpyxl.styles import Font, PatternFill
8 +from openpyxl.worksheet.datavalidation import DataValidation
9 +
10 +from aram_backend.pilot_workbook import SHEET_HEADERS
11 +
12 +
13 +OUTPUT = Path(__file__).resolve().parents[2] / "samples" / "Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx"
14 +
15 +
16 +def build_template(output: Path = OUTPUT) -> Path:
17 + workbook = Workbook()
18 + workbook.remove(workbook.active)
19 + header_fill = PatternFill("solid", fgColor="1F4E78")
20 + for name, headers in SHEET_HEADERS.items():
21 + sheet = workbook.create_sheet(name)
22 + sheet.append(headers)
23 + sheet.freeze_panes = "A2"
24 + sheet.auto_filter.ref = f"A1:{sheet.cell(1, len(headers)).coordinate}"
25 + for cell in sheet[1]:
26 + cell.font = Font(color="FFFFFF", bold=True)
27 + cell.fill = header_fill
28 + for column in range(1, len(headers) + 1):
29 + sheet.column_dimensions[sheet.cell(1, column).column_letter].width = 18
30 +
31 + guide = workbook["Guide_FA"]
32 + instructions = [
33 + ("شروع", "ابتدا اطلاعات شرکت و سال مالی را در برگه Company وارد کنید."),
34 + ("کدها", "همه کدها را به‌صورت متن وارد کنید تا صفرهای ابتدایی حفظ شوند."),
35 + ("مبالغ", "مبالغ را فقط از منبع واقعی وارد کنید؛ فایل نمونه فاقد مبلغ ساختگی است."),
36 + ("کنترل", "قبل از ورود اطلاعات، Preflight را اجرا و همه خطاهای اعلام‌شده را رفع کنید."),
37 + ("گردش", "وضعیت نگاشت فقط Draft، Reviewed یا Approved است و خودکار ارتقا نمی‌یابد."),
38 + ]
39 + for row in instructions:
40 + guide.append(row)
41 + guide.sheet_view.rightToLeft = True
42 +
43 + lists = workbook["Lists"]
44 + approved_lists = {
45 + "company_status": ("Draft", "Approved", "Locked"),
46 + "review_status": ("Draft", "Reviewed", "Approved"),
47 + "validation_status": ("Valid", "Invalid", "Pending"),
48 + "test_status": ("Pass", "Fail", "Blocked", "Not Run"),
49 + "severity": ("Critical", "High", "Medium", "Low"),
50 + }
51 + for list_name, values in approved_lists.items():
52 + for value in values:
53 + lists.append((list_name, value))
54 +
55 + checks = workbook["Checks"]
56 + for row in (
57 + ("REQUIRED_FIELDS", "Required-field completeness", "PENDING", 0, "Run backend preflight"),
58 + ("DUPLICATE_ACCOUNTS", "Duplicate accounts", "PENDING", 0, "Run backend preflight"),
59 + ("UNKNOWN_MAPPING_ACCOUNT", "Unknown mapping accounts", "PENDING", 0, "Run backend preflight"),
60 + ("INVALID_MAPPING", "Invalid mappings", "PENDING", 0, "Run backend preflight"),
61 + ("NON_ZERO_CLOSING_DELTA", "Non-zero closing_delta", "PENDING", 0, "Run backend preflight"),
62 + ):
63 + checks.append(row)
64 +
65 + company_status = DataValidation(type="list", formula1='"Draft,Approved,Locked"')
66 + review_status = DataValidation(type="list", formula1='"Draft,Reviewed,Approved"')
67 + workbook["Company"].add_data_validation(company_status)
68 + company_status.add("G2:G500")
69 + workbook["Accounts"].add_data_validation(review_status)
70 + review_status.add("V2:V5000")
71 + mapping_status = DataValidation(type="list", formula1='"Draft,Reviewed,Approved"')
72 + workbook["Mapping"].add_data_validation(mapping_status)
73 + mapping_status.add("Q2:Q5000")
74 + red = PatternFill("solid", fgColor="FFC7CE")
75 + workbook["Accounts"].conditional_formatting.add(
76 + "W2:W5000", FormulaRule(formula=["W2<>0"], fill=red)
77 + )
78 + output.parent.mkdir(parents=True, exist_ok=True)
79 + workbook.save(output)
80 + return output
81 +
82 +
83 +if __name__ == "__main__":
84 + print(build_template())
backend/src/aram_backend/pilot_workbook.py new
+259
@@ -0,0 +1,259 @@
1 +from __future__ import annotations
2 +
3 +from collections import Counter
4 +from dataclasses import dataclass
5 +from decimal import Decimal, InvalidOperation
6 +from io import BytesIO
7 +from typing import Any
8 +from zipfile import BadZipFile
9 +
10 +from openpyxl import load_workbook
11 +from openpyxl.utils.exceptions import InvalidFileException
12 +
13 +
14 +SHEET_HEADERS: dict[str, tuple[str, ...]] = {
15 + "Company": (
16 + "company_code", "company_name", "fiscal_year", "currency", "unit",
17 + "prepared_by", "status",
18 + ),
19 + "Accounts": (
20 + "company_code", "fiscal_year", "general_code", "general_name",
21 + "subsidiary_code", "subsidiary_name", "detail1_code", "detail1_name",
22 + "detail2_code", "detail2_name", "detail3_code", "detail3_name",
23 + "detail4_code", "detail4_name", "account_full_code", "account_name",
24 + "opening", "debit", "credit", "closing", "source_row", "row_status",
25 + "closing_delta",
26 + ),
27 + "Notes": (
28 + "company_code", "fiscal_year", "statement", "statement_section",
29 + "note_number", "note_title", "subnote_code", "subnote_title",
30 + ),
31 + "Mapping": (
32 + "mapping_id", "company_code", "fiscal_year", "account_full_code",
33 + "account_level", "general_code", "subsidiary_code", "detail1_code",
34 + "detail2_code", "detail3_code", "detail4_code", "target_statement",
35 + "statement_section", "note_number", "subnote_code", "mapping_version",
36 + "approval_status", "reviewer", "review_date", "source", "notes",
37 + "validation_status",
38 + ),
39 + "Test_Log": (
40 + "tester", "feature", "expected_result", "actual_result", "status",
41 + "severity", "evidence", "notes",
42 + ),
43 + "Checks": ("check_code", "check_name", "status", "affected_rows", "details"),
44 + "Guide_FA": ("section", "instruction"),
45 + "Lists": ("list_name", "value"),
46 +}
47 +
48 +_SHEET_ORDER = {name: position for position, name in enumerate(SHEET_HEADERS)}
49 +_CODE_FIELDS = {
50 + "company_code", "general_code", "subsidiary_code", "detail1_code",
51 + "detail2_code", "detail3_code", "detail4_code", "account_full_code",
52 + "note_number", "subnote_code", "mapping_id",
53 +}
54 +_REQUIRED: dict[str, set[str]] = {
55 + "Company": {"company_code", "company_name", "fiscal_year", "status"},
56 + "Accounts": {
57 + "company_code", "fiscal_year", "general_code", "general_name",
58 + "account_full_code", "account_name", "opening", "debit", "credit",
59 + "closing", "source_row", "row_status",
60 + },
61 + "Notes": {"company_code", "fiscal_year", "statement", "note_number", "note_title"},
62 + "Mapping": {
63 + "mapping_id", "company_code", "fiscal_year", "account_full_code",
64 + "account_level", "mapping_version", "approval_status",
65 + },
66 +}
67 +
68 +
69 +@dataclass(frozen=True)
70 +class PilotIssue:
71 + severity: str
72 + code: str
73 + sheet: str
74 + row: int
75 + field: str
76 + message: str
77 +
78 +
79 +@dataclass(frozen=True)
80 +class PilotPreflightResult:
81 + valid: bool
82 + issues: tuple[PilotIssue, ...]
83 + issue_counts: dict[str, int]
84 +
85 +
86 +def _empty(value: Any) -> bool:
87 + return value is None or (isinstance(value, str) and not value.strip())
88 +
89 +
90 +def _issue(issues: list[PilotIssue], code: str, sheet: str, row: int,
91 + field: str, message: str, severity: str = "ERROR") -> None:
92 + issues.append(PilotIssue(severity, code, sheet, row, field, message))
93 +
94 +
95 +def _text_code(value: Any, issues: list[PilotIssue], sheet: str, row: int,
96 + field: str) -> str | None:
97 + if _empty(value):
98 + return None
99 + if not isinstance(value, str):
100 + _issue(issues, "CODE_NOT_TEXT", sheet, row, field,
101 + "Code cells must use Excel text format; numeric coercion is forbidden.")
102 + return None
103 + return value.strip()
104 +
105 +
106 +def _positive_int(value: Any, issues: list[PilotIssue], sheet: str, row: int,
107 + field: str) -> int | None:
108 + if _empty(value):
109 + return None
110 + if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
111 + _issue(issues, "INVALID_POSITIVE_INTEGER", sheet, row, field,
112 + "Value must be a positive integer.")
113 + return None
114 + return value
115 +
116 +
117 +def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int,
118 + field: str) -> Decimal | None:
119 + if _empty(value):
120 + return None
121 + if isinstance(value, bool) or isinstance(value, str) and value.startswith("="):
122 + _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field,
123 + "Financial values must be finite numbers, not booleans or formulas.")
124 + return None
125 + try:
126 + parsed = Decimal(str(value).strip())
127 + except (InvalidOperation, ValueError):
128 + _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field,
129 + "Financial value is not a valid decimal number.")
130 + return None
131 + if not parsed.is_finite():
132 + _issue(issues, "NON_FINITE_FINANCIAL_VALUE", sheet, row, field,
133 + "NaN and Infinity are not permitted.")
134 + return None
135 + return parsed
136 +
137 +
138 +def _rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
139 + result: list[tuple[int, dict[str, Any]]] = []
140 + for row_number, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2):
141 + row = dict(zip(headers, values))
142 + if any(not _empty(value) for value in row.values()):
143 + result.append((row_number, row))
144 + return result
145 +
146 +
147 +def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult:
148 + """Validate a Pilot workbook fully in memory without persistence or mutation."""
149 + issues: list[PilotIssue] = []
150 + try:
151 + workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=False)
152 + except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError) as exc:
153 + issue = PilotIssue("ERROR", "INVALID_WORKBOOK", "__workbook__", 0, "__file__", str(exc))
154 + return PilotPreflightResult(False, (issue,), {"ERROR": 1})
155 +
156 + valid_sheets: set[str] = set()
157 + for sheet_name, expected in SHEET_HEADERS.items():
158 + if sheet_name not in workbook.sheetnames:
159 + _issue(issues, "MISSING_SHEET", sheet_name, 1, "__sheet__",
160 + f"Required sheet {sheet_name!r} is missing.")
161 + continue
162 + actual = tuple(cell.value for cell in workbook[sheet_name][1])
163 + if actual != expected:
164 + _issue(issues, "HEADER_MISMATCH", sheet_name, 1, "__headers__",
165 + f"Expected exact header order: {', '.join(expected)}.")
166 + continue
167 + valid_sheets.add(sheet_name)
168 +
169 + parsed: dict[str, list[tuple[int, dict[str, Any]]]] = {
170 + name: _rows(workbook[name], SHEET_HEADERS[name])
171 + for name in valid_sheets
172 + }
173 + workbook.close()
174 +
175 + for sheet_name in ("Company", "Accounts", "Notes", "Mapping"):
176 + for row_number, row in parsed.get(sheet_name, []):
177 + for field in _REQUIRED[sheet_name]:
178 + if _empty(row[field]):
179 + _issue(issues, "REQUIRED_FIELD", sheet_name, row_number, field,
180 + "Required field is empty.")
181 + for field in _CODE_FIELDS.intersection(row):
182 + _text_code(row[field], issues, sheet_name, row_number, field)
183 + _positive_int(row.get("fiscal_year"), issues, sheet_name, row_number, "fiscal_year")
184 +
185 + companies: set[tuple[str, int]] = set()
186 + for row_number, row in parsed.get("Company", []):
187 + code = _text_code(row["company_code"], [], "Company", row_number, "company_code")
188 + year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
189 + if code and year and year > 0:
190 + key = (code, year)
191 + if key in companies:
192 + _issue(issues, "DUPLICATE_COMPANY_YEAR", "Company", row_number,
193 + "company_code", "Company/fiscal-year key must be unique.")
194 + companies.add(key)
195 + if not _empty(row["status"]) and row["status"] not in {"Draft", "Approved", "Locked"}:
196 + _issue(issues, "INVALID_LIFECYCLE", "Company", row_number, "status",
197 + "Allowed values are Draft, Approved, and Locked.")
198 +
199 + account_keys: set[tuple[str, int, str]] = set()
200 + for row_number, row in parsed.get("Accounts", []):
201 + code = row["company_code"] if isinstance(row["company_code"], str) else None
202 + year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
203 + account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None
204 + if code and year and (code.strip(), year) not in companies:
205 + _issue(issues, "UNKNOWN_COMPANY_YEAR", "Accounts", row_number, "company_code",
206 + "Referenced company/fiscal year is not defined in Company.")
207 + if code and year and account:
208 + key = (code.strip(), year, account.strip())
209 + if key in account_keys:
210 + _issue(issues, "DUPLICATE_ACCOUNT", "Accounts", row_number,
211 + "account_full_code", "Account key is duplicated within company/fiscal year.")
212 + account_keys.add(key)
213 + values = [_finite_decimal(row[field], issues, "Accounts", row_number, field)
214 + for field in ("opening", "debit", "credit", "closing")]
215 + _positive_int(row["source_row"], issues, "Accounts", row_number, "source_row")
216 + if not _empty(row["row_status"]) and row["row_status"] not in {"Draft", "Reviewed", "Approved"}:
217 + _issue(issues, "INVALID_LIFECYCLE", "Accounts", row_number, "row_status",
218 + "Allowed values are Draft, Reviewed, and Approved.")
219 + if all(value is not None for value in values):
220 + delta = values[0] + values[1] - values[2] - values[3]
221 + if delta != 0:
222 + _issue(issues, "NON_ZERO_CLOSING_DELTA", "Accounts", row_number,
223 + "closing_delta", f"opening + debit - credit - closing equals {delta}.")
224 +
225 + for sheet_name in ("Notes", "Mapping"):
226 + for row_number, row in parsed.get(sheet_name, []):
227 + code = row["company_code"] if isinstance(row["company_code"], str) else None
228 + year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
229 + if code and year and (code.strip(), year) not in companies:
230 + _issue(issues, "UNKNOWN_COMPANY_YEAR", sheet_name, row_number,
231 + "company_code", "Referenced company/fiscal year is not defined in Company.")
232 +
233 + mapping_ids: set[str] = set()
234 + for row_number, row in parsed.get("Mapping", []):
235 + mapping_id = row["mapping_id"] if isinstance(row["mapping_id"], str) else None
236 + if mapping_id:
237 + if mapping_id.strip() in mapping_ids:
238 + _issue(issues, "DUPLICATE_MAPPING_ID", "Mapping", row_number,
239 + "mapping_id", "Mapping ID must be unique.")
240 + mapping_ids.add(mapping_id.strip())
241 + _positive_int(row["mapping_version"], issues, "Mapping", row_number, "mapping_version")
242 + if not _empty(row["approval_status"]) and row["approval_status"] not in {"Draft", "Reviewed", "Approved"}:
243 + _issue(issues, "INVALID_LIFECYCLE", "Mapping", row_number, "approval_status",
244 + "Allowed values are Draft, Reviewed, and Approved.")
245 + code = row["company_code"] if isinstance(row["company_code"], str) else None
246 + year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None
247 + account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None
248 + if code and year and account and (code.strip(), year, account.strip()) not in account_keys:
249 + _issue(issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number,
250 + "account_full_code", "Mapped account does not exist in Accounts for this company/fiscal year.")
251 +
252 + ordered = tuple(sorted(issues, key=lambda item: (
253 + _SHEET_ORDER.get(item.sheet, -1), item.row,
254 + SHEET_HEADERS.get(item.sheet, ()).index(item.field)
255 + if item.field in SHEET_HEADERS.get(item.sheet, ()) else -1,
256 + item.code, item.message,
257 + )))
258 + counts = dict(sorted(Counter(item.severity for item in ordered).items()))
259 + return PilotPreflightResult(not any(item.severity == "ERROR" for item in ordered), ordered, counts)
backend/tests/test_pilot_workbook.py new
+155
@@ -0,0 +1,155 @@
1 +from __future__ import annotations
2 +
3 +from io import BytesIO
4 +from pathlib import Path
5 +
6 +from openpyxl import Workbook, load_workbook
7 +
8 +from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook
9 +
10 +
11 +def workbook_bytes(rows: dict[str, list[tuple]] | None = None) -> bytes:
12 + workbook = Workbook()
13 + workbook.remove(workbook.active)
14 + for name, headers in SHEET_HEADERS.items():
15 + sheet = workbook.create_sheet(name)
16 + sheet.append(headers)
17 + for row in (rows or {}).get(name, []):
18 + sheet.append(row)
19 + stream = BytesIO()
20 + workbook.save(stream)
21 + return stream.getvalue()
22 +
23 +
24 +def valid_rows() -> dict[str, list[tuple]]:
25 + company = ("001", "آرام", 1405, "IRR", "rial", "tester", "Draft")
26 + account = (
27 + "001", 1405, "10", "کل", None, None, None, None, None, None, None,
28 + None, None, None, "0010", "حساب", 10, 5, 3, 12, 2, "Draft", 0,
29 + )
30 + note = ("001", 1405, "BS", "Assets", "01", "یادداشت", "001", "زیر یادداشت")
31 + mapping = (
32 + "M001", "001", 1405, "0010", "General", "10", None, None, None,
33 + None, None, "BS", "Assets", "01", "001", 1, "Draft", None, None,
34 + "Manual", None, "Pending",
35 + )
36 + return {"Company": [company], "Accounts": [account], "Notes": [note], "Mapping": [mapping]}
37 +
38 +
39 +def issue_codes(data: bytes) -> list[str]:
40 + return [issue.code for issue in preflight_pilot_workbook(data).issues]
41 +
42 +
43 +def test_minimal_valid_workbook_preserves_input_bytes():
44 + data = workbook_bytes(valid_rows())
45 + original = bytes(data)
46 + result = preflight_pilot_workbook(data)
47 + assert result.valid
48 + assert result.issues == ()
49 + assert data == original
50 +
51 +
52 +def test_invalid_workbook_bytes_return_a_typed_error():
53 + result = preflight_pilot_workbook(b"not an xlsx")
54 + assert not result.valid
55 + assert result.issues[0].code == "INVALID_WORKBOOK"
56 +
57 +
58 +def test_committed_blank_template_is_valid():
59 + template = Path(__file__).parents[2] / "samples" / "Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx"
60 + result = preflight_pilot_workbook(template.read_bytes())
61 + assert result.valid, result.issues
62 +
63 +
64 +def test_missing_sheet_and_wrong_header_order_report_exact_location():
65 + data = workbook_bytes()
66 + book = load_workbook(BytesIO(data))
67 + del book["Notes"]
68 + book["Company"].move_range("A1:B1", cols=1)
69 + stream = BytesIO()
70 + book.save(stream)
71 + result = preflight_pilot_workbook(stream.getvalue())
72 + assert ("HEADER_MISMATCH", "Company", 1, "__headers__") in {
73 + (i.code, i.sheet, i.row, i.field) for i in result.issues
74 + }
75 + assert ("MISSING_SHEET", "Notes", 1, "__sheet__") in {
76 + (i.code, i.sheet, i.row, i.field) for i in result.issues
77 + }
78 +
79 +
80 +def test_numeric_code_rejected_and_leading_zero_text_accepted():
81 + rows = valid_rows()
82 + account = list(rows["Accounts"][0])
83 + account[14] = 10
84 + rows["Accounts"] = [tuple(account)]
85 + result = preflight_pilot_workbook(workbook_bytes(rows))
86 + assert ("CODE_NOT_TEXT", "account_full_code") in {(i.code, i.field) for i in result.issues}
87 +
88 + valid = preflight_pilot_workbook(workbook_bytes(valid_rows()))
89 + assert valid.valid
90 +
91 +
92 +def test_required_duplicate_and_cross_reference_errors_are_collected():
93 + rows = valid_rows()
94 + rows["Company"].append(rows["Company"][0])
95 + rows["Accounts"].append(rows["Accounts"][0])
96 + broken_note = list(rows["Notes"][0])
97 + broken_note[0] = "999"
98 + broken_note[5] = None
99 + rows["Notes"] = [tuple(broken_note)]
100 + codes = issue_codes(workbook_bytes(rows))
101 + assert "DUPLICATE_COMPANY_YEAR" in codes
102 + assert "DUPLICATE_ACCOUNT" in codes
103 + assert "UNKNOWN_COMPANY_YEAR" in codes
104 + assert "REQUIRED_FIELD" in codes
105 +
106 +
107 +def test_unknown_account_duplicate_mapping_and_lifecycle_errors():
108 + rows = valid_rows()
109 + mapping = list(rows["Mapping"][0])
110 + mapping[3] = "0099"
111 + mapping[16] = "Published"
112 + rows["Mapping"] = [tuple(mapping), tuple(mapping)]
113 + codes = issue_codes(workbook_bytes(rows))
114 + assert "UNKNOWN_MAPPING_ACCOUNT" in codes
115 + assert "DUPLICATE_MAPPING_ID" in codes
116 + assert "INVALID_LIFECYCLE" in codes
117 +
118 +
119 +def test_non_finite_values_and_non_zero_closing_delta():
120 + rows = valid_rows()
121 + account = list(rows["Accounts"][0])
122 + account[16] = "NaN"
123 + account[19] = 99
124 + rows["Accounts"] = [tuple(account)]
125 + codes = issue_codes(workbook_bytes(rows))
126 + assert "NON_FINITE_FINANCIAL_VALUE" in codes
127 +
128 + rows = valid_rows()
129 + account = list(rows["Accounts"][0])
130 + account[19] = 11
131 + rows["Accounts"] = [tuple(account)]
132 + assert "NON_ZERO_CLOSING_DELTA" in issue_codes(workbook_bytes(rows))
133 +
134 +
135 +def test_positive_integer_fields_and_deterministic_ordering():
136 + rows = valid_rows()
137 + account = list(rows["Accounts"][0])
138 + account[20] = 1.5
139 + rows["Accounts"] = [tuple(account)]
140 + mapping = list(rows["Mapping"][0])
141 + mapping[15] = 0
142 + rows["Mapping"] = [tuple(mapping)]
143 + data = workbook_bytes(rows)
144 + first = preflight_pilot_workbook(data)
145 + second = preflight_pilot_workbook(data)
146 + assert first.issues == second.issues
147 + assert [i.code for i in first.issues].count("INVALID_POSITIVE_INTEGER") == 2
148 + assert first.issue_counts == {"ERROR": len(first.issues)}
149 +
150 +
151 +def test_validation_does_not_persist_any_artifact(tmp_path, monkeypatch):
152 + monkeypatch.chdir(tmp_path)
153 + before = set(tmp_path.iterdir())
154 + preflight_pilot_workbook(workbook_bytes(valid_rows()))
155 + assert set(tmp_path.iterdir()) == before
docs/PILOT_WORKBOOK_CONTRACT.md new
+66
@@ -0,0 +1,66 @@
1 +# V1 Pilot Workbook Contract v0.1
2 +
3 +This contract governs the blank Pilot input and mapping workbook. The approved
4 +artifact is `samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx`; it is not
5 +canonical financial data and contains no sample financial values.
6 +
7 +## Sheets and exact header order
8 +
9 +| Sheet | Exact headers |
10 +|---|---|
11 +| Company | `company_code`, `company_name`, `fiscal_year`, `currency`, `unit`, `prepared_by`, `status` |
12 +| Accounts | `company_code`, `fiscal_year`, `general_code`, `general_name`, `subsidiary_code`, `subsidiary_name`, `detail1_code`, `detail1_name`, `detail2_code`, `detail2_name`, `detail3_code`, `detail3_name`, `detail4_code`, `detail4_name`, `account_full_code`, `account_name`, `opening`, `debit`, `credit`, `closing`, `source_row`, `row_status`, `closing_delta` |
13 +| Notes | `company_code`, `fiscal_year`, `statement`, `statement_section`, `note_number`, `note_title`, `subnote_code`, `subnote_title` |
14 +| Mapping | `mapping_id`, `company_code`, `fiscal_year`, `account_full_code`, `account_level`, `general_code`, `subsidiary_code`, `detail1_code`, `detail2_code`, `detail3_code`, `detail4_code`, `target_statement`, `statement_section`, `note_number`, `subnote_code`, `mapping_version`, `approval_status`, `reviewer`, `review_date`, `source`, `notes`, `validation_status` |
15 +| Test_Log | `tester`, `feature`, `expected_result`, `actual_result`, `status`, `severity`, `evidence`, `notes` |
16 +| Checks | `check_code`, `check_name`, `status`, `affected_rows`, `details` |
17 +| Guide_FA | `section`, `instruction` |
18 +| Lists | `list_name`, `value` |
19 +
20 +Every sheet and the exact order above is mandatory. Entirely blank data rows are
21 +ignored. In a populated row, fields required by the validator are:
22 +
23 +- Company: `company_code`, `company_name`, `fiscal_year`, `status`.
24 +- Accounts: company/year, general code/name, full code/name, four financial
25 + source values, `source_row`, and `row_status`.
26 +- Notes: company/year, statement, note number, and note title.
27 +- Mapping: mapping ID, company/year, account code/level, positive mapping
28 + version, and approval status.
29 +
30 +Other fields are optional in v0.1. Fiscal years, mapping versions, and source
31 +rows are positive integers. Financial source fields are finite decimal values;
32 +NaN, Infinity, booleans, and formulas are invalid. Every code field is Excel
33 +text. Numeric code cells are rejected rather than coerced, preserving leading
34 +zeros.
35 +
36 +## Lifecycle and relationships
37 +
38 +- Company status: `Draft`, `Approved`, `Locked`.
39 +- Accounts row status and Mapping approval status: `Draft`, `Reviewed`,
40 + `Approved`. Preflight validates but never advances a status.
41 +- `(company_code, fiscal_year)` is unique in Company. Accounts, Notes, and
42 + Mapping must reference it exactly; no cross-company or cross-year fallback is
43 + allowed.
44 +- `(company_code, fiscal_year, account_full_code)` is unique in Accounts.
45 +- `mapping_id` is globally unique in the workbook. Each mapping account must
46 + exist in Accounts for the same company and year. Unknown accounts are errors;
47 + mappings are never guessed.
48 +
49 +## Validation report
50 +
51 +The in-memory API returns `valid`, deterministic `issues`, and counts by
52 +severity. Every issue has `severity`, `code`, `sheet`, one-based Excel `row`,
53 +`field`, and `message`. It collects all detectable structural and row-level
54 +errors rather than stopping at the first.
55 +
56 +`closing_delta` means only `opening + debit - credit - closing`. A non-zero
57 +result is a validation error. It is not a financial-statement calculation, does
58 +not replace any source value, and is never persisted.
59 +
60 +## Safety boundary and artifact hash
61 +
62 +Preflight reads supplied bytes in memory. It does not write workbook bytes,
63 +parsed rows, financial values, mappings, or validation reports; it never guesses
64 +or mutates values. The template generator reads no canonical file.
65 +
66 +Committed template SHA-256: `e14a7feb80a216d79ed9cb6dde2b0df3e55317f3da6b26efc77f7118f4702b6f`.
docs/PROJECT_LOG.md
+30
@@ -156,3 +156,33 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
156 - Remaining risk: PR #13 must be independently reviewed before its documentation becomes accepted
157 - Next action: review PR #13, then select the next focused Issue #11 roadmap task
158
159 +### 2026-08-24T09:29:00Z — Gate 2A implementation candidate prepared
160 +
161 +- Actor: ChatGPT/Codex implementation
162 +- Task/phase: Issue #14, Pilot workbook contract and read-only preflight
163 +- Base: `source-data-cleanup@7c7533ee87146dc8fc78b46ebf423be55532c7eb`
164 +- Working branch: `codex/gate-2a-pilot-workbook`
165 +- Scope: typed in-memory preflight, reproducible blank workbook generator,
166 + approved blank template, contract, regression tests, and control records
167 +- Local focused verification: 9 targeted preflight scenarios passed through a
168 + direct Python harness; compileall succeeded
169 +- Full pytest/Alembic: pending GitHub Backend CI because the automation runtime
170 + could not install the repository test dependencies from the external package
171 + index
172 +- Template SHA-256:
173 + `e14a7feb80a216d79ed9cb6dde2b0df3e55317f3da6b26efc77f7118f4702b6f`
174 +- Protected data: no canonical XLSX/PDF, `data/`, database, financial-source,
175 + migration, workflow, ZIP, EXE, desktop, or release file changed
176 +- Acceptance: `IN_PROGRESS`; Draft and unmerged
177 +- Remaining risks: full Backend CI and independent diff review are required
178 +- Recovery: close the Draft PR without merge; accepted branch remains unchanged
179 +
180 +### 2026-08-24T09:40:00Z — Gate 2A Draft PR and CI verified
181 +
182 +- Draft PR: [#15](https://github.com/davoodmehraban89/Aram/pull/15)
183 +- Published head: `8b0431b54392e3c19ae995e2b38bdf08a56a0473`
184 +- Changed files: 9, all within the Issue #14 allowlist
185 +- GitHub Actions: [Backend CI run #23](https://github.com/davoodmehraban89/Aram/actions/runs/32712716962), `success`
186 +- Test evidence: 52 passed, 1 warning; Alembic upgrade/downgrade and compileall succeeded
187 +- PR state: Draft, open, mergeable, and unmerged
188 +- Acceptance: `IN_PROGRESS`; independent diff review and explicit merge decision remain required
docs/handoff/LATEST_HANDOFF.md
+38 -67
@@ -1,73 +1,44 @@
1 # Aram — Latest Handoff Prompt
2
3 > Current authoritative handoff snapshot: 2026-08-24 UTC
4 -> This file supersedes every earlier handoff prompt. Verify every statement against GitHub before acting.
4 +> Verify every statement against GitHub before acting.
5
6 ----
7 -
8 -## COPY FROM HERE
9 -
10 -Use the permanent instructions in `docs/handoff/MASTER_RECOVERY_PROMPT.md`, then
11 -verify this snapshot against the private repository `davoodmehraban89/Aram`.
12 -Do not ask Davood to reconstruct project history from memory.
13 -
14 -### Accepted repository state
6 +## Accepted repository state
7
8 - Canonical branch: `source-data-cleanup`
17 -- Accepted head after Phase 2B:
18 - `7b5bd79b760d534dad34b3162f770e838616ebe9`
19 -- Phase 1B-1: merged through PR #1.
20 -- Phase 1B-2 corrections: merged through PR #4.
21 -- Phase 2A backend foundation: merged through PR #6.
22 -- One-file model refactor: merged through PR #8.
23 -- Project-control foundation: merged through PR #10.
24 -- Phase 2B ingestion foundation: independently reviewed and squash-merged
25 - through PR #12 on 2026-08-24.
26 -- No user-ready V1 release has been accepted or proven.
27 -
28 -### Accepted Phase 2B evidence
29 -
30 -- PR: https://github.com/davoodmehraban89/Aram/pull/12
31 -- Reviewed PR head: `f7cb6abb7caf3f1c0c28d402ae41b0e3c005a280`
32 -- Squash merge commit:
33 - `7b5bd79b760d534dad34b3162f770e838616ebe9`
34 -- Final PR CI: https://github.com/davoodmehraban89/Aram/actions/runs/32705724028
35 -- CI conclusion: `success`; 42 tests passed, Alembic upgrade/downgrade
36 - succeeded, and compileall succeeded.
37 -- Accepted capabilities: metadata-only source registration, exact-duplicate
38 - idempotency, semantic-conflict rejection, read-only XLSX structural
39 - inspection, and typed in-memory general-ledger parsing.
40 -- Protected boundary: no canonical XLSX/PDF, `data/`, database, ZIP, EXE,
41 - binary, or financial-source file changed in PR #12.
42 -
43 -### Superseded work
44 -
45 -- PR #9: https://github.com/davoodmehraban89/Aram/pull/9
46 -- State: CLOSED WITHOUT MERGE on 2026-08-24.
47 -- PR #9 must not be reopened or merged; its Phase 2B role was replaced by
48 - accepted PR #12.
49 -- PR #7 remains closed and unmerged. Recover any useful feature only through a
50 - separately approved, focused PR.
51 -
52 -### Remaining product boundary
53 -
54 -- Comprehensive Mapping Excel import/export is not implemented.
55 -- Note and sub-note mapping workflow and UI are not implemented.
56 -- Official `v1.0.0-pilot` release and clean-environment artifacts are not proven.
57 -- GitHub Issue #11 remains the V1 Pilot roadmap:
58 - https://github.com/davoodmehraban89/Aram/issues/11
59 -
60 -### Single next action
61 -
62 -Review and merge documentation-only PR #13 (https://github.com/davoodmehraban89/Aram/pull/13), which records
63 -the accepted PR #12 merge and PR #9 closure. After that, verify Issue #11 and
64 -select the next small, controlled implementation task. Do not begin work from
65 -an old Jules task or cached branch.
66 -
67 -### Mandatory first response
68 -
69 -Report whether GitHub access succeeded. Verify the canonical branch head,
70 -PR #12 merge state, PR #9 closure state, the current documentation-control PR,
71 -and CI evidence. Do not start implementation until this comparison is complete.
72 -
73 -## END COPY
9 +- Accepted head: `7c7533ee87146dc8fc78b46ebf423be55532c7eb`
10 +- Phase 1B-1, Phase 1B-2, Phase 2A, project controls, and Phase 2B are accepted.
11 +- PR #12 is squash-merged; PR #9 and PR #7 are closed without merge.
12 +- PR #13 is squash-merged and records the Phase 2B acceptance state.
13 +- No user-ready V1 release or EXE is accepted or proven.
14 +
15 +## Active focused candidate
16 +
17 +- Roadmap: https://github.com/davoodmehraban89/Aram/issues/11
18 +- Task: https://github.com/davoodmehraban89/Aram/issues/14
19 +- Base: `source-data-cleanup@7c7533ee87146dc8fc78b46ebf423be55532c7eb`
20 +- Branch: `codex/gate-2a-pilot-workbook`
21 +- Draft PR: https://github.com/davoodmehraban89/Aram/pull/15
22 +- Candidate scope: governed blank Pilot workbook v0.1, reproducible generator,
23 + human-readable contract, deterministic read-only preflight, focused tests,
24 + and required project-control updates.
25 +- Template path: `samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx`
26 +- Template SHA-256:
27 + `e14a7feb80a216d79ed9cb6dde2b0df3e55317f3da6b26efc77f7118f4702b6f`
28 +- Local evidence: nine focused validation scenarios and compileall passed.
29 +- Remote evidence: Backend CI run #23 passed with 52 tests and one warning;
30 + Alembic upgrade/downgrade and compileall succeeded:
31 + https://github.com/davoodmehraban89/Aram/actions/runs/32712716962
32 +- Acceptance remains pending independent diff review and an explicit merge decision.
33 +
34 +## Safety boundary
35 +
36 +The candidate must remain a Draft and unmerged. It does not persist workbook
37 +bytes or financial values, execute mappings, calculate statements, modify
38 +canonical XLSX/PDF or `data/`, or create desktop/release/ZIP/EXE artifacts.
39 +
40 +## Single next action
41 +
42 +Fetch Draft PR #15 and its exact head, review all changed files against the
43 +base, and verify the final head CI. Correct only failures caused by Issue #14.
44 +Do not start Gate 3 and do not merge without a separate acceptance decision.
samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx
Binary files /dev/null and b/samples/Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx differ