Implement Phase 2A persistent backend and data model foundation
Scaffold FastAPI + SQLAlchemy + Pydantic backend with SQLite support. Implement core entities (Company, FiscalYear, SourceDocument, AccountVersion, MappingRule, NoteDefinition, NoteRow, FinancialStatement, StatementLine). Add locked fiscal year protection primitives, health/read schema endpoints, and test suite covering constraints and relationships. Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>
google-labs-jules[bot] committed
Aug 21, 2026 at 18:26 UTC
04efc951ee0a2d4d5ef4b46f4da1ae0fc8b57ccf
20 files changed
+911
.gitignore
new
+24
@@ -0,0 +1,24 @@
1
+# Python / Byte-compiled files
2
+__pycache__/
3
+*.py[cod]
4
+*$py.class
5
+*.so
6
+
7
+# Environment / IDE
8
+.venv/
9
+env/
10
+venv/
11
+ENV/
12
+.vscode/
13
+.idea/
14
+
15
+# Testing / Coverage
16
+.pytest_cache/
17
+.coverage
18
+htmlcov/
19
+
20
+# Database files
21
+*.db
22
+*.sqlite
23
+*.sqlite3
24
+backend/app.db
backend/README.md
new
+57
@@ -0,0 +1,57 @@
1
+# Financial Reporting Platform - Backend Foundation (Phase 2A)
2
+
3
+This backend application implements the persistent relational data model foundation for the Financial Reporting Platform using Python, FastAPI, SQLAlchemy, and Pydantic.
4
+
5
+## Prerequisites
6
+
7
+- Python 3.10+
8
+- `pip`
9
+
10
+## Quick Start
11
+
12
+1. **Install Dependencies**:
13
+
14
+ ```bash
15
+ pip install -r backend/requirements.txt
16
+ ```
17
+
18
+2. **Initialize Database**:
19
+
20
+ By default, SQLite is used for local development (`financial_platform.db`).
21
+
22
+ ```bash
23
+ PYTHONPATH=. python3 backend/app/init_db.py
24
+ ```
25
+
26
+3. **Run Backend Server**:
27
+
28
+ ```bash
29
+ PYTHONPATH=. uvicorn backend.app.main:app --reload --port 8000
30
+ ```
31
+
32
+ - API Documentation: `http://localhost:8000/docs`
33
+ - Health Check: `http://localhost:8000/api/v1/health`
34
+
35
+## Environment Configuration
36
+
37
+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
+## Running Tests
42
+
43
+Run the full automated test suite using `pytest`:
44
+
45
+```bash
46
+PYTHONPATH=. pytest -v backend/tests
47
+```
48
+
49
+## Data Model Core Entities
50
+
51
+- **Company**: Corporate entity metadata (`code`, `name`).
52
+- **FiscalYear**: Year context (`year`, `status`: `Draft`, `Approved`, `Locked`).
53
+- **SourceDocument**: Metadata for imported ledger/statement files.
54
+- **AccountVersion**: Fiscal-year isolated Chart of Accounts.
55
+- **MappingRule**: Mapping rules linking accounts to note definitions.
56
+- **NoteDefinition** & **NoteRow**: Financial note definitions and structural line items.
57
+- **FinancialStatement** & **StatementLine**: Primary financial statement headers and line items.
backend/app/__init__.py
backend/app/api/endpoints.py
new
+56
@@ -0,0 +1,56 @@
1
+from typing import List, Optional
2
+from fastapi import APIRouter, Depends, HTTPException, Query
3
+from sqlalchemy.orm import Session
4
+
5
+from backend.app.database import get_db
6
+from backend.app import models, schemas
7
+
8
+router = APIRouter()
9
+
10
+
11
+@router.get("/health")
12
+def health_check():
13
+ """Health check endpoint to verify backend service status."""
14
+ return {"status": "ok", "service": "financial-reporting-platform"}
15
+
16
+
17
+@router.get("/companies", response_model=List[schemas.CompanyRead])
18
+def list_companies(db: Session = Depends(get_db)):
19
+ """Read-only schema endpoint listing companies."""
20
+ return db.query(models.Company).all()
21
+
22
+
23
+@router.get("/fiscal-years", response_model=List[schemas.FiscalYearRead])
24
+def list_fiscal_years(
25
+ company_id: Optional[int] = Query(None, description="Filter by company ID"),
26
+ db: Session = Depends(get_db)
27
+):
28
+ """Read-only schema endpoint listing fiscal years."""
29
+ query = db.query(models.FiscalYear)
30
+ if company_id is not None:
31
+ query = query.filter(models.FiscalYear.company_id == company_id)
32
+ return query.all()
33
+
34
+
35
+@router.get("/notes", response_model=List[schemas.NoteDefinitionRead])
36
+def list_note_definitions(
37
+ year_id: Optional[int] = Query(None, description="Filter by fiscal year ID"),
38
+ db: Session = Depends(get_db)
39
+):
40
+ """Read-only schema endpoint listing note definitions."""
41
+ query = db.query(models.NoteDefinition)
42
+ if year_id is not None:
43
+ query = query.filter(models.NoteDefinition.year_id == year_id)
44
+ return query.all()
45
+
46
+
47
+@router.get("/statements", response_model=List[schemas.FinancialStatementRead])
48
+def list_financial_statements(
49
+ year_id: Optional[int] = Query(None, description="Filter by fiscal year ID"),
50
+ db: Session = Depends(get_db)
51
+):
52
+ """Read-only schema endpoint listing financial statements."""
53
+ query = db.query(models.FinancialStatement)
54
+ if year_id is not None:
55
+ query = query.filter(models.FinancialStatement.year_id == year_id)
56
+ return query.all()
backend/app/config.py
new
+15
@@ -0,0 +1,15 @@
1
+import os
2
+from pydantic import ConfigDict
3
+from pydantic_settings import BaseSettings
4
+
5
+class Settings(BaseSettings):
6
+ PROJECT_NAME: str = "Financial Reporting Platform API"
7
+ VERSION: str = "0.1.0"
8
+ API_V1_STR: str = "/api/v1"
9
+
10
+ # Database settings default to SQLite for local dev
11
+ DATABASE_URL: str = os.getenv("DATABASE_URL", "sqlite:///./financial_platform.db")
12
+
13
+ model_config = ConfigDict(case_sensitive=True)
14
+
15
+settings = Settings()
backend/app/database.py
new
+33
@@ -0,0 +1,33 @@
1
+from sqlalchemy import create_engine, event
2
+from sqlalchemy.orm import sessionmaker, declarative_base
3
+from backend.app.config import settings
4
+
5
+# SQLite configuration requires check_same_thread=False for multithreaded web applications
6
+connect_args = {}
7
+if settings.DATABASE_URL.startswith("sqlite"):
8
+ connect_args["check_same_thread"] = False
9
+
10
+engine = create_engine(
11
+ settings.DATABASE_URL,
12
+ connect_args=connect_args,
13
+ pool_pre_ping=True,
14
+)
15
+
16
+# Enable SQLite foreign key constraint enforcement
17
+if settings.DATABASE_URL.startswith("sqlite"):
18
+ @event.listens_for(engine, "connect")
19
+ def set_sqlite_pragma(dbapi_connection, connection_record):
20
+ cursor = dbapi_connection.cursor()
21
+ cursor.execute("PRAGMA foreign_keys=ON")
22
+ cursor.close()
23
+
24
+SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
25
+
26
+Base = declarative_base()
27
+
28
+def get_db():
29
+ db = SessionLocal()
30
+ try:
31
+ yield db
32
+ finally:
33
+ db.close()
backend/app/init_db.py
new
+10
@@ -0,0 +1,10 @@
1
+from backend.app.database import engine, Base
2
+from backend.app.models import * # ensure all models are registered
3
+
4
+def init_db():
5
+ """Initializes database schema by creating all tables."""
6
+ Base.metadata.create_all(bind=engine)
7
+
8
+if __name__ == "__main__":
9
+ init_db()
10
+ print("Database tables initialized successfully.")
backend/app/main.py
new
+15
@@ -0,0 +1,15 @@
1
+from fastapi import FastAPI
2
+from backend.app.config import settings
3
+from backend.app.api.endpoints import router as api_router
4
+
5
+app = FastAPI(
6
+ title=settings.PROJECT_NAME,
7
+ version=settings.VERSION,
8
+ openapi_url=f"{settings.API_V1_STR}/openapi.json",
9
+)
10
+
11
+app.include_router(api_router, prefix=settings.API_V1_STR)
12
+
13
+@app.get("/")
14
+def root():
15
+ return {"message": "Financial Reporting Platform API Foundation", "docs": "/docs"}
backend/app/models/__init__.py
new
+29
@@ -0,0 +1,29 @@
1
+from backend.app.models.base import TimestampMixin
2
+from backend.app.models.entities import (
3
+ Company,
4
+ FiscalYear,
5
+ FiscalYearStatus,
6
+ StatementType,
7
+ SourceDocument,
8
+ AccountVersion,
9
+ MappingRule,
10
+ NoteDefinition,
11
+ NoteRow,
12
+ FinancialStatement,
13
+ StatementLine,
14
+)
15
+
16
+__all__ = [
17
+ "TimestampMixin",
18
+ "Company",
19
+ "FiscalYear",
20
+ "FiscalYearStatus",
21
+ "StatementType",
22
+ "SourceDocument",
23
+ "AccountVersion",
24
+ "MappingRule",
25
+ "NoteDefinition",
26
+ "NoteRow",
27
+ "FinancialStatement",
28
+ "StatementLine",
29
+]
backend/app/models/base.py
new
+17
@@ -0,0 +1,17 @@
1
+from datetime import datetime, timezone
2
+from sqlalchemy import Column, Integer, DateTime
3
+from backend.app.database import Base
4
+
5
+class TimestampMixin:
6
+ id = Column(Integer, primary_key=True, index=True, autoincrement=True)
7
+ created_at = Column(
8
+ DateTime(timezone=True),
9
+ default=lambda: datetime.now(timezone.utc),
10
+ nullable=False,
11
+ )
12
+ updated_at = Column(
13
+ DateTime(timezone=True),
14
+ default=lambda: datetime.now(timezone.utc),
15
+ onupdate=lambda: datetime.now(timezone.utc),
16
+ nullable=False,
17
+ )
backend/app/models/entities.py
new
+155
@@ -0,0 +1,155 @@
1
+import enum
2
+from sqlalchemy import (
3
+ Column,
4
+ String,
5
+ Integer,
6
+ ForeignKey,
7
+ Enum as SQLEnum,
8
+ UniqueConstraint,
9
+ JSON,
10
+ Numeric,
11
+ Text,
12
+)
13
+from sqlalchemy.orm import relationship
14
+
15
+from backend.app.database import Base
16
+from backend.app.models.base import TimestampMixin
17
+
18
+
19
+class FiscalYearStatus(str, enum.Enum):
20
+ DRAFT = "Draft"
21
+ APPROVED = "Approved"
22
+ LOCKED = "Locked"
23
+
24
+
25
+class StatementType(str, enum.Enum):
26
+ BS = "BS" # Balance Sheet
27
+ IS = "IS" # Income Statement
28
+ CF = "CF" # Cash Flow
29
+ EQ = "EQ" # Equity Statement
30
+
31
+
32
+class Company(Base, TimestampMixin):
33
+ __tablename__ = "companies"
34
+
35
+ code = Column(String(50), unique=True, index=True, nullable=False)
36
+ name = Column(String(255), nullable=False)
37
+
38
+ fiscal_years = relationship("FiscalYear", back_populates="company", cascade="all, delete-orphan")
39
+
40
+
41
+class FiscalYear(Base, TimestampMixin):
42
+ __tablename__ = "fiscal_years"
43
+ __table_args__ = (
44
+ UniqueConstraint("company_id", "year", name="uq_company_fiscal_year"),
45
+ )
46
+
47
+ company_id = Column(Integer, ForeignKey("companies.id", ondelete="CASCADE"), nullable=False, index=True)
48
+ year = Column(Integer, nullable=False, index=True)
49
+ status = Column(SQLEnum(FiscalYearStatus), default=FiscalYearStatus.DRAFT, nullable=False)
50
+
51
+ company = relationship("Company", back_populates="fiscal_years")
52
+ source_documents = relationship("SourceDocument", back_populates="fiscal_year", cascade="all, delete-orphan")
53
+ account_versions = relationship("AccountVersion", back_populates="fiscal_year", cascade="all, delete-orphan")
54
+ mapping_rules = relationship("MappingRule", back_populates="fiscal_year", cascade="all, delete-orphan")
55
+ note_definitions = relationship("NoteDefinition", back_populates="fiscal_year", cascade="all, delete-orphan")
56
+ financial_statements = relationship("FinancialStatement", back_populates="fiscal_year", cascade="all, delete-orphan")
57
+
58
+
59
+class SourceDocument(Base, TimestampMixin):
60
+ __tablename__ = "source_documents"
61
+
62
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
63
+ filename = Column(String(255), nullable=False)
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
+
68
+ fiscal_year = relationship("FiscalYear", back_populates="source_documents")
69
+
70
+
71
+class AccountVersion(Base, TimestampMixin):
72
+ __tablename__ = "account_versions"
73
+ __table_args__ = (
74
+ UniqueConstraint("year_id", "account_code", name="uq_year_account_code"),
75
+ )
76
+
77
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
78
+ account_code = Column(String(100), nullable=False, index=True)
79
+ account_name = Column(String(255), nullable=False)
80
+ t1 = Column(String(100), nullable=True)
81
+ t2 = Column(String(100), nullable=True)
82
+ t3 = Column(String(100), nullable=True)
83
+ t4 = Column(String(100), nullable=True)
84
+ nature = Column(String(50), nullable=True)
85
+
86
+ fiscal_year = relationship("FiscalYear", back_populates="account_versions")
87
+ mapping_rules = relationship("MappingRule", back_populates="account_version", cascade="all, delete-orphan")
88
+
89
+
90
+class MappingRule(Base, TimestampMixin):
91
+ __tablename__ = "mapping_rules"
92
+
93
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
94
+ account_code = Column(String(100), nullable=False, index=True)
95
+ account_version_id = Column(Integer, ForeignKey("account_versions.id", ondelete="SET NULL"), nullable=True)
96
+ target_note_id = Column(Integer, ForeignKey("note_definitions.id", ondelete="SET NULL"), nullable=True)
97
+ mapping_type = Column(String(50), nullable=False, default="DETERMINISTIC")
98
+
99
+ fiscal_year = relationship("FiscalYear", back_populates="mapping_rules")
100
+ account_version = relationship("AccountVersion", back_populates="mapping_rules")
101
+ target_note = relationship("NoteDefinition", back_populates="mapping_rules")
102
+
103
+
104
+class NoteDefinition(Base, TimestampMixin):
105
+ __tablename__ = "note_definitions"
106
+ __table_args__ = (
107
+ UniqueConstraint("year_id", "note_number", name="uq_year_note_number"),
108
+ )
109
+
110
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
111
+ note_number = Column(Integer, nullable=False, index=True)
112
+ title = Column(String(255), nullable=False)
113
+ configuration_json = Column(JSON, nullable=True)
114
+
115
+ fiscal_year = relationship("FiscalYear", back_populates="note_definitions")
116
+ rows = relationship("NoteRow", back_populates="note_definition", cascade="all, delete-orphan")
117
+ mapping_rules = relationship("MappingRule", back_populates="target_note")
118
+ statement_lines = relationship("StatementLine", back_populates="target_note")
119
+
120
+
121
+class NoteRow(Base, TimestampMixin):
122
+ __tablename__ = "note_rows"
123
+
124
+ note_id = Column(Integer, ForeignKey("note_definitions.id", ondelete="CASCADE"), nullable=False, index=True)
125
+ row_order = Column(Integer, nullable=False)
126
+ label = Column(String(255), nullable=False)
127
+ formula_logic = Column(Text, nullable=True)
128
+ sorting_rule_id = Column(String(50), nullable=True)
129
+
130
+ note_definition = relationship("NoteDefinition", back_populates="rows")
131
+
132
+
133
+class FinancialStatement(Base, TimestampMixin):
134
+ __tablename__ = "financial_statements"
135
+ __table_args__ = (
136
+ UniqueConstraint("year_id", "statement_type", name="uq_year_statement_type"),
137
+ )
138
+
139
+ year_id = Column(Integer, ForeignKey("fiscal_years.id", ondelete="CASCADE"), nullable=False, index=True)
140
+ statement_type = Column(SQLEnum(StatementType), nullable=False)
141
+
142
+ fiscal_year = relationship("FiscalYear", back_populates="financial_statements")
143
+ lines = relationship("StatementLine", back_populates="financial_statement", cascade="all, delete-orphan")
144
+
145
+
146
+class StatementLine(Base, TimestampMixin):
147
+ __tablename__ = "statement_lines"
148
+
149
+ statement_id = Column(Integer, ForeignKey("financial_statements.id", ondelete="CASCADE"), nullable=False, index=True)
150
+ line_label = Column(String(255), nullable=False)
151
+ target_note_id = Column(Integer, ForeignKey("note_definitions.id", ondelete="SET NULL"), nullable=True)
152
+ mapped_total = Column(Numeric(precision=20, scale=2), nullable=True)
153
+
154
+ financial_statement = relationship("FinancialStatement", back_populates="lines")
155
+ target_note = relationship("NoteDefinition", back_populates="statement_lines")
backend/app/schemas/__init__.py
new
+19
@@ -0,0 +1,19 @@
1
+from backend.app.schemas.entities import (
2
+ CompanyRead,
3
+ FiscalYearRead,
4
+ SourceDocumentRead,
5
+ NoteDefinitionRead,
6
+ NoteRowRead,
7
+ FinancialStatementRead,
8
+ StatementLineRead,
9
+)
10
+
11
+__all__ = [
12
+ "CompanyRead",
13
+ "FiscalYearRead",
14
+ "SourceDocumentRead",
15
+ "NoteDefinitionRead",
16
+ "NoteRowRead",
17
+ "FinancialStatementRead",
18
+ "StatementLineRead",
19
+]
backend/app/schemas/entities.py
new
+81
@@ -0,0 +1,81 @@
1
+from datetime import datetime
2
+from typing import Optional, List, Any
3
+from pydantic import BaseModel, ConfigDict
4
+from backend.app.models.entities import FiscalYearStatus, StatementType
5
+
6
+
7
+class BaseORMModel(BaseModel):
8
+ model_config = ConfigDict(from_attributes=True)
9
+
10
+
11
+class CompanyBase(BaseModel):
12
+ code: str
13
+ name: str
14
+
15
+
16
+class CompanyRead(CompanyBase, BaseORMModel):
17
+ id: int
18
+ created_at: datetime
19
+ updated_at: datetime
20
+
21
+
22
+class FiscalYearBase(BaseModel):
23
+ company_id: int
24
+ year: int
25
+ status: FiscalYearStatus = FiscalYearStatus.DRAFT
26
+
27
+
28
+class FiscalYearRead(FiscalYearBase, BaseORMModel):
29
+ id: int
30
+ created_at: datetime
31
+ updated_at: datetime
32
+
33
+
34
+class SourceDocumentRead(BaseORMModel):
35
+ id: int
36
+ year_id: int
37
+ filename: str
38
+ file_hash: str
39
+ doc_type: str
40
+ upload_date: Optional[str] = None
41
+ created_at: datetime
42
+ updated_at: datetime
43
+
44
+
45
+class NoteRowRead(BaseORMModel):
46
+ id: int
47
+ note_id: int
48
+ row_order: int
49
+ label: str
50
+ formula_logic: Optional[str] = None
51
+ sorting_rule_id: Optional[str] = None
52
+ created_at: datetime
53
+ updated_at: datetime
54
+
55
+
56
+class NoteDefinitionRead(BaseORMModel):
57
+ id: int
58
+ year_id: int
59
+ note_number: int
60
+ title: str
61
+ configuration_json: Optional[Any] = None
62
+ created_at: datetime
63
+ updated_at: datetime
64
+
65
+
66
+class StatementLineRead(BaseORMModel):
67
+ id: int
68
+ statement_id: int
69
+ line_label: str
70
+ target_note_id: Optional[int] = None
71
+ mapped_total: Optional[float] = None
72
+ created_at: datetime
73
+ updated_at: datetime
74
+
75
+
76
+class FinancialStatementRead(BaseORMModel):
77
+ id: int
78
+ year_id: int
79
+ statement_type: StatementType
80
+ created_at: datetime
81
+ updated_at: datetime
backend/app/services/protection.py
new
+28
@@ -0,0 +1,28 @@
1
+from sqlalchemy.orm import Session
2
+from backend.app.models.entities import FiscalYear, FiscalYearStatus
3
+
4
+
5
+class LockedFiscalYearError(Exception):
6
+ """Raised when attempting to modify data associated with an Approved or Locked fiscal year."""
7
+ def __init__(self, year: int, status: FiscalYearStatus):
8
+ self.year = year
9
+ self.status = status
10
+ super().__init__(
11
+ f"Cannot modify data for fiscal year {year} because its status is '{status.value}'. "
12
+ "Data in Approved or Locked fiscal years is immutable."
13
+ )
14
+
15
+
16
+def check_fiscal_year_mutable(db: Session, year_id: int) -> FiscalYear:
17
+ """
18
+ Verifies if a fiscal year is mutable (i.e. status is Draft).
19
+ If status is Approved or Locked, raises LockedFiscalYearError.
20
+ """
21
+ fiscal_year = db.query(FiscalYear).filter(FiscalYear.id == year_id).first()
22
+ if not fiscal_year:
23
+ raise ValueError(f"FiscalYear with id {year_id} not found.")
24
+
25
+ if fiscal_year.status in (FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED):
26
+ raise LockedFiscalYearError(year=fiscal_year.year, status=fiscal_year.status)
27
+
28
+ return fiscal_year
backend/requirements.txt
new
+8
@@ -0,0 +1,8 @@
1
+fastapi>=0.110.0,<1.0.0
2
+uvicorn[standard]>=0.28.0,<1.0.0
3
+sqlalchemy>=2.0.0,<3.0.0
4
+pydantic>=2.6.0,<3.0.0
5
+pydantic-settings>=2.2.0,<3.0.0
6
+pytest>=8.0.0,<10.0.0
7
+httpx>=0.27.0,<1.0.0
8
+alembic>=1.13.0,<2.0.0
backend/tests/conftest.py
new
+51
@@ -0,0 +1,51 @@
1
+import pytest
2
+from sqlalchemy import create_engine, event
3
+from sqlalchemy.orm import sessionmaker
4
+from sqlalchemy.pool import StaticPool
5
+from fastapi.testclient import TestClient
6
+
7
+from backend.app.database import Base, get_db
8
+from backend.app.main import app
9
+
10
+# Use StaticPool with sqlite:// for shared in-memory test database across thread connections
11
+SQLALCHEMY_DATABASE_URL = "sqlite://"
12
+
13
+@pytest.fixture(scope="function")
14
+def db_engine():
15
+ engine = create_engine(
16
+ SQLALCHEMY_DATABASE_URL,
17
+ connect_args={"check_same_thread": False},
18
+ poolclass=StaticPool,
19
+ )
20
+
21
+ @event.listens_for(engine, "connect")
22
+ def set_sqlite_pragma(dbapi_connection, connection_record):
23
+ cursor = dbapi_connection.cursor()
24
+ cursor.execute("PRAGMA foreign_keys=ON")
25
+ cursor.close()
26
+
27
+ Base.metadata.create_all(bind=engine)
28
+ yield engine
29
+ Base.metadata.drop_all(bind=engine)
30
+
31
+@pytest.fixture(scope="function")
32
+def db_session(db_engine):
33
+ TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=db_engine)
34
+ session = TestingSessionLocal()
35
+ try:
36
+ yield session
37
+ finally:
38
+ session.close()
39
+
40
+@pytest.fixture(scope="function")
41
+def client(db_session):
42
+ def override_get_db():
43
+ try:
44
+ yield db_session
45
+ finally:
46
+ pass
47
+
48
+ app.dependency_overrides[get_db] = override_get_db
49
+ with TestClient(app) as c:
50
+ yield c
51
+ app.dependency_overrides.clear()
backend/tests/test_api.py
new
+67
@@ -0,0 +1,67 @@
1
+from backend.app.models import Company, FiscalYear, FiscalYearStatus, NoteDefinition, FinancialStatement, StatementType
2
+
3
+
4
+def test_root_endpoint(client):
5
+ response = client.get("/")
6
+ assert response.status_code == 200
7
+ assert response.json()["message"] == "Financial Reporting Platform API Foundation"
8
+
9
+
10
+def test_health_endpoint(client):
11
+ response = client.get("/api/v1/health")
12
+ assert response.status_code == 200
13
+ assert response.json() == {"status": "ok", "service": "financial-reporting-platform"}
14
+
15
+
16
+def test_list_companies_endpoint(client, db_session):
17
+ company = Company(code="API_C1", name="API Test Company")
18
+ db_session.add(company)
19
+ db_session.commit()
20
+
21
+ response = client.get("/api/v1/companies")
22
+ assert response.status_code == 200
23
+ data = response.json()
24
+ assert len(data) == 1
25
+ assert data[0]["code"] == "API_C1"
26
+
27
+
28
+def test_list_fiscal_years_endpoint(client, db_session):
29
+ company = Company(code="API_C2", name="API Test Company 2")
30
+ db_session.add(company)
31
+ db_session.commit()
32
+
33
+ fy = FiscalYear(company_id=company.id, year=1403, status=FiscalYearStatus.DRAFT)
34
+ db_session.add(fy)
35
+ db_session.commit()
36
+
37
+ response = client.get(f"/api/v1/fiscal-years?company_id={company.id}")
38
+ assert response.status_code == 200
39
+ data = response.json()
40
+ assert len(data) == 1
41
+ assert data[0]["year"] == 1403
42
+ assert data[0]["status"] == "Draft"
43
+
44
+
45
+def test_list_notes_and_statements_endpoints(client, db_session):
46
+ company = Company(code="API_C3", name="API Test Company 3")
47
+ db_session.add(company)
48
+ db_session.commit()
49
+
50
+ fy = FiscalYear(company_id=company.id, year=1404, status=FiscalYearStatus.DRAFT)
51
+ db_session.add(fy)
52
+ db_session.commit()
53
+
54
+ note = NoteDefinition(year_id=fy.id, note_number=1, title="General Note")
55
+ stmt = FinancialStatement(year_id=fy.id, statement_type=StatementType.BS)
56
+ db_session.add_all([note, stmt])
57
+ db_session.commit()
58
+
59
+ res_notes = client.get(f"/api/v1/notes?year_id={fy.id}")
60
+ assert res_notes.status_code == 200
61
+ assert len(res_notes.json()) == 1
62
+ assert res_notes.json()[0]["title"] == "General Note"
63
+
64
+ res_stmts = client.get(f"/api/v1/statements?year_id={fy.id}")
65
+ assert res_stmts.status_code == 200
66
+ assert len(res_stmts.json()) == 1
67
+ assert res_stmts.json()[0]["statement_type"] == "BS"
backend/tests/test_constraints.py
new
+90
@@ -0,0 +1,90 @@
1
+import pytest
2
+from sqlalchemy.exc import IntegrityError
3
+from backend.app.models import (
4
+ Company,
5
+ FiscalYear,
6
+ FiscalYearStatus,
7
+ AccountVersion,
8
+ NoteDefinition,
9
+ FinancialStatement,
10
+ StatementType,
11
+ SourceDocument,
12
+)
13
+
14
+
15
+def test_unique_company_code(db_session):
16
+ c1 = Company(code="C1", name="Company One")
17
+ db_session.add(c1)
18
+ db_session.commit()
19
+
20
+ c2 = Company(code="C1", name="Company Two")
21
+ db_session.add(c2)
22
+ with pytest.raises(IntegrityError):
23
+ db_session.commit()
24
+ db_session.rollback()
25
+
26
+
27
+def test_unique_company_fiscal_year(db_session):
28
+ c = Company(code="C1", name="Company One")
29
+ db_session.add(c)
30
+ db_session.commit()
31
+
32
+ fy1 = FiscalYear(company_id=c.id, year=1402, status=FiscalYearStatus.DRAFT)
33
+ db_session.add(fy1)
34
+ db_session.commit()
35
+
36
+ fy2 = FiscalYear(company_id=c.id, year=1402, status=FiscalYearStatus.DRAFT)
37
+ db_session.add(fy2)
38
+ with pytest.raises(IntegrityError):
39
+ db_session.commit()
40
+ db_session.rollback()
41
+
42
+
43
+def test_unique_year_account_code(db_session):
44
+ c = Company(code="C1", name="Company One")
45
+ db_session.add(c)
46
+ db_session.commit()
47
+
48
+ fy = FiscalYear(company_id=c.id, year=1402, status=FiscalYearStatus.DRAFT)
49
+ db_session.add(fy)
50
+ db_session.commit()
51
+
52
+ a1 = AccountVersion(year_id=fy.id, account_code="1001", account_name="Acc 1")
53
+ a2 = AccountVersion(year_id=fy.id, account_code="1001", account_name="Acc 2")
54
+ db_session.add_all([a1, a2])
55
+ with pytest.raises(IntegrityError):
56
+ db_session.commit()
57
+ db_session.rollback()
58
+
59
+
60
+def test_fiscal_year_isolation(db_session):
61
+ c = Company(code="C1", name="Company One")
62
+ db_session.add(c)
63
+ db_session.commit()
64
+
65
+ fy1402 = FiscalYear(company_id=c.id, year=1402, status=FiscalYearStatus.LOCKED)
66
+ fy1403 = FiscalYear(company_id=c.id, year=1403, status=FiscalYearStatus.DRAFT)
67
+ db_session.add_all([fy1402, fy1403])
68
+ db_session.commit()
69
+
70
+ # Accounts with same code in different fiscal years should be allowed
71
+ a1402 = AccountVersion(year_id=fy1402.id, account_code="1001", account_name="1402 Cash")
72
+ a1403 = AccountVersion(year_id=fy1403.id, account_code="1001", account_name="1403 Cash")
73
+ db_session.add_all([a1402, a1403])
74
+ db_session.commit()
75
+
76
+ assert a1402.year_id != a1403.year_id
77
+
78
+
79
+def test_foreign_key_constraint(db_session):
80
+ # Attempt to insert SourceDocument for non-existent year_id
81
+ doc = SourceDocument(
82
+ year_id=99999,
83
+ filename="non_existent.xlsx",
84
+ file_hash="dummy",
85
+ doc_type="ledger",
86
+ )
87
+ db_session.add(doc)
88
+ with pytest.raises(IntegrityError):
89
+ db_session.commit()
90
+ db_session.rollback()
backend/tests/test_locked_year_protection.py
new
+50
@@ -0,0 +1,50 @@
1
+import pytest
2
+from backend.app.models import Company, FiscalYear, FiscalYearStatus
3
+from backend.app.services.protection import check_fiscal_year_mutable, LockedFiscalYearError
4
+
5
+
6
+def test_draft_fiscal_year_is_mutable(db_session):
7
+ company = Company(code="C_MUTE", name="Mutable Test Corp")
8
+ db_session.add(company)
9
+ db_session.commit()
10
+
11
+ fy = FiscalYear(company_id=company.id, year=1402, status=FiscalYearStatus.DRAFT)
12
+ db_session.add(fy)
13
+ db_session.commit()
14
+
15
+ # Checking mutability should succeed and return the fiscal year object
16
+ verified_fy = check_fiscal_year_mutable(db_session, fy.id)
17
+ assert verified_fy.id == fy.id
18
+ assert verified_fy.status == FiscalYearStatus.DRAFT
19
+
20
+
21
+def test_approved_fiscal_year_raises_error(db_session):
22
+ company = Company(code="C_APP", name="Approved Test Corp")
23
+ db_session.add(company)
24
+ db_session.commit()
25
+
26
+ fy = FiscalYear(company_id=company.id, year=1402, status=FiscalYearStatus.APPROVED)
27
+ db_session.add(fy)
28
+ db_session.commit()
29
+
30
+ with pytest.raises(LockedFiscalYearError) as exc_info:
31
+ check_fiscal_year_mutable(db_session, fy.id)
32
+
33
+ assert "1402" in str(exc_info.value)
34
+ assert "Approved" in str(exc_info.value)
35
+
36
+
37
+def test_locked_fiscal_year_raises_error(db_session):
38
+ company = Company(code="C_LOCK", name="Locked Test Corp")
39
+ db_session.add(company)
40
+ db_session.commit()
41
+
42
+ fy = FiscalYear(company_id=company.id, year=1402, status=FiscalYearStatus.LOCKED)
43
+ db_session.add(fy)
44
+ db_session.commit()
45
+
46
+ with pytest.raises(LockedFiscalYearError) as exc_info:
47
+ check_fiscal_year_mutable(db_session, fy.id)
48
+
49
+ assert "1402" in str(exc_info.value)
50
+ assert "Locked" in str(exc_info.value)
backend/tests/test_models.py
new
+106
@@ -0,0 +1,106 @@
1
+from backend.app.models import (
2
+ Company,
3
+ FiscalYear,
4
+ FiscalYearStatus,
5
+ SourceDocument,
6
+ AccountVersion,
7
+ MappingRule,
8
+ NoteDefinition,
9
+ NoteRow,
10
+ FinancialStatement,
11
+ StatementType,
12
+ StatementLine,
13
+)
14
+
15
+
16
+def test_create_core_entities_and_relationships(db_session):
17
+ # 1. Create Company
18
+ company = Company(code="COMP01", name="Test Company PLC")
19
+ db_session.add(company)
20
+ db_session.commit()
21
+ db_session.refresh(company)
22
+
23
+ assert company.id is not None
24
+ assert company.code == "COMP01"
25
+ assert company.created_at is not None
26
+
27
+ # 2. Create Fiscal Year
28
+ fy1402 = FiscalYear(company_id=company.id, year=1402, status=FiscalYearStatus.DRAFT)
29
+ db_session.add(fy1402)
30
+ db_session.commit()
31
+ db_session.refresh(fy1402)
32
+
33
+ assert fy1402.id is not None
34
+ assert fy1402.company.name == "Test Company PLC"
35
+
36
+ # 3. Create Source Document
37
+ doc = SourceDocument(
38
+ year_id=fy1402.id,
39
+ filename="ledger_1402.xlsx",
40
+ file_hash="abc123hash",
41
+ doc_type="ledger",
42
+ )
43
+ db_session.add(doc)
44
+
45
+ # 4. Create Account Version
46
+ acc = AccountVersion(
47
+ year_id=fy1402.id,
48
+ account_code="110101",
49
+ account_name="Cash in Hand",
50
+ nature="Debit",
51
+ )
52
+ db_session.add(acc)
53
+
54
+ # 5. Create Note Definition and Row
55
+ note = NoteDefinition(
56
+ year_id=fy1402.id,
57
+ note_number=5,
58
+ title="Cash and Cash Equivalents",
59
+ configuration_json={"section": "Current Assets"},
60
+ )
61
+ db_session.add(note)
62
+ db_session.commit()
63
+ db_session.refresh(note)
64
+
65
+ row = NoteRow(
66
+ note_id=note.id,
67
+ row_order=1,
68
+ label="Petty Cash",
69
+ formula_logic="SUM(110101)",
70
+ )
71
+ db_session.add(row)
72
+
73
+ # 6. Create Mapping Rule
74
+ rule = MappingRule(
75
+ year_id=fy1402.id,
76
+ account_code="110101",
77
+ account_version_id=acc.id,
78
+ target_note_id=note.id,
79
+ mapping_type="DETERMINISTIC",
80
+ )
81
+ db_session.add(rule)
82
+
83
+ # 7. Create Financial Statement and Line
84
+ stmt = FinancialStatement(year_id=fy1402.id, statement_type=StatementType.BS)
85
+ db_session.add(stmt)
86
+ db_session.commit()
87
+ db_session.refresh(stmt)
88
+
89
+ line = StatementLine(
90
+ statement_id=stmt.id,
91
+ line_label="Cash and Cash Equivalents",
92
+ target_note_id=note.id,
93
+ mapped_total=1500000.00,
94
+ )
95
+ db_session.add(line)
96
+ db_session.commit()
97
+
98
+ # Verify relationships via cascade/backref
99
+ db_session.refresh(fy1402)
100
+ assert len(fy1402.source_documents) == 1
101
+ assert len(fy1402.account_versions) == 1
102
+ assert len(fy1402.note_definitions) == 1
103
+ assert len(fy1402.financial_statements) == 1
104
+ assert len(note.rows) == 1
105
+ assert len(stmt.lines) == 1
106
+ assert stmt.lines[0].target_note.title == "Cash and Cash Equivalents"