Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 14:30 UTC
feat(backend): add Phase 2A persistent data foundation
Implements FastAPI, SQLAlchemy, Pydantic schemas, Alembic migrations, audit-safe fiscal-year invariants, read-only schema endpoints, and automated tests. No canonical financial data is changed. Refs #5
davoodmehraban89 committed
Aug 20, 2026 at 22:00 UTC
51c93193d8aaa99c3cde565b94ea7ac4bcec5fba
17 files changed
+707
backend/.env.example
new
+2
@@ -0,0 +1,2 @@
1
+ARAM_DATABASE_URL=sqlite:///./aram.db
2
+
backend/.gitignore
new
+8
@@ -0,0 +1,8 @@
1
+.venv/
2
+__pycache__/
3
+.pytest_cache/
4
+*.py[cod]
5
+*.db
6
+*.sqlite
7
+*.sqlite3
8
+
backend/README.md
new
+31
@@ -0,0 +1,31 @@
1
+# Aram backend
2
+
3
+Phase 2A provides the persistent, audit-safe data foundation. It deliberately
4
+does not ingest spreadsheets, calculate financial values, or alter canonical
5
+source files.
6
+
7
+## Local setup
8
+
9
+```bash
10
+cd backend
11
+python -m venv .venv
12
+source .venv/bin/activate
13
+python -m pip install -e '.[test]'
14
+alembic upgrade head
15
+uvicorn aram_backend.main:app --reload
16
+```
17
+
18
+Open `http://127.0.0.1:8000/docs`. The health endpoint is
19
+`GET /api/v1/health`; read-only schema catalogs are available at
20
+`GET /api/v1/schema/entities` and `GET /api/v1/schema/enums`.
21
+
22
+## Tests
23
+
24
+```bash
25
+cd backend
26
+pytest
27
+```
28
+
29
+Tests use an isolated temporary SQLite database with foreign-key enforcement.
30
+Runtime SQLite files are ignored by Git.
31
+
backend/alembic.ini
new
+32
@@ -0,0 +1,32 @@
1
+[alembic]
2
+script_location = migrations
3
+prepend_sys_path = src
4
+sqlalchemy.url = sqlite:///./aram.db
5
+
6
+[loggers]
7
+keys = root,sqlalchemy,alembic
8
+[handlers]
9
+keys = console
10
+[formatters]
11
+keys = generic
12
+[logger_root]
13
+level = WARN
14
+handlers = console
15
+qualname =
16
+[logger_sqlalchemy]
17
+level = WARN
18
+handlers =
19
+qualname = sqlalchemy.engine
20
+[logger_alembic]
21
+level = INFO
22
+handlers =
23
+qualname = alembic
24
+[handler_console]
25
+class = StreamHandler
26
+args = (sys.stderr,)
27
+level = NOTSET
28
+formatter = generic
29
+[formatter_generic]
30
+format = %(levelname)-5.5s [%(name)s] %(message)s
31
+datefmt = %H:%M:%S
32
+
backend/migrations/env.py
new
+49
@@ -0,0 +1,49 @@
1
+from logging.config import fileConfig
2
+
3
+from alembic import context
4
+from sqlalchemy import engine_from_config, pool
5
+
6
+from aram_backend.config import get_settings
7
+from aram_backend.database import Base
8
+from aram_backend import models # noqa: F401
9
+
10
+config = context.config
11
+if config.config_file_name:
12
+ fileConfig(config.config_file_name)
13
+config.set_main_option("sqlalchemy.url", get_settings().database_url)
14
+target_metadata = Base.metadata
15
+
16
+
17
+def run_migrations_offline() -> None:
18
+ context.configure(
19
+ url=config.get_main_option("sqlalchemy.url"),
20
+ target_metadata=target_metadata,
21
+ literal_binds=True,
22
+ dialect_opts={"paramstyle": "named"},
23
+ render_as_batch=True,
24
+ )
25
+ with context.begin_transaction():
26
+ context.run_migrations()
27
+
28
+
29
+def run_migrations_online() -> None:
30
+ connectable = engine_from_config(
31
+ config.get_section(config.config_ini_section, {}),
32
+ prefix="sqlalchemy.",
33
+ poolclass=pool.NullPool,
34
+ )
35
+ with connectable.connect() as connection:
36
+ context.configure(
37
+ connection=connection,
38
+ target_metadata=target_metadata,
39
+ render_as_batch=True,
40
+ )
41
+ with context.begin_transaction():
42
+ context.run_migrations()
43
+
44
+
45
+if context.is_offline_mode():
46
+ run_migrations_offline()
47
+else:
48
+ run_migrations_online()
49
+
backend/migrations/script.py.mako
new
+24
@@ -0,0 +1,24 @@
1
+"""${message}
2
+
3
+Revision ID: ${up_revision}
4
+Revises: ${down_revision | comma,n}
5
+"""
6
+from typing import Sequence, Union
7
+
8
+from alembic import op
9
+import sqlalchemy as sa
10
+${imports if imports else ""}
11
+
12
+revision: str = ${repr(up_revision)}
13
+down_revision: Union[str, None] = ${repr(down_revision)}
14
+branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
15
+depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
16
+
17
+
18
+def upgrade() -> None:
19
+ ${upgrades if upgrades else "pass"}
20
+
21
+
22
+def downgrade() -> None:
23
+ ${downgrades if downgrades else "pass"}
24
+
backend/migrations/versions/20260820_01_initial_schema.py
new
+24
@@ -0,0 +1,24 @@
1
+"""Initial Phase 2A schema.
2
+
3
+Revision ID: 20260820_01
4
+"""
5
+from alembic import op
6
+
7
+from aram_backend.database import Base
8
+from aram_backend import models # noqa: F401
9
+
10
+revision = "20260820_01"
11
+down_revision = None
12
+branch_labels = None
13
+depends_on = None
14
+
15
+
16
+def upgrade() -> None:
17
+ bind = op.get_bind()
18
+ Base.metadata.create_all(bind=bind)
19
+
20
+
21
+def downgrade() -> None:
22
+ bind = op.get_bind()
23
+ Base.metadata.drop_all(bind=bind)
24
+
backend/pyproject.toml
new
+30
@@ -0,0 +1,30 @@
1
+[build-system]
2
+requires = ["setuptools>=75,<81"]
3
+build-backend = "setuptools.build_meta"
4
+
5
+[project]
6
+name = "aram-backend"
7
+version = "0.1.0"
8
+description = "Audit-safe backend foundation for Aram financial statements"
9
+requires-python = ">=3.11"
10
+dependencies = [
11
+ "alembic>=1.14,<2",
12
+ "fastapi>=0.115,<1",
13
+ "pydantic-settings>=2.7,<3",
14
+ "sqlalchemy>=2.0,<3",
15
+ "uvicorn[standard]>=0.34,<1",
16
+]
17
+
18
+[project.optional-dependencies]
19
+test = [
20
+ "httpx>=0.28,<1",
21
+ "pytest>=8.3,<9",
22
+]
23
+
24
+[tool.setuptools.packages.find]
25
+where = ["src"]
26
+
27
+[tool.pytest.ini_options]
28
+testpaths = ["tests"]
29
+addopts = "-q"
30
+
backend/src/aram_backend/__init__.py
new
+4
@@ -0,0 +1,4 @@
1
+"""Aram backend package."""
2
+
3
+__version__ = "0.1.0"
4
+
backend/src/aram_backend/config.py
new
+16
@@ -0,0 +1,16 @@
1
+from functools import lru_cache
2
+
3
+from pydantic_settings import BaseSettings, SettingsConfigDict
4
+
5
+
6
+class Settings(BaseSettings):
7
+ app_name: str = "Aram API"
8
+ environment: str = "development"
9
+ database_url: str = "sqlite:///./aram.db"
10
+ model_config = SettingsConfigDict(env_prefix="ARAM_", env_file=".env")
11
+
12
+
13
+@lru_cache
14
+def get_settings() -> Settings:
15
+ return Settings()
16
+
backend/src/aram_backend/database.py
new
+44
@@ -0,0 +1,44 @@
1
+from collections.abc import Generator
2
+
3
+from sqlalchemy import MetaData, create_engine, event
4
+from sqlalchemy.engine import Engine
5
+from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
6
+
7
+from aram_backend.config import get_settings
8
+
9
+NAMING_CONVENTION = {
10
+ "ix": "ix_%(column_0_label)s",
11
+ "uq": "uq_%(table_name)s_%(column_0_name)s",
12
+ "ck": "ck_%(table_name)s_%(constraint_name)s",
13
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
14
+ "pk": "pk_%(table_name)s",
15
+}
16
+
17
+
18
+class Base(DeclarativeBase):
19
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
20
+
21
+
22
+def build_engine(database_url: str | None = None) -> Engine:
23
+ url = database_url or get_settings().database_url
24
+ connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {}
25
+ engine = create_engine(url, connect_args=connect_args)
26
+ if url.startswith("sqlite"):
27
+ event.listen(engine, "connect", _enable_sqlite_foreign_keys)
28
+ return engine
29
+
30
+
31
+def _enable_sqlite_foreign_keys(dbapi_connection, _connection_record) -> None:
32
+ cursor = dbapi_connection.cursor()
33
+ cursor.execute("PRAGMA foreign_keys=ON")
34
+ cursor.close()
35
+
36
+
37
+engine = build_engine()
38
+SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
39
+
40
+
41
+def get_session() -> Generator[Session, None, None]:
42
+ with SessionLocal() as session:
43
+ yield session
44
+
backend/src/aram_backend/main.py
new
+38
@@ -0,0 +1,38 @@
1
+from fastapi import FastAPI
2
+
3
+from aram_backend import __version__
4
+from aram_backend.config import get_settings
5
+from aram_backend.models import FiscalYearStatus, StatementType
6
+from aram_backend.schemas import EntityDescriptor, EnumCatalog, HealthResponse, SchemaCatalog
7
+
8
+settings = get_settings()
9
+app = FastAPI(title=settings.app_name, version=__version__)
10
+
11
+
12
+@app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
13
+def health() -> HealthResponse:
14
+ return HealthResponse(status="ok", service=settings.app_name, version=__version__)
15
+
16
+
17
+@app.get("/api/v1/schema/entities", response_model=SchemaCatalog, tags=["schema"])
18
+def schema_entities() -> SchemaCatalog:
19
+ return SchemaCatalog(entities=[
20
+ EntityDescriptor(name="Company", table="companies", purpose="Legal/reporting entity"),
21
+ EntityDescriptor(name="FiscalYear", table="fiscal_years", purpose="Isolated approval and lock boundary"),
22
+ EntityDescriptor(name="SourceDocument", table="source_documents", purpose="Immutable source metadata"),
23
+ EntityDescriptor(name="AccountVersion", table="account_versions", purpose="Year-specific account versions"),
24
+ EntityDescriptor(name="MappingRule", table="mapping_rules", purpose="Versioned note mapping proposals/rules"),
25
+ EntityDescriptor(name="NoteDefinition", table="note_definitions", purpose="Versioned disclosure definitions"),
26
+ EntityDescriptor(name="NoteRow", table="note_rows", purpose="Ordered disclosure rows"),
27
+ EntityDescriptor(name="FinancialStatement", table="financial_statements", purpose="Versioned primary statements"),
28
+ EntityDescriptor(name="StatementLine", table="statement_lines", purpose="Ordered statement lines"),
29
+ ])
30
+
31
+
32
+@app.get("/api/v1/schema/enums", response_model=EnumCatalog, tags=["schema"])
33
+def schema_enums() -> EnumCatalog:
34
+ return EnumCatalog(
35
+ fiscal_year_statuses=[item.value for item in FiscalYearStatus],
36
+ statement_types=[item.value for item in StatementType],
37
+ )
38
+
backend/src/aram_backend/models.py
new
+229
@@ -0,0 +1,229 @@
1
+from __future__ import annotations
2
+
3
+import enum
4
+from datetime import datetime, timezone
5
+from decimal import Decimal
6
+from typing import Any
7
+
8
+from sqlalchemy import (
9
+ JSON,
10
+ CheckConstraint,
11
+ DateTime,
12
+ Enum,
13
+ ForeignKey,
14
+ Integer,
15
+ Numeric,
16
+ String,
17
+ Text,
18
+ UniqueConstraint,
19
+ event,
20
+ inspect,
21
+ select,
22
+)
23
+from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
24
+
25
+from aram_backend.database import Base
26
+
27
+
28
+def utc_now() -> datetime:
29
+ return datetime.now(timezone.utc)
30
+
31
+
32
+class FiscalYearStatus(str, enum.Enum):
33
+ DRAFT = "Draft"
34
+ APPROVED = "Approved"
35
+ LOCKED = "Locked"
36
+
37
+
38
+class StatementType(str, enum.Enum):
39
+ BALANCE_SHEET = "BS"
40
+ INCOME_STATEMENT = "IS"
41
+ CASH_FLOW = "CF"
42
+ EQUITY = "EQ"
43
+
44
+
45
+class TimestampMixin:
46
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
47
+ updated_at: Mapped[datetime] = mapped_column(
48
+ DateTime(timezone=True), default=utc_now, onupdate=utc_now
49
+ )
50
+
51
+
52
+class Company(TimestampMixin, Base):
53
+ __tablename__ = "companies"
54
+ id: Mapped[int] = mapped_column(primary_key=True)
55
+ code: Mapped[str] = mapped_column(String(64), unique=True, index=True)
56
+ name: Mapped[str] = mapped_column(String(255))
57
+ fiscal_years: Mapped[list[FiscalYear]] = relationship(
58
+ back_populates="company", cascade="all, delete-orphan"
59
+ )
60
+
61
+
62
+class FiscalYear(TimestampMixin, Base):
63
+ __tablename__ = "fiscal_years"
64
+ __table_args__ = (
65
+ UniqueConstraint("company_id", "year", name="uq_fiscal_year_company_year"),
66
+ CheckConstraint("year > 0", name="positive_year"),
67
+ )
68
+ id: Mapped[int] = mapped_column(primary_key=True)
69
+ company_id: Mapped[int] = mapped_column(ForeignKey("companies.id", ondelete="RESTRICT"))
70
+ year: Mapped[int] = mapped_column(Integer)
71
+ status: Mapped[FiscalYearStatus] = mapped_column(
72
+ Enum(FiscalYearStatus, native_enum=False), default=FiscalYearStatus.DRAFT
73
+ )
74
+ company: Mapped[Company] = relationship(back_populates="fiscal_years")
75
+
76
+
77
+class YearOwnedMixin:
78
+ year_id: Mapped[int] = mapped_column(ForeignKey("fiscal_years.id", ondelete="RESTRICT"), index=True)
79
+
80
+
81
+class SourceDocument(TimestampMixin, YearOwnedMixin, Base):
82
+ __tablename__ = "source_documents"
83
+ __table_args__ = (
84
+ UniqueConstraint("year_id", "file_hash", name="uq_source_document_year_hash"),
85
+ )
86
+ id: Mapped[int] = mapped_column(primary_key=True)
87
+ filename: Mapped[str] = mapped_column(String(512))
88
+ file_hash: Mapped[str] = mapped_column(String(128))
89
+ document_type: Mapped[str] = mapped_column(String(64))
90
+ uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
91
+
92
+
93
+class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
94
+ __tablename__ = "account_versions"
95
+ __table_args__ = (
96
+ UniqueConstraint("year_id", "account_code", "version", name="uq_account_year_code_version"),
97
+ CheckConstraint("version > 0", name="positive_version"),
98
+ )
99
+ id: Mapped[int] = mapped_column(primary_key=True)
100
+ account_code: Mapped[str] = mapped_column(String(64), index=True)
101
+ account_name: Mapped[str] = mapped_column(String(512))
102
+ version: Mapped[int] = mapped_column(Integer, default=1)
103
+ t1: Mapped[str | None] = mapped_column(String(128))
104
+ t2: Mapped[str | None] = mapped_column(String(128))
105
+ t3: Mapped[str | None] = mapped_column(String(128))
106
+ t4: Mapped[str | None] = mapped_column(String(128))
107
+ nature: Mapped[str | None] = mapped_column(String(64))
108
+
109
+
110
+class NoteDefinition(TimestampMixin, YearOwnedMixin, Base):
111
+ __tablename__ = "note_definitions"
112
+ __table_args__ = (
113
+ UniqueConstraint("year_id", "note_number", "version", name="uq_note_year_number_version"),
114
+ CheckConstraint("version > 0", name="positive_version"),
115
+ )
116
+ id: Mapped[int] = mapped_column(primary_key=True)
117
+ note_number: Mapped[str] = mapped_column(String(32))
118
+ title: Mapped[str] = mapped_column(String(512))
119
+ version: Mapped[int] = mapped_column(Integer, default=1)
120
+ configuration_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict)
121
+ rows: Mapped[list[NoteRow]] = relationship(back_populates="note", cascade="all, delete-orphan")
122
+
123
+
124
+class NoteRow(TimestampMixin, Base):
125
+ __tablename__ = "note_rows"
126
+ __table_args__ = (
127
+ UniqueConstraint("note_id", "row_order", name="uq_note_row_order"),
128
+ CheckConstraint("row_order >= 0", name="nonnegative_row_order"),
129
+ )
130
+ id: Mapped[int] = mapped_column(primary_key=True)
131
+ note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="CASCADE"), index=True)
132
+ row_order: Mapped[int] = mapped_column(Integer)
133
+ label: Mapped[str] = mapped_column(String(512))
134
+ formula_logic: Mapped[str | None] = mapped_column(Text)
135
+ sorting_rule_id: Mapped[str | None] = mapped_column(String(128))
136
+ note: Mapped[NoteDefinition] = relationship(back_populates="rows")
137
+
138
+
139
+class MappingRule(TimestampMixin, YearOwnedMixin, Base):
140
+ __tablename__ = "mapping_rules"
141
+ __table_args__ = (
142
+ UniqueConstraint("year_id", "rule_key", "version", name="uq_mapping_year_key_version"),
143
+ CheckConstraint("version > 0", name="positive_version"),
144
+ )
145
+ id: Mapped[int] = mapped_column(primary_key=True)
146
+ rule_key: Mapped[str] = mapped_column(String(128))
147
+ version: Mapped[int] = mapped_column(Integer, default=1)
148
+ account_code: Mapped[str] = mapped_column(String(64), index=True)
149
+ target_note_id: Mapped[int] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
150
+ mapping_type: Mapped[str] = mapped_column(String(32))
151
+ target_note: Mapped[NoteDefinition] = relationship()
152
+
153
+
154
+class FinancialStatement(TimestampMixin, YearOwnedMixin, Base):
155
+ __tablename__ = "financial_statements"
156
+ __table_args__ = (
157
+ UniqueConstraint("year_id", "statement_type", "version", name="uq_statement_year_type_version"),
158
+ CheckConstraint("version > 0", name="positive_version"),
159
+ )
160
+ id: Mapped[int] = mapped_column(primary_key=True)
161
+ statement_type: Mapped[StatementType] = mapped_column(Enum(StatementType, native_enum=False))
162
+ version: Mapped[int] = mapped_column(Integer, default=1)
163
+ lines: Mapped[list[StatementLine]] = relationship(
164
+ back_populates="statement", cascade="all, delete-orphan"
165
+ )
166
+
167
+
168
+class StatementLine(TimestampMixin, Base):
169
+ __tablename__ = "statement_lines"
170
+ __table_args__ = (
171
+ UniqueConstraint("statement_id", "line_order", name="uq_statement_line_order"),
172
+ CheckConstraint("line_order >= 0", name="nonnegative_line_order"),
173
+ )
174
+ id: Mapped[int] = mapped_column(primary_key=True)
175
+ statement_id: Mapped[int] = mapped_column(ForeignKey("financial_statements.id", ondelete="CASCADE"), index=True)
176
+ line_order: Mapped[int] = mapped_column(Integer)
177
+ line_label: Mapped[str] = mapped_column(String(512))
178
+ target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
179
+ mapped_total: Mapped[Decimal | None] = mapped_column(Numeric(24, 4))
180
+ statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
181
+ target_note: Mapped[NoteDefinition | None] = relationship()
182
+
183
+
184
+def _year_id_for(obj: object) -> int | None:
185
+ if isinstance(obj, FiscalYear):
186
+ return obj.id
187
+ if isinstance(obj, YearOwnedMixin):
188
+ return obj.year_id
189
+ if isinstance(obj, NoteRow):
190
+ return obj.note.year_id if obj.note is not None else None
191
+ if isinstance(obj, StatementLine):
192
+ return obj.statement.year_id if obj.statement is not None else None
193
+ return None
194
+
195
+
196
+@event.listens_for(Session, "before_flush")
197
+def enforce_audit_invariants(session: Session, _flush_context, _instances) -> None:
198
+ for obj in session.dirty:
199
+ if isinstance(obj, FiscalYear):
200
+ history = inspect(obj).attrs.status.history
201
+ if history.deleted:
202
+ old = history.deleted[0]
203
+ allowed = {
204
+ FiscalYearStatus.DRAFT: {FiscalYearStatus.APPROVED},
205
+ FiscalYearStatus.APPROVED: {FiscalYearStatus.LOCKED},
206
+ FiscalYearStatus.LOCKED: set(),
207
+ }
208
+ if obj.status not in allowed[old]:
209
+ raise ValueError(f"Invalid fiscal-year transition: {old.value} -> {obj.status.value}")
210
+
211
+ protected = (session.new | session.dirty | session.deleted)
212
+ for obj in protected:
213
+ if isinstance(obj, FiscalYear):
214
+ continue
215
+ year_id = _year_id_for(obj)
216
+ if year_id is None:
217
+ continue
218
+ status = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
219
+ if status in {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}:
220
+ raise ValueError(
221
+ f"Fiscal year {year_id} is {status.value.lower()} and cannot be mutated"
222
+ )
223
+
224
+ if isinstance(obj, MappingRule) and obj.target_note is not None:
225
+ if obj.target_note.year_id != obj.year_id:
226
+ raise ValueError("Mapping rule and target note must belong to the same fiscal year")
227
+ if isinstance(obj, StatementLine) and obj.target_note is not None:
228
+ if obj.target_note.year_id != obj.statement.year_id:
229
+ raise ValueError("Statement line and target note must belong to the same fiscal year")
backend/src/aram_backend/schemas.py
new
+24
@@ -0,0 +1,24 @@
1
+from pydantic import BaseModel, ConfigDict
2
+
3
+
4
+class HealthResponse(BaseModel):
5
+ status: str
6
+ service: str
7
+ version: str
8
+
9
+
10
+class EntityDescriptor(BaseModel):
11
+ name: str
12
+ table: str
13
+ purpose: str
14
+
15
+
16
+class SchemaCatalog(BaseModel):
17
+ model_config = ConfigDict(frozen=True)
18
+ entities: list[EntityDescriptor]
19
+
20
+
21
+class EnumCatalog(BaseModel):
22
+ fiscal_year_statuses: list[str]
23
+ statement_types: list[str]
24
+
backend/tests/conftest.py
new
+23
@@ -0,0 +1,23 @@
1
+import pytest
2
+from fastapi.testclient import TestClient
3
+from sqlalchemy.orm import Session, sessionmaker
4
+
5
+from aram_backend.database import Base, build_engine
6
+from aram_backend.main import app
7
+
8
+
9
+@pytest.fixture
10
+def session(tmp_path) -> Session:
11
+ engine = build_engine(f"sqlite:///{tmp_path / 'test.db'}")
12
+ Base.metadata.create_all(engine)
13
+ factory = sessionmaker(bind=engine, expire_on_commit=False)
14
+ with factory() as db:
15
+ yield db
16
+ Base.metadata.drop_all(engine)
17
+ engine.dispose()
18
+
19
+
20
+@pytest.fixture
21
+def client() -> TestClient:
22
+ return TestClient(app)
23
+
backend/tests/test_api.py
new
+18
@@ -0,0 +1,18 @@
1
+def test_health(client):
2
+ response = client.get("/api/v1/health")
3
+ assert response.status_code == 200
4
+ assert response.json()["status"] == "ok"
5
+
6
+
7
+def test_read_only_schema_catalog(client):
8
+ entities = client.get("/api/v1/schema/entities")
9
+ assert entities.status_code == 200
10
+ assert len(entities.json()["entities"]) == 9
11
+ assert client.post("/api/v1/schema/entities").status_code == 405
12
+
13
+
14
+def test_enum_catalog(client):
15
+ response = client.get("/api/v1/schema/enums")
16
+ assert response.json()["fiscal_year_statuses"] == ["Draft", "Approved", "Locked"]
17
+ assert response.json()["statement_types"] == ["BS", "IS", "CF", "EQ"]
18
+
backend/tests/test_models.py
new
+111
@@ -0,0 +1,111 @@
1
+import pytest
2
+from sqlalchemy.exc import IntegrityError
3
+
4
+from aram_backend.models import (
5
+ AccountVersion,
6
+ Company,
7
+ FinancialStatement,
8
+ FiscalYear,
9
+ FiscalYearStatus,
10
+ MappingRule,
11
+ NoteDefinition,
12
+ NoteRow,
13
+ SourceDocument,
14
+ StatementLine,
15
+ StatementType,
16
+)
17
+
18
+
19
+def make_year(session, year=1404):
20
+ company = Company(code=f"CO-{year}", name="Test Company")
21
+ fiscal_year = FiscalYear(company=company, year=year)
22
+ session.add(company)
23
+ session.commit()
24
+ return fiscal_year
25
+
26
+
27
+def test_model_relationships(session):
28
+ year = make_year(session)
29
+ note = NoteDefinition(year_id=year.id, note_number="10", title="Assets", version=1)
30
+ note.rows.append(NoteRow(row_order=0, label="Tangible assets"))
31
+ statement = FinancialStatement(year_id=year.id, statement_type=StatementType.BALANCE_SHEET)
32
+ statement.lines.append(StatementLine(line_order=0, line_label="Assets", target_note=note))
33
+ session.add_all([note, statement])
34
+ session.commit()
35
+ assert note.rows[0].note_id == note.id
36
+ assert statement.lines[0].target_note_id == note.id
37
+
38
+
39
+def test_version_uniqueness(session):
40
+ year = make_year(session)
41
+ session.add(AccountVersion(year_id=year.id, account_code="1000", account_name="Cash", version=1))
42
+ session.commit()
43
+ session.add(AccountVersion(year_id=year.id, account_code="1000", account_name="Cash duplicate", version=1))
44
+ with pytest.raises(IntegrityError):
45
+ session.commit()
46
+
47
+
48
+def test_source_document_hash_unique_within_year(session):
49
+ year = make_year(session)
50
+ session.add(SourceDocument(year_id=year.id, filename="a.xlsx", file_hash="abc", document_type="ledger"))
51
+ session.commit()
52
+ session.add(SourceDocument(year_id=year.id, filename="b.xlsx", file_hash="abc", document_type="ledger"))
53
+ with pytest.raises(IntegrityError):
54
+ session.commit()
55
+
56
+
57
+def test_fiscal_year_isolation_for_mapping(session):
58
+ first = make_year(session, 1403)
59
+ second = make_year(session, 1404)
60
+ note = NoteDefinition(year_id=first.id, note_number="10", title="Assets")
61
+ session.add(note)
62
+ session.commit()
63
+ session.add(MappingRule(
64
+ year_id=second.id, rule_key="rule-1", account_code="1000",
65
+ target_note=note, mapping_type="O"
66
+ ))
67
+ with pytest.raises(ValueError, match="same fiscal year"):
68
+ session.commit()
69
+
70
+
71
+def test_locked_year_blocks_mutation(session):
72
+ year = make_year(session)
73
+ year.status = FiscalYearStatus.APPROVED
74
+ session.commit()
75
+ year.status = FiscalYearStatus.LOCKED
76
+ session.commit()
77
+ session.add(AccountVersion(year_id=year.id, account_code="1000", account_name="Cash"))
78
+ with pytest.raises(ValueError, match="locked"):
79
+ session.commit()
80
+
81
+
82
+def test_approved_year_blocks_silent_overwrite(session):
83
+ year = make_year(session)
84
+ account = AccountVersion(
85
+ year_id=year.id, account_code="1000", account_name="Cash"
86
+ )
87
+ session.add(account)
88
+ session.commit()
89
+ year.status = FiscalYearStatus.APPROVED
90
+ session.commit()
91
+ account.account_name = "Silently changed cash"
92
+ with pytest.raises(ValueError, match="approved"):
93
+ session.commit()
94
+
95
+
96
+def test_locked_year_cannot_be_reopened(session):
97
+ year = make_year(session)
98
+ year.status = FiscalYearStatus.APPROVED
99
+ session.commit()
100
+ year.status = FiscalYearStatus.LOCKED
101
+ session.commit()
102
+ year.status = FiscalYearStatus.DRAFT
103
+ with pytest.raises(ValueError, match="Invalid fiscal-year transition"):
104
+ session.commit()
105
+
106
+
107
+def test_invalid_status_skip_is_rejected(session):
108
+ year = make_year(session)
109
+ year.status = FiscalYearStatus.LOCKED
110
+ with pytest.raises(ValueError, match="Invalid fiscal-year transition"):
111
+ session.commit()