Implement Phase 4B financial statement review and snapshot layer
Add StatementSnapshot entity and ReviewStatus Enum (DRAFT, UNDER_REVIEW, APPROVED, REJECTED). Implement backend/app/accounting/snapshot.py with create_statement_snapshot(), get_snapshots_for_year(), and update_snapshot_review_status() maintaining fiscal year isolation and locked-year protection. Add 10 unit tests in test_snapshots.py (54/54 total tests passing). Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>
google-labs-jules[bot] committed
Aug 23, 2026 at 06:28 UTC
c9a5d05a73c7e00458e298713fbc1fe29721212b
7 files changed
+356
-4
backend/README.md
+13
-2
@@ -1,6 +1,6 @@
1
-# Financial Reporting Platform - Backend Architecture (Phase 2A - Phase 4A)
1
+# Financial Reporting Platform - Backend Architecture (Phase 2A - Phase 4B)
2
3
-This backend application implements the persistent relational data model, source document ingestion, financial data normalization, and accounting rule engine foundation for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
3
+This backend application implements the persistent relational data model, source document ingestion, financial data normalization, accounting rule engine, and statement review snapshot layer for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
4
5
## Prerequisites
6
@@ -63,6 +63,16 @@ The accounting module under `backend/app/accounting/` performs rule-based calcul
63
- **Statements (`backend/app/accounting/statements.py`)**: Foundation generators for Trial Balance (TB), Balance Sheet (BS), and Income Statement (IS).
64
- **Service (`backend/app/accounting/service.py`)**: `generate_financial_statements()`.
65
66
+## Review & Snapshot Layer (Phase 4B)
67
+
68
+The snapshot module under `backend/app/accounting/snapshot.py` supports review workflows and versioned statement calculation snapshots:
69
+
70
+- **Entity (`StatementSnapshot`)**: Stores frozen calculation JSON (`snapshot_data`), version number, notes, and review status (`ReviewStatus`: `DRAFT`, `UNDER_REVIEW`, `APPROVED`, `REJECTED`).
71
+- **Service Layer (`backend/app/accounting/snapshot.py`)**:
72
+ - `create_statement_snapshot(db, year_id, notes, created_by, rule_config)`: Generates statements, auto-increments version number for the fiscal year, and persists snapshot.
73
+ - `get_snapshots_for_year(db, year_id)`: Retrieves snapshots ordered by version descending.
74
+ - `update_snapshot_review_status(db, snapshot_id, new_status, notes)`: Manages review status transitions while enforcing fiscal year status immutability.
75
+
76
## Running Tests
77
78
Run the full automated test suite using `pytest`:
@@ -83,3 +93,4 @@ PYTHONPATH=. pytest -v backend/tests
93
- **MappingTemplate**: Custom column header mapping definitions.
94
- **NormalizedFinancialRecord**: Standardized financial transaction/account row records.
95
- **ValidationErrorLog**: Log of data validation errors and warnings.
96
+- **StatementSnapshot**: Versioned financial calculation snapshot and review entity.
backend/app/accounting/snapshot.py
new
+83
@@ -0,0 +1,83 @@
1
+from typing import List, Optional, Dict, Any
2
+from sqlalchemy.orm import Session
3
+from sqlalchemy import func
4
+
5
+from backend.app.models.entities import StatementSnapshot, ReviewStatus
6
+from backend.app.services.protection import check_fiscal_year_mutable
7
+from backend.app.accounting.service import generate_financial_statements
8
+from backend.app.accounting.rules import AccountingRuleConfig
9
+
10
+
11
+def create_statement_snapshot(
12
+ db: Session,
13
+ year_id: int,
14
+ notes: Optional[str] = None,
15
+ created_by: Optional[str] = None,
16
+ rule_config: Optional[AccountingRuleConfig] = None,
17
+) -> StatementSnapshot:
18
+ """
19
+ Generates financial statement calculations from normalized records,
20
+ determines next version number for year_id, and persists a StatementSnapshot.
21
+ Enforces fiscal year mutability protection.
22
+ """
23
+ check_fiscal_year_mutable(db, year_id)
24
+
25
+ # Compute latest version number for year_id
26
+ max_ver = (
27
+ db.query(func.max(StatementSnapshot.version))
28
+ .filter(StatementSnapshot.year_id == year_id)
29
+ .scalar()
30
+ )
31
+ next_ver = (max_ver or 0) + 1
32
+
33
+ # Generate frozen financial calculation snapshot data
34
+ calc_data = generate_financial_statements(db, year_id, rule_config)
35
+
36
+ snapshot = StatementSnapshot(
37
+ year_id=year_id,
38
+ version=next_ver,
39
+ status=ReviewStatus.DRAFT,
40
+ snapshot_data=calc_data,
41
+ created_by=created_by,
42
+ notes=notes,
43
+ )
44
+
45
+ db.add(snapshot)
46
+ db.commit()
47
+ db.refresh(snapshot)
48
+ return snapshot
49
+
50
+
51
+def get_snapshots_for_year(db: Session, year_id: int) -> List[StatementSnapshot]:
52
+ """Retrieves all statement snapshots for a given fiscal year ordered by version desc."""
53
+ return (
54
+ db.query(StatementSnapshot)
55
+ .filter(StatementSnapshot.year_id == year_id)
56
+ .order_by(StatementSnapshot.version.desc())
57
+ .all()
58
+ )
59
+
60
+
61
+def update_snapshot_review_status(
62
+ db: Session,
63
+ snapshot_id: int,
64
+ new_status: ReviewStatus,
65
+ notes: Optional[str] = None,
66
+) -> StatementSnapshot:
67
+ """
68
+ Updates review status (DRAFT, UNDER_REVIEW, APPROVED, REJECTED) for a snapshot.
69
+ Enforces fiscal year mutability protection.
70
+ """
71
+ snapshot = db.query(StatementSnapshot).filter(StatementSnapshot.id == snapshot_id).first()
72
+ if not snapshot:
73
+ raise ValueError(f"StatementSnapshot with id {snapshot_id} not found.")
74
+
75
+ check_fiscal_year_mutable(db, snapshot.year_id)
76
+
77
+ snapshot.status = new_status
78
+ if notes:
79
+ snapshot.notes = f"{snapshot.notes or ''}\n[Status Change to {new_status.value}]: {notes}".strip()
80
+
81
+ db.commit()
82
+ db.refresh(snapshot)
83
+ return snapshot
backend/app/models/__init__.py
+4
@@ -5,6 +5,7 @@ from backend.app.models.entities import (
5
FiscalYearStatus,
6
StatementType,
7
ValidationSeverity,
8
+ ReviewStatus,
9
SourceDocument,
10
AccountVersion,
11
MappingRule,
@@ -15,6 +16,7 @@ from backend.app.models.entities import (
16
MappingTemplate,
17
NormalizedFinancialRecord,
18
ValidationErrorLog,
19
+ StatementSnapshot,
20
)
21
22
__all__ = [
@@ -24,6 +26,7 @@ __all__ = [
26
"FiscalYearStatus",
27
"StatementType",
28
"ValidationSeverity",
29
+ "ReviewStatus",
30
"SourceDocument",
31
"AccountVersion",
32
"MappingRule",
@@ -34,4 +37,5 @@ __all__ = [
37
"MappingTemplate",
38
"NormalizedFinancialRecord",
39
"ValidationErrorLog",
40
+ "StatementSnapshot",
41
]
backend/app/models/entities.py
+25
-1
@@ -35,6 +35,13 @@ class ValidationSeverity(str, enum.Enum):
35
ERROR = "ERROR"
36
37
38
+class ReviewStatus(str, enum.Enum):
39
+ DRAFT = "DRAFT"
40
+ UNDER_REVIEW = "UNDER_REVIEW"
41
+ APPROVED = "APPROVED"
42
+ REJECTED = "REJECTED"
43
+
44
+
45
class Company(Base, TimestampMixin):
46
__tablename__ = "companies"
47
@@ -63,6 +70,7 @@ class FiscalYear(Base, TimestampMixin):
70
mapping_templates = relationship("MappingTemplate", back_populates="fiscal_year", cascade="all, delete-orphan")
71
normalized_records = relationship("NormalizedFinancialRecord", back_populates="fiscal_year", cascade="all, delete-orphan")
72
validation_logs = relationship("ValidationErrorLog", back_populates="fiscal_year", cascade="all, delete-orphan")
73
+ statement_snapshots = relationship("StatementSnapshot", back_populates="fiscal_year", cascade="all, delete-orphan")
74
75
76
class SourceDocument(Base, TimestampMixin):
@@ -176,7 +184,7 @@ class MappingTemplate(Base, TimestampMixin):
184
185
year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
186
template_name = Column(String(100), nullable=False)
179
- column_mappings = Column(JSON, nullable=False) # JSON dict mapping canonical fields to source column headers
187
+ column_mappings = Column(JSON, nullable=False)
188
189
fiscal_year = relationship("FiscalYear", back_populates="mapping_templates")
190
@@ -214,3 +222,19 @@ class ValidationErrorLog(Base, TimestampMixin):
222
223
fiscal_year = relationship("FiscalYear", back_populates="validation_logs")
224
source_document = relationship("SourceDocument", back_populates="validation_logs")
225
+
226
+
227
+class StatementSnapshot(Base, TimestampMixin):
228
+ __tablename__ = "statement_snapshots"
229
+ __table_args__ = (
230
+ UniqueConstraint("year_id", "version", name="uq_year_snapshot_version"),
231
+ )
232
+
233
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
234
+ version = Column(Integer, nullable=False, default=1)
235
+ status = Column(SQLEnum(ReviewStatus), nullable=False, default=ReviewStatus.DRAFT)
236
+ snapshot_data = Column(JSON, nullable=False) # Contains frozen Trial Balance, Balance Sheet, Income Statement
237
+ created_by = Column(String(100), nullable=True)
238
+ notes = Column(Text, nullable=True)
239
+
240
+ fiscal_year = relationship("FiscalYear", back_populates="statement_snapshots")
backend/app/schemas/__init__.py
+2
@@ -9,6 +9,7 @@ from backend.app.schemas.entities import (
9
MappingTemplateRead,
10
NormalizedFinancialRecordRead,
11
ValidationErrorLogRead,
12
+ StatementSnapshotRead,
13
)
14
15
__all__ = [
@@ -22,4 +23,5 @@ __all__ = [
23
"MappingTemplateRead",
24
"NormalizedFinancialRecordRead",
25
"ValidationErrorLogRead",
26
+ "StatementSnapshotRead",
27
]
backend/app/schemas/entities.py
+13
-1
@@ -1,7 +1,7 @@
1
from datetime import datetime
2
from typing import Optional, List, Any, Dict
3
from pydantic import BaseModel, ConfigDict
4
-from backend.app.models.entities import FiscalYearStatus, StatementType, ValidationSeverity
4
+from backend.app.models.entities import FiscalYearStatus, StatementType, ValidationSeverity, ReviewStatus
5
6
7
class BaseORMModel(BaseModel):
@@ -120,3 +120,15 @@ class ValidationErrorLogRead(BaseORMModel):
120
context_data: Optional[Dict[str, Any]] = None
121
created_at: datetime
122
updated_at: datetime
123
+
124
+
125
+class StatementSnapshotRead(BaseORMModel):
126
+ id: int
127
+ year_id: int
128
+ version: int
129
+ status: ReviewStatus
130
+ snapshot_data: Dict[str, Any]
131
+ created_by: Optional[str] = None
132
+ notes: Optional[str] = None
133
+ created_at: datetime
134
+ updated_at: datetime
backend/tests/test_snapshots.py
new
+216
@@ -0,0 +1,216 @@
1
+import pytest
2
+from backend.app.models import (
3
+ Company,
4
+ FiscalYear,
5
+ FiscalYearStatus,
6
+ SourceDocument,
7
+ NormalizedFinancialRecord,
8
+ StatementSnapshot,
9
+ ReviewStatus,
10
+)
11
+from backend.app.services.protection import LockedFiscalYearError
12
+from backend.app.accounting.snapshot import (
13
+ create_statement_snapshot,
14
+ get_snapshots_for_year,
15
+ update_snapshot_review_status,
16
+)
17
+
18
+
19
+def test_create_statement_snapshot_and_versioning(db_session):
20
+ comp = Company(code="SNAP1", name="Snapshot Corp 1")
21
+ db_session.add(comp)
22
+ db_session.commit()
23
+
24
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
25
+ db_session.add(fy)
26
+ db_session.commit()
27
+
28
+ doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="h1", doc_type="ledger")
29
+ db_session.add(doc)
30
+ db_session.commit()
31
+
32
+ rec = NormalizedFinancialRecord(
33
+ year_id=fy.id,
34
+ source_document_id=doc.id,
35
+ row_index=1,
36
+ account_code="1101",
37
+ account_name="Cash",
38
+ debit=1000.0,
39
+ credit=0.0,
40
+ net_amount=1000.0,
41
+ )
42
+ db_session.add(rec)
43
+ db_session.commit()
44
+
45
+ snap1 = create_statement_snapshot(db_session, year_id=fy.id, notes="Initial run", created_by="auditor1")
46
+ assert snap1.id is not None
47
+ assert snap1.version == 1
48
+ assert snap1.status == ReviewStatus.DRAFT
49
+ assert snap1.snapshot_data["trial_balance"]["total_debit"] == 1000.0
50
+
51
+ snap2 = create_statement_snapshot(db_session, year_id=fy.id, notes="Second run", created_by="auditor2")
52
+ assert snap2.version == 2
53
+
54
+
55
+def test_review_status_transitions(db_session):
56
+ comp = Company(code="SNAP2", name="Snapshot Corp 2")
57
+ db_session.add(comp)
58
+ db_session.commit()
59
+
60
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
61
+ db_session.add(fy)
62
+ db_session.commit()
63
+
64
+ snap = create_statement_snapshot(db_session, year_id=fy.id)
65
+ assert snap.status == ReviewStatus.DRAFT
66
+
67
+ # Transition to UNDER_REVIEW
68
+ updated = update_snapshot_review_status(db_session, snap.id, ReviewStatus.UNDER_REVIEW, notes="Submitted for review")
69
+ assert updated.status == ReviewStatus.UNDER_REVIEW
70
+ assert "Submitted for review" in updated.notes
71
+
72
+ # Transition to APPROVED
73
+ approved = update_snapshot_review_status(db_session, snap.id, ReviewStatus.APPROVED, notes="Looks good")
74
+ assert approved.status == ReviewStatus.APPROVED
75
+
76
+
77
+def test_snapshots_fiscal_year_isolation(db_session):
78
+ comp = Company(code="SNAP3", name="Snapshot Corp 3")
79
+ db_session.add(comp)
80
+ db_session.commit()
81
+
82
+ fy1402 = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
83
+ fy1403 = FiscalYear(company_id=comp.id, year=1403, status=FiscalYearStatus.DRAFT)
84
+ db_session.add_all([fy1402, fy1403])
85
+ db_session.commit()
86
+
87
+ snap1402 = create_statement_snapshot(db_session, year_id=fy1402.id)
88
+ snap1403 = create_statement_snapshot(db_session, year_id=fy1403.id)
89
+
90
+ snaps_1402 = get_snapshots_for_year(db_session, fy1402.id)
91
+ snaps_1403 = get_snapshots_for_year(db_session, fy1403.id)
92
+
93
+ assert len(snaps_1402) == 1
94
+ assert snaps_1402[0].id == snap1402.id
95
+ assert len(snaps_1403) == 1
96
+ assert snaps_1403[0].id == snap1403.id
97
+
98
+
99
+def test_immutability_of_normalized_source_records_during_snapshot(db_session):
100
+ comp = Company(code="SNAP4", name="Snapshot Corp 4")
101
+ db_session.add(comp)
102
+ db_session.commit()
103
+
104
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
105
+ db_session.add(fy)
106
+ db_session.commit()
107
+
108
+ doc = SourceDocument(year_id=fy.id, filename="ledger.csv", file_hash="h4", doc_type="ledger")
109
+ db_session.add(doc)
110
+ db_session.commit()
111
+
112
+ rec = NormalizedFinancialRecord(
113
+ year_id=fy.id,
114
+ source_document_id=doc.id,
115
+ row_index=1,
116
+ account_code="1101",
117
+ account_name="Cash",
118
+ debit=500.0,
119
+ credit=0.0,
120
+ net_amount=500.0,
121
+ )
122
+ db_session.add(rec)
123
+ db_session.commit()
124
+
125
+ snap = create_statement_snapshot(db_session, year_id=fy.id)
126
+ persisted_rec = db_session.query(NormalizedFinancialRecord).filter_by(id=rec.id).first()
127
+
128
+ assert persisted_rec.debit == 500.0
129
+ assert persisted_rec.account_code == "1101"
130
+
131
+
132
+def test_locked_fiscal_year_snapshot_creation_protection(db_session):
133
+ comp = Company(code="SNAP5", name="Snapshot Corp 5")
134
+ db_session.add(comp)
135
+ db_session.commit()
136
+
137
+ fy_locked = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.LOCKED)
138
+ db_session.add(fy_locked)
139
+ db_session.commit()
140
+
141
+ with pytest.raises(LockedFiscalYearError):
142
+ create_statement_snapshot(db_session, year_id=fy_locked.id)
143
+
144
+
145
+def test_locked_fiscal_year_snapshot_update_protection(db_session):
146
+ comp = Company(code="SNAP6", name="Snapshot Corp 6")
147
+ db_session.add(comp)
148
+ db_session.commit()
149
+
150
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
151
+ db_session.add(fy)
152
+ db_session.commit()
153
+
154
+ snap = create_statement_snapshot(db_session, year_id=fy.id)
155
+
156
+ # Lock fiscal year
157
+ fy.status = FiscalYearStatus.LOCKED
158
+ db_session.commit()
159
+
160
+ with pytest.raises(LockedFiscalYearError):
161
+ update_snapshot_review_status(db_session, snap.id, ReviewStatus.APPROVED)
162
+
163
+
164
+def test_non_existent_snapshot_update_handling(db_session):
165
+ with pytest.raises(ValueError) as exc_info:
166
+ update_snapshot_review_status(db_session, 99999, ReviewStatus.APPROVED)
167
+ assert "99999" in str(exc_info.value)
168
+
169
+
170
+def test_snapshot_rejection_workflow(db_session):
171
+ comp = Company(code="SNAP7", name="Snapshot Corp 7")
172
+ db_session.add(comp)
173
+ db_session.commit()
174
+
175
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
176
+ db_session.add(fy)
177
+ db_session.commit()
178
+
179
+ snap = create_statement_snapshot(db_session, year_id=fy.id)
180
+ rejected = update_snapshot_review_status(db_session, snap.id, ReviewStatus.REJECTED, notes="Missing disclosures")
181
+
182
+ assert rejected.status == ReviewStatus.REJECTED
183
+ assert "Missing disclosures" in rejected.notes
184
+
185
+
186
+def test_get_snapshots_ordered_by_version(db_session):
187
+ comp = Company(code="SNAP8", name="Snapshot Corp 8")
188
+ db_session.add(comp)
189
+ db_session.commit()
190
+
191
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
192
+ db_session.add(fy)
193
+ db_session.commit()
194
+
195
+ snap1 = create_statement_snapshot(db_session, year_id=fy.id)
196
+ snap2 = create_statement_snapshot(db_session, year_id=fy.id)
197
+
198
+ snaps = get_snapshots_for_year(db_session, fy.id)
199
+ assert len(snaps) == 2
200
+ assert snaps[0].version == 2
201
+ assert snaps[1].version == 1
202
+
203
+
204
+def test_snapshot_data_contains_statement_foundations(db_session):
205
+ comp = Company(code="SNAP9", name="Snapshot Corp 9")
206
+ db_session.add(comp)
207
+ db_session.commit()
208
+
209
+ fy = FiscalYear(company_id=comp.id, year=1402, status=FiscalYearStatus.DRAFT)
210
+ db_session.add(fy)
211
+ db_session.commit()
212
+
213
+ snap = create_statement_snapshot(db_session, year_id=fy.id)
214
+ assert "trial_balance" in snap.snapshot_data
215
+ assert "balance_sheet" in snap.snapshot_data
216
+ assert "income_statement" in snap.snapshot_data