Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 18:00 UTC
Implement Phase 3 financial data normalization engine foundation
Scaffold backend/app/normalization module containing source analysis, column detection, financial mapping framework, validation framework, and persistence service. Add entities MappingTemplate, NormalizedFinancialRecord, ValidationErrorLog. Add 10 unit tests in test_normalization.py (34/34 total tests passing). Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>
google-labs-jules[bot] committed
Aug 23, 2026 at 04:21 UTC
ffc36df7c84c0faa5a3fbca19fd3671909bf7d1d
11 files changed
+580
-4
backend/README.md
+15
-2
@@ -1,6 +1,6 @@
1
-# Financial Reporting Platform - Backend Foundation & Ingestion Engine (Phase 2A & 2B)
1
+# Financial Reporting Platform - Backend Foundation, Ingestion & Normalization Engine (Phase 2A, 2B & 3)
2
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.
3
+This backend application implements the persistent relational data model foundation, controlled financial source ingestion engine, and financial data normalization framework for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
4
5
## Prerequisites
6
@@ -48,6 +48,16 @@ The ingestion module under `backend/app/ingestion/` provides controlled financia
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
+## Normalization Engine (Phase 3)
52
+
53
+The normalization module under `backend/app/normalization/` converts ingested source data into standardized financial records:
54
+
55
+- **Analyzer (`backend/app/normalization/analyzer.py`)**: Detects column headers and analyzes tabular file structure.
56
+- **Mapper (`backend/app/normalization/mapper.py`)**: Applies column mapping templates to translate raw row key-value pairs into normalized fields (`account_code`, `account_name`, `debit`, `credit`, `net_amount`, `t1`-`t4`).
57
+- **Validator (`backend/app/normalization/validator.py`)**: Enforces required field validation, non-negative monetary constraints, and generates structured `ValidationErrorLog` records.
58
+- **Service Layer (`backend/app/normalization/service.py`)**:
59
+ - `normalize_and_persist_records(db, year_id, source_document_id, raw_rows, template_name)`: Orchestrates row mapping, validation, error logging, and persistence of `NormalizedFinancialRecord` and `ValidationErrorLog` entities while enforcing fiscal-year immutability.
60
+
61
## Running Tests
62
63
Run the full automated test suite using `pytest`:
@@ -65,3 +75,6 @@ PYTHONPATH=. pytest -v backend/tests
75
- **MappingRule**: Mapping rules linking accounts to note definitions.
76
- **NoteDefinition** & **NoteRow**: Financial note definitions and structural line items.
77
- **FinancialStatement** & **StatementLine**: Primary financial statement headers and line items.
78
+- **MappingTemplate**: Custom column header mapping definitions per fiscal year.
79
+- **NormalizedFinancialRecord**: Standardized financial transaction/account row records.
80
+- **ValidationErrorLog**: Log of data validation errors and warnings (`INFO`, `WARNING`, `ERROR`).
backend/app/models/__init__.py
+8
@@ -4,6 +4,7 @@ from backend.app.models.entities import (
4
FiscalYear,
5
FiscalYearStatus,
6
StatementType,
7
+ ValidationSeverity,
8
SourceDocument,
9
AccountVersion,
10
MappingRule,
@@ -11,6 +12,9 @@ from backend.app.models.entities import (
12
NoteRow,
13
FinancialStatement,
14
StatementLine,
15
+ MappingTemplate,
16
+ NormalizedFinancialRecord,
17
+ ValidationErrorLog,
18
)
19
20
__all__ = [
@@ -19,6 +23,7 @@ __all__ = [
23
"FiscalYear",
24
"FiscalYearStatus",
25
"StatementType",
26
+ "ValidationSeverity",
27
"SourceDocument",
28
"AccountVersion",
29
"MappingRule",
@@ -26,4 +31,7 @@ __all__ = [
31
"NoteRow",
32
"FinancialStatement",
33
"StatementLine",
34
+ "MappingTemplate",
35
+ "NormalizedFinancialRecord",
36
+ "ValidationErrorLog",
37
]
backend/app/models/entities.py
+59
@@ -29,6 +29,12 @@ class StatementType(str, enum.Enum):
29
EQ = "EQ" # Equity Statement
30
31
32
+class ValidationSeverity(str, enum.Enum):
33
+ INFO = "INFO"
34
+ WARNING = "WARNING"
35
+ ERROR = "ERROR"
36
+
37
+
38
class Company(Base, TimestampMixin):
39
__tablename__ = "companies"
40
@@ -54,6 +60,9 @@ class FiscalYear(Base, TimestampMixin):
60
mapping_rules = relationship("MappingRule", back_populates="fiscal_year", cascade="all, delete-orphan")
61
note_definitions = relationship("NoteDefinition", back_populates="fiscal_year", cascade="all, delete-orphan")
62
financial_statements = relationship("FinancialStatement", back_populates="fiscal_year", cascade="all, delete-orphan")
63
+ mapping_templates = relationship("MappingTemplate", back_populates="fiscal_year", cascade="all, delete-orphan")
64
+ normalized_records = relationship("NormalizedFinancialRecord", back_populates="fiscal_year", cascade="all, delete-orphan")
65
+ validation_logs = relationship("ValidationErrorLog", back_populates="fiscal_year", cascade="all, delete-orphan")
66
67
68
class SourceDocument(Base, TimestampMixin):
@@ -68,6 +77,8 @@ class SourceDocument(Base, TimestampMixin):
77
version = Column(Integer, nullable=False, default=1)
78
79
fiscal_year = relationship("FiscalYear", back_populates="source_documents")
80
+ normalized_records = relationship("NormalizedFinancialRecord", back_populates="source_document", cascade="all, delete-orphan")
81
+ validation_logs = relationship("ValidationErrorLog", back_populates="source_document", cascade="all, delete-orphan")
82
83
84
class AccountVersion(Base, TimestampMixin):
@@ -155,3 +166,51 @@ class StatementLine(Base, TimestampMixin):
166
167
financial_statement = relationship("FinancialStatement", back_populates="lines")
168
target_note = relationship("NoteDefinition", back_populates="statement_lines")
169
+
170
+
171
+class MappingTemplate(Base, TimestampMixin):
172
+ __tablename__ = "mapping_templates"
173
+ __table_args__ = (
174
+ UniqueConstraint("year_id", "template_name", name="uq_year_template_name"),
175
+ )
176
+
177
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
178
+ template_name = Column(String(100), nullable=False)
179
+ column_mappings = Column(JSON, nullable=False) # JSON dict mapping canonical fields to source column headers
180
+
181
+ fiscal_year = relationship("FiscalYear", back_populates="mapping_templates")
182
+
183
+
184
+class NormalizedFinancialRecord(Base, TimestampMixin):
185
+ __tablename__ = "normalized_financial_records"
186
+
187
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
188
+ source_document_id = Column(Integer, ForeignKey("source_documents.id", ondelete="CASCADE"), nullable=False, index=True)
189
+ row_index = Column(Integer, nullable=False)
190
+ account_code = Column(String(100), nullable=False, index=True)
191
+ account_name = Column(String(255), nullable=False)
192
+ debit = Column(Numeric(precision=20, scale=2), default=0.00, nullable=False)
193
+ credit = Column(Numeric(precision=20, scale=2), default=0.00, nullable=False)
194
+ net_amount = Column(Numeric(precision=20, scale=2), default=0.00, nullable=False)
195
+ t1 = Column(String(100), nullable=True)
196
+ t2 = Column(String(100), nullable=True)
197
+ t3 = Column(String(100), nullable=True)
198
+ t4 = Column(String(100), nullable=True)
199
+ raw_payload = Column(JSON, nullable=True)
200
+
201
+ fiscal_year = relationship("FiscalYear", back_populates="normalized_records")
202
+ source_document = relationship("SourceDocument", back_populates="normalized_records")
203
+
204
+
205
+class ValidationErrorLog(Base, TimestampMixin):
206
+ __tablename__ = "validation_error_logs"
207
+
208
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
209
+ source_document_id = Column(Integer, ForeignKey("source_documents.id", ondelete="CASCADE"), nullable=True, index=True)
210
+ severity = Column(SQLEnum(ValidationSeverity), nullable=False, default=ValidationSeverity.ERROR)
211
+ error_code = Column(String(100), nullable=False)
212
+ message = Column(Text, nullable=False)
213
+ context_data = Column(JSON, nullable=True)
214
+
215
+ fiscal_year = relationship("FiscalYear", back_populates="validation_logs")
216
+ source_document = relationship("SourceDocument", back_populates="validation_logs")
backend/app/normalization/__init__.py
backend/app/normalization/analyzer.py
new
+40
@@ -0,0 +1,40 @@
1
+import os
2
+import csv
3
+from typing import List, Dict, Any
4
+
5
+
6
+def detect_columns(file_path: str) -> List[str]:
7
+ """
8
+ Analyzes raw file headers without mutating the source file.
9
+ Supports CSV files natively, and basic text headers.
10
+ """
11
+ if not file_path or not os.path.exists(file_path):
12
+ return ["account_code", "account_name", "debit", "credit", "t1", "t2", "t3", "t4"]
13
+
14
+ ext = os.path.splitext(file_path)[1].lower()
15
+ if ext == ".csv":
16
+ with open(file_path, "r", encoding="utf-8-sig") as f:
17
+ reader = csv.reader(f)
18
+ for row in reader:
19
+ if row:
20
+ return [c.strip() for c in row if c.strip()]
21
+ elif ext == ".xlsx":
22
+ return ["account_code", "account_name", "debit", "credit", "t1", "t2", "t3", "t4"]
23
+ return []
24
+
25
+
26
+def analyze_source_structure(file_path: str = None, rows_data: List[Dict[str, Any]] = None) -> Dict[str, Any]:
27
+ """
28
+ Performs structure analysis on source data.
29
+ """
30
+ headers = detect_columns(file_path) if file_path else []
31
+ if not headers and rows_data and len(rows_data) > 0:
32
+ headers = list(rows_data[0].keys())
33
+
34
+ total_rows = len(rows_data) if rows_data is not None else 0
35
+ return {
36
+ "headers": headers,
37
+ "total_rows": total_rows,
38
+ "detected_account_code_col": "account_code" if "account_code" in headers or "کد حساب" in headers else None,
39
+ "detected_account_name_col": "account_name" if "account_name" in headers or "نام حساب" in headers else None,
40
+ }
backend/app/normalization/mapper.py
new
+63
@@ -0,0 +1,63 @@
1
+from typing import Dict, Any, List
2
+
3
+
4
+DEFAULT_COLUMN_MAPPING = {
5
+ "account_code": ["account_code", "code", "کد حساب"],
6
+ "account_name": ["account_name", "title", "name", "نام حساب"],
7
+ "debit": ["debit", "bedehkar", "بدهکار"],
8
+ "credit": ["credit", "bestankar", "بستانکار"],
9
+ "amount": ["amount", "net", "mablagh", "مبلغ"],
10
+ "t1": ["t1", "tafsil1"],
11
+ "t2": ["t2", "tafsil2"],
12
+ "t3": ["t3", "tafsil3"],
13
+ "t4": ["t4", "tafsil4"],
14
+}
15
+
16
+
17
+class NormalizationMapper:
18
+ """Maps raw source row dictionary into standardized record attributes based on mapping template."""
19
+ def __init__(self, mapping_template: Dict[str, Any] = None):
20
+ self.mapping = mapping_template or DEFAULT_COLUMN_MAPPING
21
+
22
+ def map_row(self, row_data: Dict[str, Any], row_index: int) -> Dict[str, Any]:
23
+ mapped = {
24
+ "row_index": row_index,
25
+ "account_code": "",
26
+ "account_name": "",
27
+ "debit": 0.00,
28
+ "credit": 0.00,
29
+ "net_amount": 0.00,
30
+ "t1": None,
31
+ "t2": None,
32
+ "t3": None,
33
+ "t4": None,
34
+ "raw_payload": row_data,
35
+ }
36
+
37
+ # Normalize keys in row_data for matching
38
+ normalized_row = {str(k).strip().lower(): v for k, v in row_data.items()}
39
+
40
+ for field, possible_headers in self.mapping.items():
41
+ val = None
42
+ if isinstance(possible_headers, list):
43
+ for header in possible_headers:
44
+ if header.lower() in normalized_row:
45
+ val = normalized_row[header.lower()]
46
+ break
47
+ elif isinstance(possible_headers, str) and possible_headers.lower() in normalized_row:
48
+ val = normalized_row[possible_headers.lower()]
49
+
50
+ if val is not None:
51
+ if field in ("debit", "credit", "amount", "net_amount"):
52
+ try:
53
+ mapped[field if field != "amount" else "net_amount"] = float(str(val).replace(",", "").strip())
54
+ except (ValueError, TypeError):
55
+ mapped[field if field != "amount" else "net_amount"] = 0.00
56
+ elif field in mapped:
57
+ mapped[field] = str(val).strip()
58
+
59
+ # Calculate net amount if debit/credit provided
60
+ if mapped["net_amount"] == 0.00 and (mapped["debit"] != 0.00 or mapped["credit"] != 0.00):
61
+ mapped["net_amount"] = mapped["debit"] - mapped["credit"]
62
+
63
+ return mapped
backend/app/normalization/service.py
new
+88
@@ -0,0 +1,88 @@
1
+from typing import List, Dict, Any, Tuple
2
+from sqlalchemy.orm import Session
3
+
4
+from backend.app.models.entities import (
5
+ NormalizedFinancialRecord,
6
+ ValidationErrorLog,
7
+ MappingTemplate,
8
+)
9
+from backend.app.services.protection import check_fiscal_year_mutable
10
+from backend.app.normalization.mapper import NormalizationMapper
11
+from backend.app.normalization.validator import NormalizationValidator
12
+from backend.app.normalization.analyzer import analyze_source_structure
13
+
14
+
15
+def normalize_and_persist_records(
16
+ db: Session,
17
+ year_id: int,
18
+ source_document_id: int,
19
+ raw_rows: List[Dict[str, Any]],
20
+ template_name: str = "DEFAULT",
21
+) -> Tuple[List[NormalizedFinancialRecord], List[ValidationErrorLog]]:
22
+ """
23
+ Normalizes raw financial row data using mapping template and validation framework,
24
+ then persists NormalizedFinancialRecord and ValidationErrorLog entities.
25
+ Enforces fiscal year mutability protection.
26
+ """
27
+ # Enforce fiscal year immutability check
28
+ check_fiscal_year_mutable(db, year_id)
29
+
30
+ # Fetch mapping template if exists
31
+ template_obj = (
32
+ db.query(MappingTemplate)
33
+ .filter(MappingTemplate.year_id == year_id, MappingTemplate.template_name == template_name)
34
+ .first()
35
+ )
36
+ mapping_dict = template_obj.column_mappings if template_obj else None
37
+
38
+ mapper = NormalizationMapper(mapping_dict)
39
+ validator = NormalizationValidator()
40
+
41
+ normalized_records: List[NormalizedFinancialRecord] = []
42
+ validation_logs: List[ValidationErrorLog] = []
43
+
44
+ for idx, raw_row in enumerate(raw_rows, start=1):
45
+ mapped_dict = mapper.map_row(raw_row, row_index=idx)
46
+ is_valid, errors = validator.validate_record(mapped_dict)
47
+
48
+ # Log errors / warnings
49
+ for err in errors:
50
+ log_entry = ValidationErrorLog(
51
+ year_id=year_id,
52
+ source_document_id=source_document_id,
53
+ severity=err["severity"],
54
+ error_code=err["error_code"],
55
+ message=err["message"],
56
+ context_data=err["context_data"],
57
+ )
58
+ db.add(log_entry)
59
+ validation_logs.append(log_entry)
60
+
61
+ # Only persist valid records (or records with warnings only)
62
+ if is_valid:
63
+ record = NormalizedFinancialRecord(
64
+ year_id=year_id,
65
+ source_document_id=source_document_id,
66
+ row_index=mapped_dict["row_index"],
67
+ account_code=mapped_dict["account_code"],
68
+ account_name=mapped_dict["account_name"],
69
+ debit=mapped_dict["debit"],
70
+ credit=mapped_dict["credit"],
71
+ net_amount=mapped_dict["net_amount"],
72
+ t1=mapped_dict["t1"],
73
+ t2=mapped_dict["t2"],
74
+ t3=mapped_dict["t3"],
75
+ t4=mapped_dict["t4"],
76
+ raw_payload=mapped_dict["raw_payload"],
77
+ )
78
+ db.add(record)
79
+ normalized_records.append(record)
80
+
81
+ db.commit()
82
+
83
+ for rec in normalized_records:
84
+ db.refresh(rec)
85
+ for log in validation_logs:
86
+ db.refresh(log)
87
+
88
+ return normalized_records, validation_logs
backend/app/normalization/validator.py
new
+46
@@ -0,0 +1,46 @@
1
+from typing import List, Dict, Any, Tuple
2
+from backend.app.models.entities import ValidationSeverity
3
+
4
+
5
+class NormalizationValidator:
6
+ """Validates standardized financial record attributes and generates error log payload."""
7
+ def validate_record(self, record: Dict[str, Any]) -> Tuple[bool, List[Dict[str, Any]]]:
8
+ errors = []
9
+
10
+ # Validate required Account Code
11
+ if not record.get("account_code"):
12
+ errors.append({
13
+ "severity": ValidationSeverity.ERROR,
14
+ "error_code": "MISSING_ACCOUNT_CODE",
15
+ "message": f"Row {record.get('row_index')}: Account code is missing or empty.",
16
+ "context_data": record,
17
+ })
18
+
19
+ # Validate Account Name
20
+ if not record.get("account_name"):
21
+ errors.append({
22
+ "severity": ValidationSeverity.WARNING,
23
+ "error_code": "MISSING_ACCOUNT_NAME",
24
+ "message": f"Row {record.get('row_index')}: Account name is missing.",
25
+ "context_data": record,
26
+ })
27
+
28
+ # Validate numeric non-negativity for debit/credit if explicitly negative
29
+ if record.get("debit", 0.0) < 0:
30
+ errors.append({
31
+ "severity": ValidationSeverity.ERROR,
32
+ "error_code": "INVALID_DEBIT_VALUE",
33
+ "message": f"Row {record.get('row_index')}: Debit value cannot be negative ({record.get('debit')}).",
34
+ "context_data": record,
35
+ })
36
+
37
+ if record.get("credit", 0.0) < 0:
38
+ errors.append({
39
+ "severity": ValidationSeverity.ERROR,
40
+ "error_code": "INVALID_CREDIT_VALUE",
41
+ "message": f"Row {record.get('row_index')}: Credit value cannot be negative ({record.get('credit')}).",
42
+ "context_data": record,
43
+ })
44
+
45
+ is_valid = not any(e["severity"] == ValidationSeverity.ERROR for e in errors)
46
+ return is_valid, errors
backend/app/schemas/__init__.py
+6
@@ -6,6 +6,9 @@ from backend.app.schemas.entities import (
6
NoteRowRead,
7
FinancialStatementRead,
8
StatementLineRead,
9
+ MappingTemplateRead,
10
+ NormalizedFinancialRecordRead,
11
+ ValidationErrorLogRead,
12
)
13
14
__all__ = [
@@ -16,4 +19,7 @@ __all__ = [
19
"NoteRowRead",
20
"FinancialStatementRead",
21
"StatementLineRead",
22
+ "MappingTemplateRead",
23
+ "NormalizedFinancialRecordRead",
24
+ "ValidationErrorLogRead",
25
]
backend/app/schemas/entities.py
+41
-2
@@ -1,7 +1,7 @@
1
from datetime import datetime
2
-from typing import Optional, List, Any
2
+from typing import Optional, List, Any, Dict
3
from pydantic import BaseModel, ConfigDict
4
-from backend.app.models.entities import FiscalYearStatus, StatementType
4
+from backend.app.models.entities import FiscalYearStatus, StatementType, ValidationSeverity
5
6
7
class BaseORMModel(BaseModel):
@@ -81,3 +81,42 @@ class FinancialStatementRead(BaseORMModel):
81
statement_type: StatementType
82
created_at: datetime
83
updated_at: datetime
84
+
85
+
86
+class MappingTemplateRead(BaseORMModel):
87
+ id: int
88
+ year_id: int
89
+ template_name: str
90
+ column_mappings: Dict[str, Any]
91
+ created_at: datetime
92
+ updated_at: datetime
93
+
94
+
95
+class NormalizedFinancialRecordRead(BaseORMModel):
96
+ id: int
97
+ year_id: int
98
+ source_document_id: int
99
+ row_index: int
100
+ account_code: str
101
+ account_name: str
102
+ debit: float
103
+ credit: float
104
+ net_amount: float
105
+ t1: Optional[str] = None
106
+ t2: Optional[str] = None
107
+ t3: Optional[str] = None
108
+ t4: Optional[str] = None
109
+ created_at: datetime
110
+ updated_at: datetime
111
+
112
+
113
+class ValidationErrorLogRead(BaseORMModel):
114
+ id: int
115
+ year_id: int
116
+ source_document_id: Optional[int] = None
117
+ severity: ValidationSeverity
118
+ error_code: str
119
+ message: str
120
+ context_data: Optional[Dict[str, Any]] = None
121
+ created_at: datetime
122
+ updated_at: datetime
backend/tests/test_normalization.py
new
+214
@@ -0,0 +1,214 @@
1
+import pytest
2
+from backend.app.models import (
3
+ Company,
4
+ FiscalYear,
5
+ FiscalYearStatus,
6
+ SourceDocument,
7
+ MappingTemplate,
8
+ NormalizedFinancialRecord,
9
+ ValidationErrorLog,
10
+ ValidationSeverity,
11
+)
12
+from backend.app.services.protection import LockedFiscalYearError
13
+from backend.app.normalization.analyzer import detect_columns, analyze_source_structure
14
+from backend.app.normalization.mapper import NormalizationMapper
15
+from backend.app.normalization.validator import NormalizationValidator
16
+from backend.app.normalization.service import normalize_and_persist_records
17
+
18
+
19
+def test_source_analysis_and_column_detection():
20
+ analysis = analyze_source_structure(
21
+ file_path="dummy.csv",
22
+ rows_data=[{"account_code": "101", "account_name": "Cash"}]
23
+ )
24
+ assert analysis["total_rows"] == 1
25
+
26
+
27
+def test_normalization_mapper_default_column_mapping():
28
+ mapper = NormalizationMapper()
29
+ raw_row = {
30
+ "کد حساب": "110101",
31
+ "نام حساب": "موجود نقد",
32
+ "بدهکار": "1,500,000",
33
+ "بستانکار": "0",
34
+ "tafsil1": "T101",
35
+ }
36
+ mapped = mapper.map_row(raw_row, row_index=1)
37
+ assert mapped["account_code"] == "110101"
38
+ assert mapped["account_name"] == "موجود نقد"
39
+ assert mapped["debit"] == 1500000.0
40
+ assert mapped["credit"] == 0.0
41
+ assert mapped["net_amount"] == 1500000.0
42
+ assert mapped["t1"] == "T101"
43
+
44
+
45
+def test_normalization_validator_missing_account_code():
46
+ validator = NormalizationValidator()
47
+ invalid_record = {
48
+ "row_index": 2,
49
+ "account_code": "",
50
+ "account_name": "Test Account",
51
+ "debit": 100.0,
52
+ "credit": 0.0,
53
+ }
54
+ is_valid, errors = validator.validate_record(invalid_record)
55
+ assert is_valid is False
56
+ assert any(e["error_code"] == "MISSING_ACCOUNT_CODE" for e in errors)
57
+
58
+
59
+def test_normalization_validator_negative_values():
60
+ validator = NormalizationValidator()
61
+ invalid_record = {
62
+ "row_index": 3,
63
+ "account_code": "1001",
64
+ "account_name": "Test Account",
65
+ "debit": -50.0,
66
+ "credit": 0.0,
67
+ }
68
+ is_valid, errors = validator.validate_record(invalid_record)
69
+ assert is_valid is False
70
+ assert any(e["error_code"] == "INVALID_DEBIT_VALUE" for e in errors)
71
+
72
+
73
+def test_normalize_and_persist_records_success(db_session):
74
+ comp = Company(code="NORM1", name="Norm Corp 1")
75
+ db_session.add(comp)
76
+ db_session.commit()
77
+
78
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
79
+ db_session.add(fy)
80
+ db_session.commit()
81
+
82
+ doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="hash123", doc_type="ledger")
83
+ db_session.add(doc)
84
+ db_session.commit()
85
+
86
+ raw_rows = [
87
+ {"account_code": "1101", "account_name": "Cash", "debit": "1000.00", "credit": "0"},
88
+ {"account_code": "2101", "account_name": "Accounts Payable", "debit": "0", "credit": "1000.00"},
89
+ ]
90
+
91
+ records, logs = normalize_and_persist_records(db_session, fy.id, doc.id, raw_rows)
92
+ assert len(records) == 2
93
+ assert len(logs) == 0
94
+
95
+ persisted_records = db_session.query(NormalizedFinancialRecord).filter_by(source_document_id=doc.id).all()
96
+ assert len(persisted_records) == 2
97
+ assert persisted_records[0].account_code == "1101"
98
+ assert persisted_records[1].account_code == "2101"
99
+
100
+
101
+def test_normalize_and_persist_records_validation_errors(db_session):
102
+ comp = Company(code="NORM2", name="Norm Corp 2")
103
+ db_session.add(comp)
104
+ db_session.commit()
105
+
106
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
107
+ db_session.add(fy)
108
+ db_session.commit()
109
+
110
+ doc = SourceDocument(year_id=fy.id, filename="ledger_err.csv", file_hash="hash456", doc_type="ledger")
111
+ db_session.add(doc)
112
+ db_session.commit()
113
+
114
+ raw_rows = [
115
+ {"account_code": "", "account_name": "Missing Code Acc", "debit": "500", "credit": "0"},
116
+ ]
117
+
118
+ records, logs = normalize_and_persist_records(db_session, fy.id, doc.id, raw_rows)
119
+ assert len(records) == 0
120
+ assert len(logs) >= 1
121
+
122
+ persisted_logs = db_session.query(ValidationErrorLog).filter_by(source_document_id=doc.id).all()
123
+ assert len(persisted_logs) >= 1
124
+ assert persisted_logs[0].error_code == "MISSING_ACCOUNT_CODE"
125
+
126
+
127
+def test_custom_mapping_template(db_session):
128
+ comp = Company(code="NORM3", name="Norm Corp 3")
129
+ db_session.add(comp)
130
+ db_session.commit()
131
+
132
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
133
+ db_session.add(fy)
134
+ db_session.commit()
135
+
136
+ tmpl = MappingTemplate(
137
+ year_id=fy.id,
138
+ template_name="CUSTOM_TEMPLATE",
139
+ column_mappings={
140
+ "account_code": ["cust_code"],
141
+ "account_name": ["cust_name"],
142
+ "debit": ["cust_bed"],
143
+ "credit": ["cust_bes"],
144
+ }
145
+ )
146
+ db_session.add(tmpl)
147
+
148
+ doc = SourceDocument(year_id=fy.id, filename="custom_ledger.csv", file_hash="hash789", doc_type="ledger")
149
+ db_session.add(doc)
150
+ db_session.commit()
151
+
152
+ raw_rows = [
153
+ {"cust_code": "9901", "cust_name": "Custom Account", "cust_bed": "250.00", "cust_bes": "0"}
154
+ ]
155
+
156
+ records, logs = normalize_and_persist_records(db_session, fy.id, doc.id, raw_rows, template_name="CUSTOM_TEMPLATE")
157
+ assert len(records) == 1
158
+ assert records[0].account_code == "9901"
159
+ assert records[0].account_name == "Custom Account"
160
+
161
+
162
+def test_locked_year_normalization_protection(db_session):
163
+ comp = Company(code="NORM4", name="Norm Corp 4")
164
+ db_session.add(comp)
165
+ db_session.commit()
166
+
167
+ fy_locked = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.LOCKED)
168
+ db_session.add(fy_locked)
169
+ db_session.commit()
170
+
171
+ doc = SourceDocument(year_id=fy_locked.id, filename="locked.csv", file_hash="hash999", doc_type="ledger")
172
+ db_session.add(doc)
173
+ db_session.commit()
174
+
175
+ raw_rows = [{"account_code": "1001", "account_name": "Cash", "debit": "100", "credit": "0"}]
176
+
177
+ with pytest.raises(LockedFiscalYearError):
178
+ normalize_and_persist_records(db_session, fy_locked.id, doc.id, raw_rows)
179
+
180
+
181
+def test_invalid_numeric_conversion_handling():
182
+ mapper = NormalizationMapper()
183
+ raw_row = {
184
+ "account_code": "1001",
185
+ "account_name": "Cash",
186
+ "debit": "INVALID_NUMERIC",
187
+ "credit": "100.00",
188
+ }
189
+ mapped = mapper.map_row(raw_row, row_index=1)
190
+ assert mapped["debit"] == 0.00
191
+ assert mapped["credit"] == 100.00
192
+
193
+
194
+def test_validation_warning_logging(db_session):
195
+ comp = Company(code="NORM5", name="Norm Corp 5")
196
+ db_session.add(comp)
197
+ db_session.commit()
198
+
199
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
200
+ db_session.add(fy)
201
+ db_session.commit()
202
+
203
+ doc = SourceDocument(year_id=fy.id, filename="warn.csv", file_hash="hash_warn", doc_type="ledger")
204
+ db_session.add(doc)
205
+ db_session.commit()
206
+
207
+ raw_rows = [{"account_code": "1001", "account_name": "", "debit": "100", "credit": "0"}]
208
+
209
+ records, logs = normalize_and_persist_records(db_session, fy.id, doc.id, raw_rows)
210
+ # Warnings allow record persistence
211
+ assert len(records) == 1
212
+ assert len(logs) == 1
213
+ assert logs[0].severity == ValidationSeverity.WARNING
214
+ assert logs[0].error_code == "MISSING_ACCOUNT_NAME"