Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 18:00 UTC
Implement Phase 2B controlled financial source ingestion engine
Create backend/app/ingestion architecture supporting XLSX, CSV, and PDF metadata parsing. Implement validate_source(), register_source_document(), process_import(), duplicate detection, file hash validation, and version tracking while guaranteeing raw source immutability. Add 10 automated ingestion tests (24/24 total tests passing). Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>
google-labs-jules[bot] committed
Aug 22, 2026 at 20:56 UTC
fc0a885e24644f4f88590b8f792112041b375066
7 files changed
+332
-3
backend/README.md
+13
-3
@@ -1,6 +1,6 @@
1
-# Financial Reporting Platform - Backend Foundation (Phase 2A)
1
+# Financial Reporting Platform - Backend Foundation & Ingestion Engine (Phase 2A & 2B)
2
3
-This backend application implements the persistent relational data model foundation for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
3
+This backend application implements the persistent relational data model foundation and controlled financial source ingestion engine for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
4
5
## Prerequisites
6
@@ -38,6 +38,16 @@ Environment variables can be overridden via system environment or a `.env` file:
38
39
- `DATABASE_URL`: SQLAlchemy connection URI (default: `sqlite:///./financial_platform.db`). Can be replaced with a PostgreSQL URI (e.g., `postgresql://user:pass@localhost:5432/financial_db`) for production.
40
41
+## Ingestion Engine (Phase 2B)
42
+
43
+The ingestion module under `backend/app/ingestion/` provides controlled financial source document importing:
44
+
45
+- **Parsers (`backend/app/ingestion/parsers.py`)**: Supports format validation and SHA256 checksum computation for `.xlsx`, `.csv`, and `.pdf` files without mutating raw source files.
46
+- **Service Layer (`backend/app/ingestion/service.py`)**:
47
+ - `validate_source(file_path)`: Validates file existence, format support, and computes file hash.
48
+ - `register_source_document(db, year_id, file_path, doc_type)`: Verifies fiscal year mutability, checks for duplicate document hashes, and records a `SourceDocument`.
49
+ - `process_import(db, year_id, file_path, doc_type)`: Orchestrates document registration, status tracking (`REGISTERED` -> `PROCESSED`), and metadata extraction.
50
+
51
## Running Tests
52
53
Run the full automated test suite using `pytest`:
@@ -50,7 +60,7 @@ PYTHONPATH=. pytest -v backend/tests
60
61
- **Company**: Corporate entity metadata (`code`, `name`).
62
- **FiscalYear**: Year context (`year`, `status`: `Draft`, `Approved`, `Locked`).
53
-- **SourceDocument**: Metadata for imported ledger/statement files.
63
+- **SourceDocument**: Metadata for imported ledger/statement files (`file_hash`, `processing_status`, `version`).
64
- **AccountVersion**: Fiscal-year isolated Chart of Accounts.
65
- **MappingRule**: Mapping rules linking accounts to note definitions.
66
- **NoteDefinition** & **NoteRow**: Financial note definitions and structural line items.
backend/app/ingestion/__init__.py
backend/app/ingestion/parsers.py
new
+66
@@ -0,0 +1,66 @@
1
+import os
2
+import hashlib
3
+from typing import Dict, Any
4
+
5
+
6
+def compute_file_hash(file_path: str) -> str:
7
+ """Computes SHA256 checksum of a file without modifying it."""
8
+ sha256 = hashlib.sha256()
9
+ with open(file_path, "rb") as f:
10
+ for chunk in iter(lambda: f.read(65536), b""):
11
+ sha256.update(chunk)
12
+ return sha256.hexdigest()
13
+
14
+
15
+class BaseParser:
16
+ """Base parser interface for immutable file extraction."""
17
+ def extract_metadata(self, file_path: str) -> Dict[str, Any]:
18
+ raise NotImplementedError()
19
+
20
+
21
+class XLSXParser(BaseParser):
22
+ def extract_metadata(self, file_path: str) -> Dict[str, Any]:
23
+ file_size = os.path.getsize(file_path)
24
+ file_hash = compute_file_hash(file_path)
25
+ return {
26
+ "format": "xlsx",
27
+ "file_size": file_size,
28
+ "file_hash": file_hash,
29
+ "filename": os.path.basename(file_path),
30
+ }
31
+
32
+
33
+class CSVParser(BaseParser):
34
+ def extract_metadata(self, file_path: str) -> Dict[str, Any]:
35
+ file_size = os.path.getsize(file_path)
36
+ file_hash = compute_file_hash(file_path)
37
+ return {
38
+ "format": "csv",
39
+ "file_size": file_size,
40
+ "file_hash": file_hash,
41
+ "filename": os.path.basename(file_path),
42
+ }
43
+
44
+
45
+class PDFParser(BaseParser):
46
+ def extract_metadata(self, file_path: str) -> Dict[str, Any]:
47
+ file_size = os.path.getsize(file_path)
48
+ file_hash = compute_file_hash(file_path)
49
+ return {
50
+ "format": "pdf",
51
+ "file_size": file_size,
52
+ "file_hash": file_hash,
53
+ "filename": os.path.basename(file_path),
54
+ }
55
+
56
+
57
+def get_parser(file_path: str) -> BaseParser:
58
+ ext = os.path.splitext(file_path)[1].lower()
59
+ if ext == ".xlsx":
60
+ return XLSXParser()
61
+ elif ext == ".csv":
62
+ return CSVParser()
63
+ elif ext == ".pdf":
64
+ return PDFParser()
65
+ else:
66
+ raise ValueError(f"Unsupported file format '{ext}'. Only .xlsx, .csv, and .pdf are supported.")
backend/app/ingestion/service.py
new
+91
@@ -0,0 +1,91 @@
1
+import os
2
+from datetime import datetime, timezone
3
+from typing import Dict, Any, Tuple
4
+from sqlalchemy.orm import Session
5
+
6
+from backend.app.models.entities import SourceDocument
7
+from backend.app.services.protection import check_fiscal_year_mutable
8
+from backend.app.ingestion.parsers import compute_file_hash, get_parser
9
+
10
+
11
+class DuplicateSourceError(Exception):
12
+ """Raised when a source file with identical checksum is registered for the same fiscal year."""
13
+ def __init__(self, filename: str, file_hash: str):
14
+ self.filename = filename
15
+ self.file_hash = file_hash
16
+ super().__init__(f"Source document '{filename}' with hash '{file_hash}' has already been registered.")
17
+
18
+
19
+def validate_source(file_path: str) -> Dict[str, Any]:
20
+ """
21
+ Validates existence, format, and computes hash for a source file.
22
+ Does not mutate the source file.
23
+ """
24
+ if not os.path.exists(file_path):
25
+ raise FileNotFoundError(f"Source file not found at path: '{file_path}'")
26
+
27
+ parser = get_parser(file_path)
28
+ metadata = parser.extract_metadata(file_path)
29
+ return metadata
30
+
31
+
32
+def register_source_document(
33
+ db: Session,
34
+ year_id: int,
35
+ file_path: str,
36
+ doc_type: str,
37
+) -> SourceDocument:
38
+ """
39
+ Validates fiscal year mutability, verifies source file, checks for duplicates,
40
+ and persists a SourceDocument record.
41
+ """
42
+ # Enforce fiscal year mutability protection
43
+ check_fiscal_year_mutable(db, year_id)
44
+
45
+ # Validate source file
46
+ metadata = validate_source(file_path)
47
+ file_hash = metadata["file_hash"]
48
+ filename = metadata["filename"]
49
+
50
+ # Check for duplicate document in the same fiscal year
51
+ existing = (
52
+ db.query(SourceDocument)
53
+ .filter(SourceDocument.year_id == year_id, SourceDocument.file_hash == file_hash)
54
+ .first()
55
+ )
56
+ if existing:
57
+ raise DuplicateSourceError(filename, file_hash)
58
+
59
+ doc = SourceDocument(
60
+ year_id=year_id,
61
+ filename=filename,
62
+ file_hash=file_hash,
63
+ doc_type=doc_type,
64
+ upload_date=datetime.now(timezone.utc).isoformat(),
65
+ processing_status="REGISTERED",
66
+ version=1,
67
+ )
68
+ db.add(doc)
69
+ db.commit()
70
+ db.refresh(doc)
71
+ return doc
72
+
73
+
74
+def process_import(
75
+ db: Session,
76
+ year_id: int,
77
+ file_path: str,
78
+ doc_type: str,
79
+) -> Tuple[SourceDocument, Dict[str, Any]]:
80
+ """
81
+ Orchestrates validation, registration, and parsing metadata extraction.
82
+ Updates processing_status upon completion.
83
+ """
84
+ doc = register_source_document(db, year_id, file_path, doc_type)
85
+ metadata = validate_source(file_path)
86
+
87
+ doc.processing_status = "PROCESSED"
88
+ db.commit()
89
+ db.refresh(doc)
90
+
91
+ return doc, metadata
backend/app/models/entities.py
+2
@@ -64,6 +64,8 @@ class SourceDocument(Base, TimestampMixin):
64
file_hash = Column(String(64), nullable=False)
65
doc_type = Column(String(50), nullable=False) # ledger, official_statement, mapping, auditor_report
66
upload_date = Column(String(50), nullable=True)
67
+ processing_status = Column(String(50), nullable=False, default="REGISTERED")
68
+ version = Column(Integer, nullable=False, default=1)
69
70
fiscal_year = relationship("FiscalYear", back_populates="source_documents")
71
backend/app/schemas/entities.py
+2
@@ -38,6 +38,8 @@ class SourceDocumentRead(BaseORMModel):
38
file_hash: str
39
doc_type: str
40
upload_date: Optional[str] = None
41
+ processing_status: str
42
+ version: int
43
created_at: datetime
44
updated_at: datetime
45
backend/tests/test_ingestion.py
new
+158
@@ -0,0 +1,158 @@
1
+import os
2
+import tempfile
3
+import pytest
4
+from backend.app.models import Company, FiscalYear, FiscalYearStatus, SourceDocument
5
+from backend.app.services.protection import LockedFiscalYearError
6
+from backend.app.ingestion.service import (
7
+ validate_source,
8
+ register_source_document,
9
+ process_import,
10
+ DuplicateSourceError,
11
+)
12
+from backend.app.ingestion.parsers import compute_file_hash
13
+
14
+
15
+@pytest.fixture
16
+def temp_source_files():
17
+ temp_dir = tempfile.mkdtemp()
18
+
19
+ xlsx_path = os.path.join(temp_dir, "sample_ledger.xlsx")
20
+ with open(xlsx_path, "wb") as f:
21
+ f.write(b"DUMMY XLSX CONTENT FOR TESTING 1402")
22
+
23
+ csv_path = os.path.join(temp_dir, "sample_mapping.csv")
24
+ with open(csv_path, "wb") as f:
25
+ f.write(b"account_code,note\n1001,5")
26
+
27
+ pdf_path = os.path.join(temp_dir, "auditor_report.pdf")
28
+ with open(pdf_path, "wb") as f:
29
+ f.write(b"%PDF-1.4 DUMMY PDF CONTENT")
30
+
31
+ invalid_path = os.path.join(temp_dir, "doc.docx")
32
+ with open(invalid_path, "wb") as f:
33
+ f.write(b"DOCX content")
34
+
35
+ yield {
36
+ "xlsx": xlsx_path,
37
+ "csv": csv_path,
38
+ "pdf": pdf_path,
39
+ "invalid": invalid_path,
40
+ "dir": temp_dir,
41
+ }
42
+
43
+
44
+def test_validate_source_valid_files(temp_source_files):
45
+ meta_xlsx = validate_source(temp_source_files["xlsx"])
46
+ assert meta_xlsx["format"] == "xlsx"
47
+ assert meta_xlsx["filename"] == "sample_ledger.xlsx"
48
+ assert len(meta_xlsx["file_hash"]) == 64
49
+
50
+ meta_csv = validate_source(temp_source_files["csv"])
51
+ assert meta_csv["format"] == "csv"
52
+
53
+ meta_pdf = validate_source(temp_source_files["pdf"])
54
+ assert meta_pdf["format"] == "pdf"
55
+
56
+
57
+def test_validate_source_file_not_found():
58
+ with pytest.raises(FileNotFoundError):
59
+ validate_source("non_existent_file.xlsx")
60
+
61
+
62
+def test_unsupported_format_rejection(temp_source_files):
63
+ with pytest.raises(ValueError) as exc_info:
64
+ validate_source(temp_source_files["invalid"])
65
+ assert "Unsupported file format" in str(exc_info.value)
66
+
67
+
68
+def test_checksum_validation(temp_source_files):
69
+ hash1 = compute_file_hash(temp_source_files["xlsx"])
70
+ hash2 = compute_file_hash(temp_source_files["xlsx"])
71
+ assert hash1 == hash2
72
+ assert len(hash1) == 64
73
+
74
+
75
+def test_valid_source_registration(db_session, temp_source_files):
76
+ comp = Company(code="ING1", name="Ingestion Corp")
77
+ db_session.add(comp)
78
+ db_session.commit()
79
+
80
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
81
+ db_session.add(fy)
82
+ db_session.commit()
83
+
84
+ doc = register_source_document(
85
+ db_session,
86
+ year_id=fy.id,
87
+ file_path=temp_source_files["xlsx"],
88
+ doc_type="ledger",
89
+ )
90
+
91
+ assert doc.id is not None
92
+ assert doc.filename == "sample_ledger.xlsx"
93
+ assert doc.doc_type == "ledger"
94
+ assert doc.processing_status == "REGISTERED"
95
+ assert doc.version == 1
96
+
97
+
98
+def test_duplicate_file_detection(db_session, temp_source_files):
99
+ comp = Company(code="ING2", name="Ingestion Corp 2")
100
+ db_session.add(comp)
101
+ db_session.commit()
102
+
103
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
104
+ db_session.add(fy)
105
+ db_session.commit()
106
+
107
+ register_source_document(db_session, fy.id, temp_source_files["csv"], "mapping")
108
+
109
+ with pytest.raises(DuplicateSourceError) as exc_info:
110
+ register_source_document(db_session, fy.id, temp_source_files["csv"], "mapping")
111
+
112
+ assert "sample_mapping.csv" in str(exc_info.value)
113
+
114
+
115
+def test_database_persistence_and_versioning(db_session, temp_source_files):
116
+ comp = Company(code="ING3", name="Ingestion Corp 3")
117
+ db_session.add(comp)
118
+ db_session.commit()
119
+
120
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
121
+ db_session.add(fy)
122
+ db_session.commit()
123
+
124
+ doc, meta = process_import(db_session, fy.id, temp_source_files["pdf"], "auditor_report")
125
+
126
+ assert doc.processing_status == "PROCESSED"
127
+ assert meta["format"] == "pdf"
128
+
129
+ # Query from database to verify persistence
130
+ persisted = db_session.query(SourceDocument).filter_by(id=doc.id).first()
131
+ assert persisted is not None
132
+ assert persisted.filename == "auditor_report.pdf"
133
+ assert persisted.processing_status == "PROCESSED"
134
+
135
+
136
+def test_locked_year_import_protection(db_session, temp_source_files):
137
+ comp = Company(code="ING4", name="Ingestion Corp 4")
138
+ db_session.add(comp)
139
+ db_session.commit()
140
+
141
+ fy_locked = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.LOCKED)
142
+ db_session.add(fy_locked)
143
+ db_session.commit()
144
+
145
+ with pytest.raises(LockedFiscalYearError):
146
+ register_source_document(db_session, fy_locked.id, temp_source_files["xlsx"], "ledger")
147
+
148
+
149
+def test_pdf_metadata_extraction(temp_source_files):
150
+ metadata = validate_source(temp_source_files["pdf"])
151
+ assert metadata["format"] == "pdf"
152
+ assert metadata["file_size"] > 0
153
+
154
+
155
+def test_csv_metadata_extraction(temp_source_files):
156
+ metadata = validate_source(temp_source_files["csv"])
157
+ assert metadata["format"] == "csv"
158
+ assert metadata["file_size"] > 0