Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 20:45 UTC
feat(backend): accept Phase 2B ingestion foundation (#12)
Add metadata-only source registration, semantic-conflict safeguards, read-only XLSX inspection, typed general-ledger parsing, regression tests, and current project-control documentation.
davoodmehraban89 committed
Aug 24, 2026 at 12:02 UTC
7b5bd79b760d534dad34b3162f770e838616ebe9
11 files changed
+853
-93
PROJECT_STATUS.md
+8
-7
@@ -6,7 +6,7 @@
6
7
- Repository: [davoodmehraban89/Aram](https://github.com/davoodmehraban89/Aram)
8
- Accepted branch: `source-data-cleanup`
9
-- Accepted baseline commit: [`5122fd052ebe0ffe0e07dbb8153a872a4f047355`](https://github.com/davoodmehraban89/Aram/commit/5122fd052ebe0ffe0e07dbb8153a872a4f047355)
9
+- Accepted baseline commit: [`a41b07d7a7dd192c3ae4a277eb4903327883456f`](https://github.com/davoodmehraban89/Aram/commit/a41b07d7a7dd192c3ae4a277eb4903327883456f)
10
- Product objective: a controlled, auditable accounting and financial-statement workflow that preserves canonical source data.
11
12
## Status vocabulary
@@ -28,8 +28,9 @@
28
| Phase 1B-1 source inventory | `VERIFIED_AND_MERGED` | [PR #1](https://github.com/davoodmehraban89/Aram/pull/1) |
29
| Phase 1B-2 audit corrections | `VERIFIED_AND_MERGED` | [PR #4](https://github.com/davoodmehraban89/Aram/pull/4) |
30
| Phase 2A backend foundation | `VERIFIED_AND_MERGED` | [PR #6](https://github.com/davoodmehraban89/Aram/pull/6) |
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) |
32
-| Phase 2B ingestion foundation | `IN_PROGRESS` | Draft [PR #9](https://github.com/davoodmehraban89/Aram/pull/9); not merged |
33
+| Phase 2B ingestion foundation | `IN_PROGRESS` | Draft [PR #12](https://github.com/davoodmehraban89/Aram/pull/12) replacement candidate (PR #9 superseded) |
34
| Parallel V1 prototype | `VERIFIED_BUT_UNMERGED` | Closed, unmerged [PR #7](https://github.com/davoodmehraban89/Aram/pull/7); reference/recovery source only |
35
| PR #7 test/release claims | `CLAIMED_BUT_NOT_PROVEN` | No independent acceptance evidence recorded |
36
| Official V1 release | `NOT_IMPLEMENTED` | No accepted user-ready release |
@@ -42,16 +43,16 @@ The accepted branch does not include PR #7's `desktop/`, `dist/`, ZIP/EXE, or V1
43
44
- Agent reports have previously diverged from the remote repository.
45
- PR #7 is large, unmerged, and cannot be accepted as a single unit.
45
-- PR #9 is draft work and must not be treated as accepted.
46
+- PR #12 is the current replacement candidate; PR #9 is superseded but open.
47
- Binary execution on a clean Windows environment has not been independently proven.
48
- Mapping, notes, and sub-notes are incomplete for V1.
49
50
## Next approved action
51
51
-1. Review and merge this documentation-control PR only after confirming its nine-file documentation and handoff scope.
52
-2. Independently review PR #9 and accept, correct, or close it.
53
-3. Audit PR #7 feature-by-feature; recover useful work through small PRs only.
54
-4. Build the mandatory Mapping Excel and note/sub-note workflow before V1 acceptance.
52
+Independently review Draft PR #12 at its current remote head. Verify the complete
53
+11-file diff, successful Backend CI, regression coverage, and protected-data
54
+boundaries. Then explicitly accept it, request changes, or reject it. Do not merge
55
+PR #9 while PR #12 is the active replacement candidate.
56
57
## Control documents
58
backend/README.md
+19
@@ -29,3 +29,22 @@ pytest
29
Tests use an isolated temporary SQLite database with foreign-key enforcement.
30
Runtime SQLite files are ignored by Git.
31
32
+## Phase 2B: Source registration and inspection
33
+
34
+Phase 2B adds metadata-only registration plus read-only inspection of supported
35
+source documents.
36
+
37
+- Supported file suffixes: `.xlsx` and `.csv`.
38
+- Supported document types: `financial_statement`, `general_ledger`,
39
+ `mapping`, and `trial_balance`.
40
+- Registration stores the fiscal year, safe filename, document type, and SHA-256
41
+ content hash. It does not persist source payload bytes.
42
+- An exact duplicate—same fiscal year, content hash, safe filename, and document
43
+ type—is idempotent and returns the existing `SourceDocument`.
44
+- Reusing the same fiscal year and content hash with a different safe filename,
45
+ document type, or both raises `SourceRegistrationError`. The existing record
46
+ remains unchanged and no second record is created.
47
+- XLSX structural inspection is read-only. General-ledger rows are parsed as
48
+ typed in-memory records without changing the workbook.
49
+- Phase 2B does not persist financial values, execute mappings, calculate
50
+ balances, or modify canonical source files.
backend/pyproject.toml
+1
@@ -13,6 +13,7 @@ dependencies = [
13
"pydantic-settings>=2.7,<3",
14
"sqlalchemy>=2.0,<3",
15
"uvicorn[standard]>=0.34,<1",
16
+ "openpyxl>=3.1,<4",
17
]
18
19
[project.optional-dependencies]
backend/src/aram_backend/ingestion.py
new
+78
@@ -0,0 +1,78 @@
1
+from __future__ import annotations
2
+
3
+import hashlib
4
+from pathlib import Path
5
+
6
+from sqlalchemy import select
7
+from sqlalchemy.orm import Session
8
+
9
+from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument
10
+
11
+
12
+ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
13
+ALLOWED_DOCUMENT_TYPES = frozenset(
14
+ {"financial_statement", "general_ledger", "mapping", "trial_balance"}
15
+)
16
+
17
+
18
+class SourceRegistrationError(ValueError):
19
+ """Raised when source metadata cannot be registered safely."""
20
+
21
+
22
+def register_source_document(
23
+ session: Session,
24
+ *,
25
+ year_id: int,
26
+ filename: str,
27
+ document_type: str,
28
+ content: bytes,
29
+) -> SourceDocument:
30
+ """Register immutable source metadata without persisting source bytes.
31
+
32
+ Re-registering the same bytes for the same fiscal year is idempotent. The
33
+ caller owns the transaction and may inspect the returned row before commit.
34
+ """
35
+
36
+ if not filename or "/" in filename or "\\" in filename:
37
+ raise SourceRegistrationError("filename must not contain a path")
38
+ safe_name = Path(filename).name
39
+ if Path(safe_name).suffix.lower() not in ALLOWED_SOURCE_SUFFIXES:
40
+ raise SourceRegistrationError("only .csv and .xlsx source files are supported")
41
+ if document_type not in ALLOWED_DOCUMENT_TYPES:
42
+ raise SourceRegistrationError("unsupported source document type")
43
+ if not content:
44
+ raise SourceRegistrationError("source file must not be empty")
45
+
46
+ year = session.get(FiscalYear, year_id)
47
+ if year is None:
48
+ raise SourceRegistrationError(f"fiscal year {year_id} does not exist")
49
+ if year.status is not FiscalYearStatus.DRAFT:
50
+ raise SourceRegistrationError(
51
+ f"fiscal year {year_id} is {year.status.value.lower()} and cannot accept sources"
52
+ )
53
+
54
+ file_hash = hashlib.sha256(content).hexdigest()
55
+ existing = session.scalar(
56
+ select(SourceDocument).where(
57
+ SourceDocument.year_id == year_id,
58
+ SourceDocument.file_hash == file_hash,
59
+ )
60
+ )
61
+ if existing is not None:
62
+ if existing.document_type != document_type and existing.filename != safe_name:
63
+ raise SourceRegistrationError(f"document type and filename mismatch for existing content hash")
64
+ if existing.document_type != document_type:
65
+ raise SourceRegistrationError(f"document type mismatch for existing content hash")
66
+ if existing.filename != safe_name:
67
+ raise SourceRegistrationError(f"filename mismatch for existing content hash")
68
+ return existing
69
+
70
+ source = SourceDocument(
71
+ year_id=year_id,
72
+ filename=safe_name,
73
+ file_hash=file_hash,
74
+ document_type=document_type,
75
+ )
76
+ session.add(source)
77
+ session.flush()
78
+ return source
backend/src/aram_backend/ledger_parser.py
new
+150
@@ -0,0 +1,150 @@
1
+from __future__ import annotations
2
+
3
+from collections.abc import Iterator
4
+from dataclasses import dataclass
5
+from decimal import Decimal, InvalidOperation
6
+from io import BytesIO
7
+
8
+from openpyxl import load_workbook
9
+
10
+from aram_backend.workbook_inspection import inspect_xlsx
11
+
12
+
13
+@dataclass(frozen=True)
14
+class LedgerRecord:
15
+ row_number: int
16
+ account_code: str
17
+ account_name: str
18
+ source_year: int
19
+ entry_type: str
20
+ t1_code: str | None
21
+ t2_code: str | None
22
+ t3_code: str | None
23
+ t4_code: str | None
24
+ opening: Decimal
25
+ debit: Decimal
26
+ credit: Decimal
27
+ closing: Decimal
28
+
29
+
30
+class LedgerParseError(ValueError):
31
+ """Raised when a source ledger row cannot be represented safely."""
32
+
33
+
34
+_FIELDS = {
35
+ "account_code": "حساب",
36
+ "account_name": "ACCOUNT_NAME",
37
+ "source_year": "year",
38
+ "entry_type": "نوع",
39
+ "t1_code": "T1_CODE",
40
+ "t2_code": "T2_CODE",
41
+ "t3_code": "T3_CODE",
42
+ "t4_code": "T4_CODE",
43
+ "opening": "OPENING",
44
+ "debit": "Debit",
45
+ "credit": "Credit",
46
+ "closing": "CLOSING",
47
+}
48
+
49
+
50
+def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
51
+ """Stream typed ledger rows without persisting or calculating values."""
52
+
53
+ inspection = inspect_xlsx(content, document_type="general_ledger")
54
+ workbook = load_workbook(
55
+ BytesIO(content), read_only=True, data_only=True, keep_links=False
56
+ )
57
+ try:
58
+ worksheet = workbook[inspection.data_sheet]
59
+ header_values = next(
60
+ worksheet.iter_rows(
61
+ min_row=inspection.header_row,
62
+ max_row=inspection.header_row,
63
+ values_only=True,
64
+ )
65
+ )
66
+ indexes = {
67
+ str(value).strip(): index
68
+ for index, value in enumerate(header_values)
69
+ if value is not None
70
+ }
71
+
72
+ for row_number, values in enumerate(
73
+ worksheet.iter_rows(
74
+ min_row=inspection.header_row + 1, values_only=True
75
+ ),
76
+ start=inspection.header_row + 1,
77
+ ):
78
+ if not any(value is not None for value in values):
79
+ continue
80
+
81
+ def value(field: str):
82
+ return values[indexes[_FIELDS[field]]]
83
+
84
+ yield LedgerRecord(
85
+ row_number=row_number,
86
+ account_code=_required_code(value("account_code"), row_number, "حساب"),
87
+ account_name=_required_text(
88
+ value("account_name"), row_number, "ACCOUNT_NAME"
89
+ ),
90
+ source_year=_required_year(value("source_year"), row_number),
91
+ entry_type=_required_text(value("entry_type"), row_number, "نوع"),
92
+ t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
93
+ t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
94
+ t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
95
+ t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
96
+ opening=_required_decimal(value("opening"), row_number, "OPENING"),
97
+ debit=_required_decimal(value("debit"), row_number, "Debit"),
98
+ credit=_required_decimal(value("credit"), row_number, "Credit"),
99
+ closing=_required_decimal(value("closing"), row_number, "CLOSING"),
100
+ )
101
+ finally:
102
+ workbook.close()
103
+
104
+
105
+def _required_text(value: object, row_number: int, field: str) -> str:
106
+ text = str(value).strip() if value is not None else ""
107
+ if not text:
108
+ raise LedgerParseError(f"row {row_number}: {field} is required")
109
+ return text
110
+
111
+
112
+def _required_year(value: object, row_number: int) -> int:
113
+ parsed = _required_decimal(value, row_number, "year")
114
+ if parsed != parsed.to_integral_value() or parsed <= 0:
115
+ raise LedgerParseError(f"row {row_number}: year must be a positive integer")
116
+ return int(parsed)
117
+
118
+
119
+def _required_code(value: object, row_number: int, field: str) -> str:
120
+ code = _optional_code(value, row_number, field)
121
+ if code is None:
122
+ raise LedgerParseError(f"row {row_number}: {field} is required")
123
+ return code
124
+
125
+
126
+def _optional_code(value: object, row_number: int, field: str) -> str | None:
127
+ if value is None:
128
+ return None
129
+ if isinstance(value, bool):
130
+ raise LedgerParseError(f"row {row_number}: {field} is not a valid code")
131
+ if isinstance(value, str):
132
+ code = value.strip()
133
+ return code or None
134
+ parsed = _required_decimal(value, row_number, field)
135
+ if parsed != parsed.to_integral_value():
136
+ raise LedgerParseError(f"row {row_number}: {field} must be an integer code")
137
+ return str(int(parsed))
138
+
139
+
140
+def _required_decimal(value: object, row_number: int, field: str) -> Decimal:
141
+ if value is None or isinstance(value, bool):
142
+ raise LedgerParseError(f"row {row_number}: {field} is required and numeric")
143
+ candidate = str(value).strip().replace(",", "").replace("٬", "")
144
+ try:
145
+ parsed = Decimal(candidate)
146
+ except (InvalidOperation, ValueError) as exc:
147
+ raise LedgerParseError(f"row {row_number}: {field} is not numeric") from exc
148
+ if not parsed.is_finite():
149
+ raise LedgerParseError(f"row {row_number}: {field} must be finite")
150
+ return parsed
backend/src/aram_backend/workbook_inspection.py
new
+136
@@ -0,0 +1,136 @@
1
+from __future__ import annotations
2
+
3
+from dataclasses import dataclass
4
+from io import BytesIO
5
+from zipfile import BadZipFile
6
+
7
+from openpyxl import load_workbook
8
+from openpyxl.utils.exceptions import InvalidFileException
9
+
10
+
11
+MAX_WORKSHEETS = 100
12
+MAX_HEADER_COLUMNS = 256
13
+
14
+
15
+@dataclass(frozen=True)
16
+class WorkbookInspection:
17
+ document_type: str
18
+ sheet_names: tuple[str, ...]
19
+ data_sheet: str | None
20
+ header_row: int | None
21
+ headers: tuple[str, ...]
22
+
23
+
24
+class WorkbookInspectionError(ValueError):
25
+ """Raised when an XLSX source does not match an accepted source profile."""
26
+
27
+
28
+_TABULAR_PROFILES = {
29
+ "general_ledger": {
30
+ "sheet": "Source",
31
+ "header_row": 2,
32
+ "required_headers": frozenset(
33
+ {
34
+ "حساب",
35
+ "ACCOUNT_NAME",
36
+ "year",
37
+ "نوع",
38
+ "T1_CODE",
39
+ "T2_CODE",
40
+ "T3_CODE",
41
+ "T4_CODE",
42
+ "OPENING",
43
+ "Debit",
44
+ "Credit",
45
+ "CLOSING",
46
+ }
47
+ ),
48
+ },
49
+ "mapping": {
50
+ "sheet": "Data",
51
+ "header_row": 1,
52
+ "required_headers": frozenset(
53
+ {
54
+ "کد حساب",
55
+ "نوع",
56
+ "کد یادداشت",
57
+ "شرح یادداشت",
58
+ "فرمول یادداشت اصلی",
59
+ "فرمول یادداشت فرعی",
60
+ }
61
+ ),
62
+ },
63
+}
64
+
65
+_PRIMARY_STATEMENT_SHEETS = frozenset(
66
+ {"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"}
67
+)
68
+
69
+
70
+def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
71
+ """Validate workbook structure without importing rows or evaluating formulas."""
72
+
73
+ if not content:
74
+ raise WorkbookInspectionError("workbook must not be empty")
75
+ if document_type not in {*_TABULAR_PROFILES, "financial_statement"}:
76
+ raise WorkbookInspectionError("document type has no XLSX inspection profile")
77
+
78
+ try:
79
+ workbook = load_workbook(
80
+ BytesIO(content), read_only=True, data_only=False, keep_links=False
81
+ )
82
+ except (BadZipFile, InvalidFileException, OSError, ValueError) as exc:
83
+ raise WorkbookInspectionError("invalid or unreadable XLSX workbook") from exc
84
+
85
+ try:
86
+ sheet_names = tuple(workbook.sheetnames)
87
+ if len(sheet_names) > MAX_WORKSHEETS:
88
+ raise WorkbookInspectionError("workbook contains too many worksheets")
89
+
90
+ if document_type == "financial_statement":
91
+ missing = _PRIMARY_STATEMENT_SHEETS.difference(sheet_names)
92
+ if missing:
93
+ raise WorkbookInspectionError(
94
+ f"financial statement workbook is missing sheets: {sorted(missing)}"
95
+ )
96
+ return WorkbookInspection(
97
+ document_type=document_type,
98
+ sheet_names=sheet_names,
99
+ data_sheet=None,
100
+ header_row=None,
101
+ headers=(),
102
+ )
103
+
104
+ profile = _TABULAR_PROFILES[document_type]
105
+ sheet_name = profile["sheet"]
106
+ if sheet_name not in workbook:
107
+ raise WorkbookInspectionError(f"required worksheet is missing: {sheet_name}")
108
+
109
+ worksheet = workbook[sheet_name]
110
+ header_row = profile["header_row"]
111
+ values = next(
112
+ worksheet.iter_rows(
113
+ min_row=header_row,
114
+ max_row=header_row,
115
+ max_col=min(worksheet.max_column, MAX_HEADER_COLUMNS),
116
+ values_only=True,
117
+ ),
118
+ (),
119
+ )
120
+ headers = tuple(str(value).strip() for value in values if value is not None)
121
+ if len(headers) != len(set(headers)):
122
+ raise WorkbookInspectionError("header row contains duplicate names")
123
+
124
+ missing = profile["required_headers"].difference(headers)
125
+ if missing:
126
+ raise WorkbookInspectionError(f"required headers are missing: {sorted(missing)}")
127
+
128
+ return WorkbookInspection(
129
+ document_type=document_type,
130
+ sheet_names=sheet_names,
131
+ data_sheet=sheet_name,
132
+ header_row=header_row,
133
+ headers=headers,
134
+ )
135
+ finally:
136
+ workbook.close()
backend/tests/test_ingestion.py
new
+192
@@ -0,0 +1,192 @@
1
+import hashlib
2
+
3
+import pytest
4
+
5
+from aram_backend.ingestion import SourceRegistrationError, register_source_document
6
+from aram_backend.models import Company, FiscalYear, FiscalYearStatus, SourceDocument
7
+
8
+
9
+def make_year(session, year=1404):
10
+ company = Company(code=f"ING-{year}", name="Ingestion Test Company")
11
+ fiscal_year = FiscalYear(company=company, year=year)
12
+ session.add(company)
13
+ session.commit()
14
+ return fiscal_year
15
+
16
+
17
+def test_registers_hash_and_metadata_without_source_payload(session):
18
+ year = make_year(session)
19
+ payload = b"account_code,amount\n1000,125\n"
20
+
21
+ source = register_source_document(
22
+ session,
23
+ year_id=year.id,
24
+ filename="ledger.csv",
25
+ document_type="general_ledger",
26
+ content=payload,
27
+ )
28
+ session.commit()
29
+
30
+ assert source.file_hash == hashlib.sha256(payload).hexdigest()
31
+ assert source.filename == "ledger.csv"
32
+ assert not hasattr(source, "content")
33
+
34
+
35
+def test_registration_is_idempotent_within_a_year(session):
36
+ year = make_year(session)
37
+ arguments = {
38
+ "year_id": year.id,
39
+ "filename": "trial-balance.xlsx",
40
+ "document_type": "trial_balance",
41
+ "content": b"safe-test-bytes",
42
+ }
43
+
44
+ first = register_source_document(session, **arguments)
45
+ session.commit()
46
+ second = register_source_document(session, **arguments)
47
+ session.commit()
48
+
49
+ assert second.id == first.id
50
+ assert session.query(SourceDocument).count() == 1
51
+
52
+
53
+def test_same_source_is_isolated_between_fiscal_years(session):
54
+ first_year = make_year(session, 1403)
55
+ second_year = make_year(session, 1404)
56
+ payload = b"same-source"
57
+
58
+ first = register_source_document(
59
+ session,
60
+ year_id=first_year.id,
61
+ filename="source.csv",
62
+ document_type="general_ledger",
63
+ content=payload,
64
+ )
65
+ second = register_source_document(
66
+ session,
67
+ year_id=second_year.id,
68
+ filename="source.csv",
69
+ document_type="general_ledger",
70
+ content=payload,
71
+ )
72
+ session.commit()
73
+
74
+ assert first.id != second.id
75
+ assert first.file_hash == second.file_hash
76
+
77
+
78
+@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
79
+def test_protected_year_rejects_source_registration(session, status):
80
+ year = make_year(session)
81
+ year.status = FiscalYearStatus.APPROVED
82
+ session.commit()
83
+ if status is FiscalYearStatus.LOCKED:
84
+ year.status = FiscalYearStatus.LOCKED
85
+ session.commit()
86
+
87
+ with pytest.raises(SourceRegistrationError, match="cannot accept sources"):
88
+ register_source_document(
89
+ session,
90
+ year_id=year.id,
91
+ filename="blocked.xlsx",
92
+ document_type="financial_statement",
93
+ content=b"blocked",
94
+ )
95
+
96
+
97
+@pytest.mark.parametrize(
98
+ ("filename", "document_type", "content"),
99
+ [
100
+ ("../ledger.csv", "general_ledger", b"data"),
101
+ ("..\\ledger.csv", "general_ledger", b"data"),
102
+ ("ledger.exe", "general_ledger", b"data"),
103
+ ("ledger.csv", "unknown", b"data"),
104
+ ("ledger.csv", "general_ledger", b""),
105
+ ],
106
+)
107
+def test_rejects_unsafe_or_unsupported_source_metadata(
108
+ session, filename, document_type, content
109
+):
110
+ year = make_year(session)
111
+
112
+ with pytest.raises(SourceRegistrationError):
113
+ register_source_document(
114
+ session,
115
+ year_id=year.id,
116
+ filename=filename,
117
+ document_type=document_type,
118
+ content=content,
119
+ )
120
+
121
+def test_duplicate_registration_different_document_type_rejected(session):
122
+ year = make_year(session)
123
+ arguments = {
124
+ "year_id": year.id,
125
+ "filename": "trial-balance.xlsx",
126
+ "document_type": "trial_balance",
127
+ "content": b"safe-test-bytes-conflict",
128
+ }
129
+
130
+ first = register_source_document(session, **arguments)
131
+ session.commit()
132
+
133
+ conflict_arguments = arguments.copy()
134
+ conflict_arguments["document_type"] = "general_ledger"
135
+
136
+ with pytest.raises(SourceRegistrationError, match="document type mismatch for existing content hash"):
137
+ register_source_document(session, **conflict_arguments)
138
+
139
+ session.rollback()
140
+ assert session.query(SourceDocument).count() == 1
141
+ existing = session.query(SourceDocument).first()
142
+ assert existing.document_type == "trial_balance"
143
+ assert existing.filename == "trial-balance.xlsx"
144
+
145
+def test_duplicate_registration_different_filename_rejected(session):
146
+ year = make_year(session)
147
+ arguments = {
148
+ "year_id": year.id,
149
+ "filename": "trial-balance.xlsx",
150
+ "document_type": "trial_balance",
151
+ "content": b"safe-test-bytes-conflict-2",
152
+ }
153
+
154
+ first = register_source_document(session, **arguments)
155
+ session.commit()
156
+
157
+ conflict_arguments = arguments.copy()
158
+ conflict_arguments["filename"] = "other.xlsx"
159
+
160
+ with pytest.raises(SourceRegistrationError, match="filename mismatch for existing content hash"):
161
+ register_source_document(session, **conflict_arguments)
162
+
163
+ session.rollback()
164
+ assert session.query(SourceDocument).count() == 1
165
+ existing = session.query(SourceDocument).first()
166
+ assert existing.document_type == "trial_balance"
167
+ assert existing.filename == "trial-balance.xlsx"
168
+
169
+def test_duplicate_registration_different_both_rejected(session):
170
+ year = make_year(session)
171
+ arguments = {
172
+ "year_id": year.id,
173
+ "filename": "trial-balance.xlsx",
174
+ "document_type": "trial_balance",
175
+ "content": b"safe-test-bytes-conflict-3",
176
+ }
177
+
178
+ first = register_source_document(session, **arguments)
179
+ session.commit()
180
+
181
+ conflict_arguments = arguments.copy()
182
+ conflict_arguments["document_type"] = "general_ledger"
183
+ conflict_arguments["filename"] = "other.xlsx"
184
+
185
+ with pytest.raises(SourceRegistrationError, match="document type and filename mismatch for existing content hash"):
186
+ register_source_document(session, **conflict_arguments)
187
+
188
+ session.rollback()
189
+ assert session.query(SourceDocument).count() == 1
190
+ existing = session.query(SourceDocument).first()
191
+ assert existing.document_type == "trial_balance"
192
+ assert existing.filename == "trial-balance.xlsx"
backend/tests/test_ledger_parser.py
new
+90
@@ -0,0 +1,90 @@
1
+from decimal import Decimal
2
+from io import BytesIO
3
+
4
+import pytest
5
+from openpyxl import Workbook
6
+
7
+from aram_backend.ledger_parser import LedgerParseError, parse_general_ledger
8
+
9
+
10
+HEADERS = [
11
+ "حساب",
12
+ "ACCOUNT_NAME",
13
+ "year",
14
+ "نوع",
15
+ "T1_CODE",
16
+ "T2_CODE",
17
+ "T3_CODE",
18
+ "T4_CODE",
19
+ "OPENING",
20
+ "Debit",
21
+ "Credit",
22
+ "CLOSING",
23
+]
24
+
25
+
26
+def ledger_bytes(*rows):
27
+ workbook = Workbook()
28
+ sheet = workbook.active
29
+ sheet.title = "Source"
30
+ sheet.append(["source ledger"])
31
+ sheet.append(HEADERS)
32
+ for row in rows:
33
+ sheet.append(row)
34
+ output = BytesIO()
35
+ workbook.save(output)
36
+ workbook.close()
37
+ return output.getvalue()
38
+
39
+
40
+def valid_row(**overrides):
41
+ values = {
42
+ "حساب": "0001",
43
+ "ACCOUNT_NAME": "Test account",
44
+ "year": "1404",
45
+ "نوع": "O",
46
+ "T1_CODE": None,
47
+ "T2_CODE": None,
48
+ "T3_CODE": None,
49
+ "T4_CODE": None,
50
+ "OPENING": "0",
51
+ "Debit": "0",
52
+ "Credit": "0",
53
+ "CLOSING": "0",
54
+ }
55
+ values.update(overrides)
56
+ return [values[header] for header in HEADERS]
57
+
58
+
59
+def test_streams_typed_records_without_calculation():
60
+ records = list(parse_general_ledger(ledger_bytes(valid_row())))
61
+
62
+ assert len(records) == 1
63
+ assert records[0].row_number == 3
64
+ assert records[0].account_code == "0001"
65
+ assert records[0].opening == Decimal("0")
66
+ assert records[0].closing == Decimal("0")
67
+
68
+
69
+def test_skips_completely_blank_rows():
70
+ records = list(parse_general_ledger(ledger_bytes([None] * len(HEADERS), valid_row())))
71
+
72
+ assert [record.row_number for record in records] == [4]
73
+
74
+
75
+@pytest.mark.parametrize(
76
+ ("field", "invalid", "message"),
77
+ [
78
+ ("Debit", "NaN", "must be finite"),
79
+ ("Credit", "Infinity", "must be finite"),
80
+ ("CLOSING", "not-numeric", "is not numeric"),
81
+ ("ACCOUNT_NAME", None, "is required"),
82
+ ("year", "1404.5", "positive integer"),
83
+ ("T1_CODE", 12.5, "integer code"),
84
+ ],
85
+)
86
+def test_rejects_unsafe_or_incomplete_rows(field, invalid, message):
87
+ content = ledger_bytes(valid_row(**{field: invalid}))
88
+
89
+ with pytest.raises(LedgerParseError, match=message):
90
+ list(parse_general_ledger(content))
backend/tests/test_workbook_inspection.py
new
+91
@@ -0,0 +1,91 @@
1
+from io import BytesIO
2
+
3
+import pytest
4
+from openpyxl import Workbook
5
+
6
+from aram_backend.workbook_inspection import WorkbookInspectionError, inspect_xlsx
7
+
8
+
9
+def workbook_bytes(sheet_rows):
10
+ workbook = Workbook()
11
+ default = workbook.active
12
+ workbook.remove(default)
13
+ for sheet_name, rows in sheet_rows:
14
+ sheet = workbook.create_sheet(sheet_name)
15
+ for row in rows:
16
+ sheet.append(row)
17
+ output = BytesIO()
18
+ workbook.save(output)
19
+ workbook.close()
20
+ return output.getvalue()
21
+
22
+
23
+def test_inspects_accepted_general_ledger_structure():
24
+ headers = [
25
+ "حساب",
26
+ "ACCOUNT_NAME",
27
+ "year",
28
+ "نوع",
29
+ "T1_CODE",
30
+ "T2_CODE",
31
+ "T3_CODE",
32
+ "T4_CODE",
33
+ "OPENING",
34
+ "Debit",
35
+ "Credit",
36
+ "CLOSING",
37
+ ]
38
+ content = workbook_bytes([("Source", [["source ledger"], headers])])
39
+
40
+ result = inspect_xlsx(content, document_type="general_ledger")
41
+
42
+ assert result.data_sheet == "Source"
43
+ assert result.header_row == 2
44
+ assert result.headers == tuple(headers)
45
+
46
+
47
+def test_inspects_accepted_mapping_structure():
48
+ headers = [
49
+ "کد حساب",
50
+ "نوع",
51
+ "کد یادداشت",
52
+ "شرح یادداشت",
53
+ "فرمول یادداشت اصلی",
54
+ "فرمول یادداشت فرعی",
55
+ ]
56
+ content = workbook_bytes([("Data", [headers])])
57
+
58
+ result = inspect_xlsx(content, document_type="mapping")
59
+
60
+ assert result.data_sheet == "Data"
61
+ assert result.header_row == 1
62
+
63
+
64
+def test_inspects_primary_financial_statement_sheet_set():
65
+ names = ["سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"]
66
+ content = workbook_bytes([(name, []) for name in names])
67
+
68
+ result = inspect_xlsx(content, document_type="financial_statement")
69
+
70
+ assert result.sheet_names == tuple(names)
71
+ assert result.headers == ()
72
+
73
+
74
+@pytest.mark.parametrize(
75
+ "content",
76
+ [
77
+ workbook_bytes([("Wrong", [["not the expected sheet"]])]),
78
+ workbook_bytes([("Source", [["source ledger"], ["حساب"]])]),
79
+ b"not-an-xlsx-file",
80
+ ],
81
+)
82
+def test_rejects_invalid_or_mismatched_workbooks(content):
83
+ with pytest.raises(WorkbookInspectionError):
84
+ inspect_xlsx(content, document_type="general_ledger")
85
+
86
+
87
+def test_rejects_document_type_without_an_xlsx_profile():
88
+ content = workbook_bytes([("Sheet", [])])
89
+
90
+ with pytest.raises(WorkbookInspectionError, match="no XLSX inspection profile"):
91
+ inspect_xlsx(content, document_type="trial_balance")
docs/PROJECT_LOG.md
+29
@@ -103,3 +103,32 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
103
- Reviewer: pending independent review
104
- Remaining risk: evidence and diff review incomplete
105
- Next action: review before any acceptance
106
+
107
+### [2026-08-24] Phase 2B Replacement Candidate (PR #12)
108
+- Recorded PR #10 governance merge in PROJECT_STATUS.md.
109
+- Created and recorded PR #12 as the replacement candidate for Phase 2B, superseding PR #9.
110
+- Current active branch: `codex/phase-2b-source-registration-12955190277775369594`
111
+- Base SHA: `a41b07d7a7dd192c3ae4a277eb4903327883456f`
112
+- Verified CI evidence: GitHub Backend CI run #16 successful on PR #12.
113
+- Updated docs to ensure Phase 2B metadata-registration conflict rejection is thoroughly tested and verified.
114
+
115
+### 2026-08-24T08:00:00Z — PR #12 corrective evidence and documentation finalization
116
+
117
+- Actor: Jules implementation; ChatGPT/Codex independent remote verification and documentation correction
118
+- Task/phase: Phase 2B ingestion foundation replacement candidate
119
+- Base: `source-data-cleanup@a41b07d7a7dd192c3ae4a277eb4903327883456f`
120
+- Working branch: `codex/phase-2b-source-registration-12955190277775369594`
121
+- PR: [#12](https://github.com/davoodmehraban89/Aram/pull/12)
122
+- Independently reviewed implementation head: `9e90533658e400a51402db673efae9cbd0aa37d1`
123
+- Changed files at reviewed head: `PROJECT_STATUS.md`, `backend/README.md`, `backend/pyproject.toml`, `backend/src/aram_backend/ingestion.py`, `backend/src/aram_backend/ledger_parser.py`, `backend/src/aram_backend/workbook_inspection.py`, `backend/tests/test_ingestion.py`, `backend/tests/test_ledger_parser.py`, `backend/tests/test_workbook_inspection.py`, `docs/PROJECT_LOG.md`, `docs/handoff/LATEST_HANDOFF.md`
124
+- Regression evidence: exact duplicate remains idempotent; same-year/same-hash conflicts in document type, filename, or both raise `SourceRegistrationError`; each rejection leaves one unchanged original `SourceDocument`
125
+- Reported local verification by Jules: full backend pytest suite, compileall, Alembic upgrade/downgrade round-trip, and `git diff --check` passed; exact pytest count was not independently captured and remains `NOT_VERIFIED`
126
+- GitHub Actions: [Backend CI run #17](https://github.com/davoodmehraban89/Aram/actions/runs/32703999006), `success`
127
+- Artifacts/releases: none
128
+- Protected data: the complete PR filename list contains no canonical XLSX/PDF, `data/`, database, ZIP, EXE, or financial-source file
129
+- Acceptance: `IN_PROGRESS`; Draft and unmerged
130
+- Reviewer: ChatGPT/Codex candidate-requirements review; final acceptance pending
131
+- Remaining risks: final documentation commits require their own CI result; independent acceptance decision is not yet recorded
132
+- Recovery: close PR #12 without merging to leave the accepted branch unchanged
133
+- Next action: independently review the final remote head and record an explicit decision
134
+
docs/handoff/LATEST_HANDOFF.md
+59
-86
@@ -1,106 +1,79 @@
1
# Aram — Latest Handoff Prompt
2
3
-> Current authoritative handoff snapshot created: 2026-08-24 UTC
4
-> This file supersedes every earlier handoff prompt. After each meaningful project step, replace this file with a newer version. Do not use older versions as the continuation baseline.
3
+> Current authoritative handoff snapshot: 2026-08-24 UTC
4
+> This file supersedes every earlier handoff prompt. Verify every statement against GitHub before acting.
5
6
---
7
8
## COPY FROM HERE
9
10
-Use the permanent instructions in `ARAM_MASTER_RECOVERY_PROMPT.md`, then verify this current handoff against the private GitHub repository `davoodmehraban89/Aram`.
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
12
-### Last independently verified repository state
13
-
14
-- Default/canonical branch: `source-data-cleanup`
15
-- Accepted governance merge SHA: `e42d76a24e591a265d3bb6c79ac614ff5b2f211f`
16
-- Governance merge URL: `https://github.com/davoodmehraban89/Aram/commit/e42d76a24e591a265d3bb6c79ac614ff5b2f211f`
17
-- Note: a later documentation-only commit may move the branch head beyond this SHA. Always fetch the current branch head; `e42d76a...` remains the independently verified PR #10 merge evidence.
18
-
19
-### Accepted and merged state
14
+### Accepted repository state
15
16
+- Canonical branch: `source-data-cleanup`
17
+- Approved base used by the active Phase 2B candidate:
18
+ `a41b07d7a7dd192c3ae4a277eb4903327883456f`
19
- Phase 1B-1: merged through PR #1.
20
- Phase 1B-2 corrections: merged through PR #4.
23
-- Phase 2A backend/data-model foundation: merged through PR #6.
21
+- Phase 2A backend foundation: merged through PR #6.
22
- One-file model refactor: merged through PR #8.
25
-- Project-control and durable handoff foundation: merged through PR #10 at `e42d76a24e591a265d3bb6c79ac614ff5b2f211f`.
26
-- No accepted, user-ready V1 release has been proven.
27
-
28
-### Work currently requiring attention
29
-
30
-#### PR #10 — project-control foundation
31
-
32
-- URL: `https://github.com/davoodmehraban89/Aram/pull/10`
33
-- State at last verification: CLOSED AND MERGED
34
-- Merged at: `2026-08-24T06:46:50Z`
35
-- Merge SHA: `e42d76a24e591a265d3bb6c79ac614ff5b2f211f`
36
-- Base: `source-data-cleanup`
37
-- Verified base SHA: `5122fd052ebe0ffe0e07dbb8153a872a4f047355`
38
-- Head branch: `codex/project-control-foundation`
39
-- Final reviewed head SHA: `7650aafd06a913d660704ae80dea260eb3728b04`
40
-- Verified scope: 10 files, 794 additions, and 0 deletions.
41
-- Verified changed files:
42
- - `.github/pull_request_template.md`
43
- - `AGENTS.md`
44
- - `PROJECT_STATUS.md`
45
- - `docs/ACCEPTANCE_POLICY.md`
46
- - `docs/DECISION_LOG.md`
47
- - `docs/JULES_TASK_TEMPLATE.md`
48
- - `docs/PROJECT_LOG.md`
49
- - `docs/handoff/CHATGPT_BOOTSTRAP_PROMPT.txt`
50
- - `docs/handoff/LATEST_HANDOFF.md`
51
- - `docs/handoff/MASTER_RECOVERY_PROMPT.md`
52
-- Verification: no trailing whitespace and no conflict markers were found.
53
-- Scope: documentation, agent instructions, and PR template only.
54
-- No application code, tests, workflows, XLSX, PDF, ZIP, EXE, database, or financial-data file changed.
55
-- GitHub Actions/check status at last verification: no workflow run and no status checks were attached to the head commit.
56
-- Acceptance result: independently reviewed, explicitly authorized by Davood, and squash-merged successfully. The durable controls now exist on the accepted branch.
57
-
58
-The ten-file count supersedes the earlier six-file, seven-file, and nine-file reports. `AGENTS.md` was added after confirming from official Jules documentation that Jules reads repository-level instructions. Two durable handoff files were added so recovery remains possible when ChatGPT history is unavailable. A plain-text `CHATGPT_BOOTSTRAP_PROMPT.txt` was then added as the saveable entry point that guides a successor chat through official GitHub connection and evidence recovery.
59
-
60
-#### PR #9 — Phase 2B ingestion foundation
61
-
62
-- URL: `https://github.com/davoodmehraban89/Aram/pull/9`
63
-- Last known state: OPEN, DRAFT, NOT MERGED
64
-- Original base: `source-data-cleanup@5122fd052ebe0ffe0e07dbb8153a872a4f047355`; it must now be rebased or updated onto the accepted governance baseline.
65
-- Last observed head SHA: `8b141d793ad2d534fdf7399bb79d101d53ae29af`
66
-- Claimed scope: source registration, read-only XLSX preflight, and ledger parsing.
67
-- Independent verification confirmed Backend CI run #14 succeeded with the PR head and the exact eight-file scope.
68
-- An independent review comment requested two changes before acceptance: reject same-hash registrations when filename/document type conflicts with the existing record, and integrate the project-control documents after PR #10 becomes the baseline.
69
-- Review comment ID: `5391629767`.
70
-
71
-#### PR #7 — closed prototype/recovery source
72
-
73
-- URL: `https://github.com/davoodmehraban89/Aram/pull/7`
74
-- State: CLOSED, UNMERGED.
75
-- It contains a large parallel prototype including desktop and branch-level ZIP/EXE work.
76
-- It is not an accepted V1 and must not be merged directly.
77
-- Recover useful features only through small, focused PRs based on the accepted branch.
78
-
79
-### Current product boundary
80
-
81
-- Comprehensive financial-statement Mapping Excel import/export is not complete.
82
-- Note and sub-note mapping workflow is not complete.
83
-- Mapping management UI is not complete.
84
-- Official `v1.0.0-pilot` GitHub Release and independently verified downloadable assets have not been proven.
85
-- Branch-level ZIP/EXE existence does not equal an official or tested release.
86
-- A governed Pilot Excel contract named `Aram_Pilot_Input_and_Mapping_Template_v0.1.xlsx` has been created for user testing and future importer implementation. It contains Company, Accounts, Notes, Mapping, Test_Log, Checks, and data-dictionary sheets. It is a data contract, not proof that the current application can import it yet.
87
-- GitHub Issue #11 is the canonical V1 Pilot roadmap: `https://github.com/davoodmehraban89/Aram/issues/11`.
88
-
89
-### Current operating decision
90
-
91
-- Davood has Google AI Pro and therefore uses Jules in Pro. At the time of this handoff, the published Jules in Pro allowance is 100 tasks per rolling 24 hours and 15 concurrent tasks; this is not expected to constrain the project's controlled, sequential workflow.
92
-- Jules is the primary implementation agent under the repository controls in `AGENTS.md` and the acceptance policy.
93
-- ChatGPT/Codex must independently verify the remote branch, commit, diff, CI, and artifacts after each task.
94
-- GitHub Copilot Cloud Agent is not the planned replacement because it requires a paid Copilot plan and may introduce payment/access risk for Davood in Iran.
95
-- If Jules reports completion that is absent or contradictory in GitHub, reject that task and issue one controlled corrective prompt. Escalate the specific task to direct GitHub/Codex implementation only if the corrective attempt also fails.
96
-- The project must never depend on a single chat session or agent memory.
23
+- Project-control foundation: merged through PR #10.
24
+- No Phase 2B candidate and no user-ready V1 release has been accepted or merged.
25
+
26
+### Active Phase 2B candidate: PR #12
27
+
28
+- URL: https://github.com/davoodmehraban89/Aram/pull/12
29
+- Branch: `codex/phase-2b-source-registration-12955190277775369594`
30
+- Base: `source-data-cleanup@a41b07d7a7dd192c3ae4a277eb4903327883456f`
31
+- State at last verification: OPEN, DRAFT, MERGEABLE, NOT MERGED.
32
+- Independently reviewed implementation head:
33
+ `9e90533658e400a51402db673efae9cbd0aa37d1`
34
+- Scope at that head: 11 files; no canonical XLSX/PDF, `data/`, database,
35
+ ZIP, EXE, or financial-source file.
36
+- Backend CI run #17:
37
+ https://github.com/davoodmehraban89/Aram/actions/runs/32703999006
38
+- Run #17 conclusion: `success`.
39
+- Regression tests cover exact-duplicate idempotency and rejection of same-year,
40
+ same-hash conflicts in filename, document type, or both. Rejected conflicts
41
+ leave one unchanged original `SourceDocument`.
42
+- Backend README documents metadata-only registration, supported types,
43
+ read-only XLSX inspection and ledger parsing, semantic-conflict rejection,
44
+ and the non-persistence of payload bytes and financial values.
45
+- Documentation-control corrections were added after the reviewed implementation
46
+ head; fetch the current PR head and its newest CI before deciding acceptance.
47
+
48
+### Superseded candidate: PR #9
49
+
50
+- URL: https://github.com/davoodmehraban89/Aram/pull/9
51
+- PR #9 is the older Phase 2B candidate.
52
+- Do not merge PR #9 while PR #12 is under review.
53
+- Close or otherwise disposition PR #9 only after PR #12 receives an explicit
54
+ independent acceptance decision.
55
+
56
+### Protected boundaries
57
+
58
+- Do not modify canonical XLSX/PDF files, `data/`, financial source values,
59
+ databases, ZIP/EXE artifacts, mappings, desktop code, or release code as part
60
+ of Phase 2B candidate review.
61
+- PR #7 remains closed and unmerged; recover work from it only through separately
62
+ approved focused tasks.
63
+- Mapping import/export, note/sub-note workflow, UI, and an official tested V1
64
+ release remain incomplete.
65
66
### Single next action
67
100
-Send Jules the focused corrective task for PR #9: fix the same-hash semantic identity collision, add regression tests, rebase or update from the accepted governance baseline, and update `PROJECT_STATUS.md` plus append `docs/PROJECT_LOG.md`. Then independently verify its branch, commit, exact diff, CI, and GitHub evidence. Do not begin the Excel importer until the corrected Phase 2B foundation is accepted.
68
+Independently review the current remote head of Draft PR #12: verify its complete
69
+diff, changed-file list, new Backend CI result, regression behavior, and protected
70
+data boundary. Record an explicit acceptance decision. Do not merge either PR #12
71
+or PR #9 before that decision.
72
73
### Mandatory first response
74
104
-Report whether GitHub access succeeded, then compare this handoff with current GitHub evidence. Do not ask Davood to retell the history and do not start new implementation work before the comparison is complete.
75
+Report whether GitHub access succeeded. Then report the current PR #12 head,
76
+Draft/merge state, exact changed files, and CI evidence compared with this handoff.
77
+Do not start new implementation work until that comparison is complete.
78
79
## END COPY