Files
finance/backend/alembic/versions/20260922_0003_savings_system.py
T
k1nq 970fe9dacf
Gitea Actions CI / detect (push) Successful in 3s
Gitea Actions CI / Compose & nginx validation (push) Failing after 14s
Gitea Actions CI / Frontend (lint / type / test / build) (push) Successful in 45s
Gitea Actions CI / Backend (lint / type / test / build) (push) Successful in 1m31s
Refactor code for improved readability and consistency across multiple files
2026-09-23 15:22:26 +05:00

187 lines
7.8 KiB
Python

"""Savings system resources, adjustments and reversible conversions."""
import uuid
import sqlalchemy as sa
from alembic import op
revision = "0003"
down_revision = "0002"
branch_labels = None
depends_on = None
OLD_ACCOUNT_KINDS = "kind IN ('cash', 'debit', 'credit')"
NEW_ACCOUNT_KINDS = "kind IN ('cash', 'debit', 'credit', 'savings')"
OLD_OPERATION_TYPES = "type IN ('expense', 'income', 'transfer', 'refund')"
NEW_OPERATION_TYPES = "type IN ('expense', 'income', 'transfer', 'refund', 'adjustment')"
def _has_column(bind, table: str, column: str) -> bool:
inspector = sa.inspect(bind)
return column in {item["name"] for item in inspector.get_columns(table)}
def _check_constraints(bind, table: str) -> list[dict]:
inspector = sa.inspect(bind)
return inspector.get_check_constraints(table)
def _has_unique_constraint(bind, table: str, name: str) -> bool:
inspector = sa.inspect(bind)
return any((item.get("name") or "") == name for item in inspector.get_unique_constraints(table))
def _normalized_sqltext(expression: str) -> str:
return "".join(expression.lower().split()).strip("()")
def _replace_check_constraint(bind, table: str, bare_name: str, expression: str) -> None:
"""Swap a check constraint for a new value list, dialect-safely.
Fresh databases already carry the new constraint from revision 0001's
metadata materialization, so an exact (normalized) expression match is a
no-op. Otherwise the constraint is dropped and recreated by bare name and
the metadata naming convention expands it (batch mode re-applies the
``ck_%(table_name)s_%(constraint_name)s`` template).
"""
wanted = _normalized_sqltext(expression)
existing = next(
(
item
for item in _check_constraints(bind, table)
if (item.get("name") or "").endswith(bare_name)
),
None,
)
if existing is not None and _normalized_sqltext(existing.get("sqltext") or "") == wanted:
return
with op.batch_alter_table(table) as batch_op:
if existing is not None:
batch_op.drop_constraint(bare_name, type_="check")
batch_op.create_check_constraint(bare_name, expression)
def _space_ids(bind) -> list[str]:
return [str(row[0]) for row in bind.execute(sa.text("SELECT id FROM financial_spaces"))]
def _has_row(bind, query: str) -> bool:
return bind.execute(sa.text(query)).first() is not None
def upgrade() -> None:
bind = op.get_bind()
# Revision 0001 materializes the schema from live model metadata, so a
# database created fresh already carries these objects; guard every step.
if not _has_column(bind, "accounts", "system_key"):
op.add_column("accounts", sa.Column("system_key", sa.String(length=64), nullable=True))
if not _has_unique_constraint(bind, "accounts", "uq_accounts_space_system_key"):
with op.batch_alter_table("accounts") as batch_op:
batch_op.create_unique_constraint(
"uq_accounts_space_system_key", ["space_id", "system_key"]
)
_replace_check_constraint(bind, "accounts", "kind_valid", NEW_ACCOUNT_KINDS)
if not _has_column(bind, "operations", "converted_from_expense"):
op.add_column(
"operations",
sa.Column(
"converted_from_expense",
sa.Boolean(),
nullable=False,
server_default=sa.false(),
),
)
if not _has_column(bind, "operations", "previous_category_id"):
op.add_column("operations", sa.Column("previous_category_id", sa.Uuid(), nullable=True))
_replace_check_constraint(bind, "operations", "type_valid", NEW_OPERATION_TYPES)
if not _has_unique_constraint(bind, "categories", "uq_categories_system_pair"):
with op.batch_alter_table("categories") as batch_op:
batch_op.create_unique_constraint(
"uq_categories_system_pair",
["space_id", "system_key", "linked_account_id"],
)
# One system savings account + envelope per existing space. Fresh installs
# have no spaces at migration time and get the pair at space creation.
from sqlalchemy.orm import Session
from app.db.session import set_space_context
from app.ledger.savings import ensure_savings_resources
session = Session(bind=bind)
try:
for space_id in _space_ids(bind):
set_space_context(session, space_id)
ensure_savings_resources(session, space_id=uuid.UUID(hex=space_id))
session.flush()
finally:
session.close()
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
# Refuse before any mutation when 0002 cannot represent the current data.
# This prevents SQLite batch DDL from leaving a partially downgraded schema.
if inspector.has_table("accounts"):
incompatible_queries = {
"adjustment operations": "SELECT 1 FROM operations WHERE type = 'adjustment' LIMIT 1",
"converted expenses": (
"SELECT 1 FROM operations WHERE converted_from_expense = true LIMIT 1"
),
"savings account operations": (
"SELECT 1 FROM operations o JOIN accounts a "
"ON a.id = o.account_id OR a.id = o.counter_account_id "
"WHERE a.system_key = 'savings' LIMIT 1"
),
"savings account postings": (
"SELECT 1 FROM postings p JOIN accounts a ON a.id = p.account_id "
"WHERE a.system_key = 'savings' LIMIT 1"
),
"savings category operations": (
"SELECT 1 FROM operations o JOIN categories c ON c.id = o.category_id "
"WHERE c.system_key = 'savings' LIMIT 1"
),
"savings category funding": (
"SELECT 1 FROM funding_movements f JOIN categories c ON c.id = f.category_id "
"WHERE c.system_key = 'savings' LIMIT 1"
),
"savings category plans": (
"SELECT 1 FROM plan_assignments p JOIN categories c ON c.id = p.category_id "
"WHERE c.system_key = 'savings' LIMIT 1"
),
"non-system savings accounts": (
"SELECT 1 FROM accounts WHERE kind = 'savings' "
"AND (system_key IS NULL OR system_key <> 'savings') LIMIT 1"
),
}
blocked_by = [
label for label, query in incompatible_queries.items() if _has_row(bind, query)
]
if blocked_by:
raise RuntimeError(
"Cannot downgrade savings migration while incompatible data exists: "
+ ", ".join(blocked_by)
)
# The preflight proved these system resources have no dependent history.
bind.execute(sa.text("DELETE FROM categories WHERE system_key = 'savings'"))
bind.execute(sa.text("DELETE FROM accounts WHERE system_key = 'savings'"))
if _has_unique_constraint(bind, "categories", "uq_categories_system_pair"):
with op.batch_alter_table("categories") as batch_op:
batch_op.drop_constraint("uq_categories_system_pair", type_="unique")
_replace_check_constraint(bind, "operations", "type_valid", OLD_OPERATION_TYPES)
if _has_column(bind, "operations", "previous_category_id"):
op.drop_column("operations", "previous_category_id")
if _has_column(bind, "operations", "converted_from_expense"):
op.drop_column("operations", "converted_from_expense")
_replace_check_constraint(bind, "accounts", "kind_valid", OLD_ACCOUNT_KINDS)
if _has_unique_constraint(bind, "accounts", "uq_accounts_space_system_key"):
with op.batch_alter_table("accounts") as batch_op:
batch_op.drop_constraint("uq_accounts_space_system_key", type_="unique")
if _has_column(bind, "accounts", "system_key"):
op.drop_column("accounts", "system_key")