1
+import pytest
2
+from backend.app.models import (
3
+ Company,
4
+ FiscalYear,
5
+ FiscalYearStatus,
6
+ StatementType,
7
+ AccountHierarchyLevel,
8
+ NormalizedFinancialRecord,
9
+ SourceDocument,
10
+ COAMappingRule,
11
+)
12
+from backend.app.normalization.mapping_engine import COAMappingEngine
13
+from backend.app.ingestion.ledger_validator import classify_account_hierarchy, validate_excel_ledger_structure
14
+
15
+
16
+def test_account_hierarchy_classification():
17
+ assert classify_account_hierarchy("11") == AccountHierarchyLevel.GENERAL_LEDGER
18
+ assert classify_account_hierarchy("1101") == AccountHierarchyLevel.SUBSIDIARY_LEDGER
19
+ assert classify_account_hierarchy("110101") == AccountHierarchyLevel.DETAIL_1
20
+ assert classify_account_hierarchy("11010101") == AccountHierarchyLevel.DETAIL_2
21
+
22
+
23
+def test_unmapped_account_detection(db_session):
24
+ comp = Company(code="COA_1", name="COA Corp 1")
25
+ db_session.add(comp)
26
+ db_session.commit()
27
+
28
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
29
+ db_session.add(fy)
30
+ db_session.commit()
31
+
32
+ doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="h_coa1", doc_type="ledger")
33
+ db_session.add(doc)
34
+ db_session.commit()
35
+
36
+ rec = NormalizedFinancialRecord(
37
+ year_id=fy.id,
38
+ source_document_id=doc.id,
39
+ row_index=1,
40
+ account_code="110101",
41
+ account_name="Cash Account Detail",
42
+ debit=100.0,
43
+ credit=0.0,
44
+ net_amount=100.0,
45
+ )
46
+ db_session.add(rec)
47
+ db_session.commit()
48
+
49
+ engine = COAMappingEngine(db_session, fy.id)
50
+ unmapped = engine.detect_unmapped_accounts()
51
+
52
+ assert len(unmapped) == 1
53
+ assert unmapped[0]["account_code"] == "110101"
54
+
55
+
56
+def test_save_coa_mapping_rule(db_session):
57
+ comp = Company(code="COA_2", name="COA Corp 2")
58
+ db_session.add(comp)
59
+ db_session.commit()
60
+
61
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
62
+ db_session.add(fy)
63
+ db_session.commit()
64
+
65
+ engine = COAMappingEngine(db_session, fy.id)
66
+ rule = engine.save_mapping_rule(
67
+ account_code="110101",
68
+ account_name="Cash Detail",
69
+ target_statement=StatementType.BS,
70
+ statement_section="Current Assets",
71
+ group_name="Cash and Cash Equivalents",
72
+ is_approved=True,
73
+ )
74
+
75
+ assert rule.id is not None
76
+ assert rule.is_approved is True
77
+
78
+ # Confirm unmapped account list is now empty
79
+ unmapped = engine.detect_unmapped_accounts()
80
+ assert len(unmapped) == 0
81
+
82
+
83
+def test_template_reuse_across_fiscal_years(db_session):
84
+ comp = Company(code="COA_3", name="COA Corp 3")
85
+ db_session.add(comp)
86
+ db_session.commit()
87
+
88
+ fy1402 = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
89
+ fy1403 = FiscalYear(company_id=comp.id, year=1403, status=FiscalYearStatus.DRAFT)
90
+ db_session.add_all([fy1402, fy1403])
91
+ db_session.commit()
92
+
93
+ engine1402 = COAMappingEngine(db_session, fy1402.id)
94
+ engine1402.save_mapping_rule(
95
+ account_code="1101",
96
+ account_name="Cash",
97
+ target_statement=StatementType.BS,
98
+ statement_section="Current Assets",
99
+ group_name="Cash",
100
+ is_approved=True,
101
+ )
102
+
103
+ engine1403 = COAMappingEngine(db_session, fy1403.id)
104
+ copied = engine1403.copy_template_from_year(fy1402.id)
105
+
106
+ assert copied == 1
107
+ rules1403 = db_session.query(COAMappingRule).filter_by(year_id=fy1403.id).all()
108
+ assert len(rules1403) == 1
109
+ assert rules1403[0].account_code == "1101"
110
+
111
+
112
+def test_company_isolation_in_coa_mapping(db_session):
113
+ comp1 = Company(code="COA_C1", name="COA Corp C1")
114
+ comp2 = Company(code="COA_C2", name="COA Corp C2")
115
+ db_session.add_all([comp1, comp2])
116
+ db_session.commit()
117
+
118
+ fy1 = FiscalYear(company_id=comp1.id, year=1402, status=FiscalYearStatus.DRAFT)
119
+ fy2 = FiscalYear(company_id=comp2.id, year=1402, status=FiscalYearStatus.DRAFT)
120
+ db_session.add_all([fy1, fy2])
121
+ db_session.commit()
122
+
123
+ engine1 = COAMappingEngine(db_session, fy1.id)
124
+ engine1.save_mapping_rule("1101", "Cash", StatementType.BS, "Assets", "Cash", True)
125
+
126
+ rules_c2 = db_session.query(COAMappingRule).filter_by(year_id=fy2.id).all()
127
+ assert len(rules_c2) == 0
128
+
129
+
130
+def test_fiscal_year_isolation_in_coa_mapping(db_session):
131
+ comp = Company(code="COA_ISO", name="COA Iso Corp")
132
+ db_session.add(comp)
133
+ db_session.commit()
134
+
135
+ fy1402 = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
136
+ fy1403 = FiscalYear(company_id=comp.id, year=1403, status=FiscalYearStatus.DRAFT)
137
+ db_session.add_all([fy1402, fy1403])
138
+ db_session.commit()
139
+
140
+ engine1402 = COAMappingEngine(db_session, fy1402.id)
141
+ engine1402.save_mapping_rule("1101", "Cash 1402", StatementType.BS, "Assets", "Cash", True)
142
+
143
+ rules_1403 = db_session.query(COAMappingRule).filter_by(year_id=fy1403.id).all()
144
+ assert len(rules_1403) == 0
145
+
146
+
147
+def test_api_unmapped_accounts_endpoint(client, db_session):
148
+ comp = Company(code="API_UNMAP", name="API Unmap Corp")
149
+ db_session.add(comp)
150
+ db_session.commit()
151
+
152
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
153
+ db_session.add(fy)
154
+ db_session.commit()
155
+
156
+ res = client.get(f"/api/v1/coa/unmapped?year_id={fy.id}")
157
+ assert res.status_code == 200
158
+ assert isinstance(res.json(), list)
159
+
160
+
161
+def test_api_save_coa_mapping_rule_endpoint(client, db_session):
162
+ comp = Company(code="API_RULE", name="API Rule Corp")
163
+ db_session.add(comp)
164
+ db_session.commit()
165
+
166
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
167
+ db_session.add(fy)
168
+ db_session.commit()
169
+
170
+ rule_payload = {
171
+ "account_code": "1101",
172
+ "account_name": "Cash",
173
+ "target_statement": "BS",
174
+ "statement_section": "Current Assets",
175
+ "group_name": "Cash Equivalents",
176
+ "is_approved": True,
177
+ }
178
+
179
+ res = client.post(f"/api/v1/coa/rules?year_id={fy.id}", json=rule_payload)
180
+ assert res.status_code == 200
181
+ assert res.json()["account_code"] == "1101"
182
+
183
+
184
+def test_api_copy_template_endpoint(client, db_session):
185
+ comp = Company(code="API_COPY", name="API Copy Corp")
186
+ db_session.add(comp)
187
+ db_session.commit()
188
+
189
+ fy1402 = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
190
+ fy1403 = FiscalYear(company_id=comp.id, year=1403, status=FiscalYearStatus.DRAFT)
191
+ db_session.add_all([fy1402, fy1403])
192
+ db_session.commit()
193
+
194
+ res = client.post(f"/api/v1/coa/copy-template?year_id={fy1403.id}&source_year_id={fy1402.id}")
195
+ assert res.status_code == 200
196
+ assert res.json()["copied_rules_count"] == 0
197
+
198
+
199
+def test_validate_excel_ledger_structure_valid_csv(tmp_path):
200
+ csv_file = tmp_path / "valid_ledger.csv"
201
+ csv_file.write_text("account_code,account_name,debit,credit\n1101,Cash,100,0")
202
+
203
+ result = validate_excel_ledger_structure(str(csv_file))
204
+ assert result["has_valid_headers"] is True
205
+ assert result["format"] == "csv"
206
+
207
+
208
+def test_validate_excel_ledger_structure_not_found():
209
+ with pytest.raises(FileNotFoundError):
210
+ validate_excel_ledger_structure("non_existent_ledger.csv")
211
+
212
+
213
+def test_validate_excel_ledger_structure_unsupported_format(tmp_path):
214
+ invalid_file = tmp_path / "invalid.docx"
215
+ invalid_file.write_text("dummy docx")
216
+
217
+ with pytest.raises(ValueError):
218
+ validate_excel_ledger_structure(str(invalid_file))
219
+
220
+
221
+def test_detail_level_hierarchy_classification():
222
+ assert classify_account_hierarchy("1101010101") == AccountHierarchyLevel.DETAIL_3
223
+ assert classify_account_hierarchy("110101010101") == AccountHierarchyLevel.DETAIL_4
224
+
225
+
226
+def test_unmapped_account_suggestion_generation(db_session):
227
+ comp = Company(code="SUGG_1", name="Suggestion Corp")
228
+ db_session.add(comp)
229
+ db_session.commit()
230
+
231
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
232
+ db_session.add(fy)
233
+ db_session.commit()
234
+
235
+ doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="h_sugg", doc_type="ledger")
236
+ db_session.add(doc)
237
+ db_session.commit()
238
+
239
+ rec = NormalizedFinancialRecord(
240
+ year_id=fy.id,
241
+ source_document_id=doc.id,
242
+ row_index=1,
243
+ account_code="2101",
244
+ account_name="Property Plant Equipment",
245
+ debit=500.0,
246
+ credit=0.0,
247
+ net_amount=500.0,
248
+ )
249
+ db_session.add(rec)
250
+ db_session.commit()
251
+
252
+ engine = COAMappingEngine(db_session, fy.id)
253
+ unmapped = engine.detect_unmapped_accounts()
254
+
255
+ assert len(unmapped) == 1
256
+ assert "Property" in unmapped[0]["suggested_statement"]
257
+
258
+
259
+def test_coa_mapping_rule_update_existing(db_session):
260
+ comp = Company(code="UPDATE_COA", name="Update COA Corp")
261
+ db_session.add(comp)
262
+ db_session.commit()
263
+
264
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
265
+ db_session.add(fy)
266
+ db_session.commit()
267
+
268
+ engine = COAMappingEngine(db_session, fy.id)
269
+ engine.save_mapping_rule("1101", "Old Name", StatementType.BS, "Current Assets", "Cash", False)
270
+ updated = engine.save_mapping_rule("1101", "Updated Cash Name", StatementType.BS, "Current Assets", "Cash Equivalents", True)
271
+
272
+ assert updated.account_name == "Updated Cash Name"
273
+ assert updated.is_approved is True