Update file metadata in manifest.json and change MinIO image source in docker-compose.yml

This commit is contained in:
k1nq
2026-09-23 09:23:13 +05:00
parent 8c2b89c80d
commit db4dd7572e
71 changed files with 31011 additions and 8308 deletions
@@ -0,0 +1,194 @@
"""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")
+4 -4
View File
@@ -22,8 +22,8 @@ def category_spend(
return [
{
"categoryId": row["category_id"],
"name": row["category"] if not row["category"].startswith("category.") else None,
"nameKey": row["category"] if row["category"].startswith("category.") else None,
"name": row["name"],
"nameKey": row["name_key"],
"amountKopecks": row["amount_kopecks"],
}
for row in rows
@@ -75,8 +75,8 @@ def plan_fact(month: str, db: Db, context: Context) -> dict:
"items": [
{
"categoryId": row["category_id"],
"name": row["name"] if not str(row["name"]).startswith("category.") else None,
"nameKey": row["name"] if str(row["name"]).startswith("category.") else None,
"name": row.get("name"),
"nameKey": row.get("name_key"),
"plannedKopecks": row["planned"],
"actualKopecks": row["spent"],
}
+12 -7
View File
@@ -7,7 +7,7 @@ from sqlalchemy.orm import Session
from app.budgeting.models import PeriodClosure
from app.budgeting.service import compute_period_state, get_or_create_period
from app.categorization.service import resolve_category_name
from app.categorization.service import resolve_category_name, resolve_category_name_key
from app.ledger.models import Account, Category, Operation
from app.ledger.service import account_balance
@@ -40,16 +40,21 @@ def category_spend(
)
totals[expense.category_id] += expense.amount_kopecks - int(refunded or 0)
categories = {
item.id: resolve_category_name(item)
item.id: item
for item in db.query(Category).filter_by(space_id=space_id).all()
}
return [
{
"category_id": category_id,
"category": (
categories.get(category_id, "category.unnamed")
if category_id is not None
else "category.uncategorized"
"name": (
resolve_category_name(categories[category_id])
if category_id is not None and category_id in categories
else None
),
"name_key": (
resolve_category_name_key(categories[category_id])
if category_id is not None and category_id in categories
else "uncategorized"
),
"amount_kopecks": amount,
}
@@ -66,7 +71,7 @@ def cash_flow(db: Session, *, space_id: uuid.UUID, date_from: date, date_to: dat
totals: dict[tuple[date, str], int] = defaultdict(int)
for operation in operations:
effective = operation.posted_on or operation.occurred_on
if not date_from <= effective <= date_to or operation.type == "transfer":
if not date_from <= effective <= date_to or operation.type in {"transfer", "adjustment"}:
continue
signed = (
operation.amount_kopecks
+74 -30
View File
@@ -1,11 +1,12 @@
import uuid
from datetime import date
from typing import Literal
from typing import Annotated, Literal
from fastapi import APIRouter
from fastapi import APIRouter, Query
from pydantic import BaseModel, Field
from app.budgeting import service
from app.categorization import service as categorization
from app.dependencies import Context, Csrf, Db
router = APIRouter(prefix="/budget", tags=["budget"])
@@ -117,35 +118,78 @@ def categories(month: str, db: Db, context: Context) -> list[dict]:
year, month_number = parse_month(month)
period = period_for(db, context, year, month_number)
state = service.compute_period_state(db, space_id=context.space.id, period=period)
rows = state["monthly_categories"] + [
{
"category_id": row["category_id"],
"name": row["name"],
"planned": 0,
"funded": row["funded_total"],
"spent": row["funded_total"] - row["available"],
"available": row["available"],
}
for row in state["envelopes"]
]
rows = state["monthly_categories"] + state["envelopes"]
category_by_id = {
str(item.id): item for item in service.list_categories(db, space_id=context.space.id)
str(item.id): item
for item in service.list_categories(db, space_id=context.space.id, include_archived=True)
}
return [
{
"id": row["category_id"],
"name": row["name"] if not str(row["name"]).startswith("category.") else None,
"nameKey": row["name"] if str(row["name"]).startswith("category.") else None,
"kind": category_by_id[row["category_id"]].kind,
"archived": False,
"creditAccountId": category_by_id[row["category_id"]].linked_account_id,
"plannedKopecks": row["planned"],
"fundedKopecks": row["funded"],
"spentKopecks": row["spent"],
"availableKopecks": row["available"],
}
for row in rows
]
result = []
for row in rows:
category = category_by_id[row["category_id"]]
result.append(
{
"id": row["category_id"],
"name": row["name"],
"nameKey": row["name_key"],
"kind": category.kind,
"system": row["system"],
"archived": category.archived,
"creditAccountId": category.linked_account_id,
"plannedKopecks": row["planned"],
"fundedKopecks": row["funded"],
"spentKopecks": row["spent"],
"availableKopecks": row["available"],
}
)
return result
def category_definition_json(category) -> dict:
return {
"id": category.id,
"name": categorization.resolve_category_name(category),
"nameKey": categorization.resolve_category_name_key(category),
"kind": category.kind,
"systemKey": category.system_key,
"linkedAccountId": category.linked_account_id,
"archived": category.archived,
}
@router.get("/category-definitions")
def category_definitions(
db: Db,
context: Context,
include_archived: Annotated[bool, Query(alias="includeArchived")] = False,
) -> list[dict]:
items = service.list_categories(
db, space_id=context.space.id, include_archived=include_archived
)
return [category_definition_json(item) for item in items]
class CategoryDefinitionPatchBody(BaseModel):
name: str | None = Field(default=None, min_length=1, max_length=200)
archived: bool | None = None
@router.patch("/category-definitions/{category_id}")
def patch_category_definition(
category_id: uuid.UUID,
body: CategoryDefinitionPatchBody,
db: Db,
context: Context,
_csrf: Csrf,
) -> dict:
category = service.update_category_definition(
db,
space_id=context.space.id,
user=context.user,
category_id=category_id,
name=body.name,
archived=body.archived,
)
return category_definition_json(category)
@router.post("/categories", status_code=201)
@@ -157,7 +201,7 @@ def create_category(body: CategoryBody, db: Db, context: Context, _csrf: Csrf) -
kind=body.kind,
name=body.name,
)
return {"id": category.id, "kind": category.kind, "name": body.name}
return category_definition_json(category)
@router.patch("/categories/{category_id}")
+111 -21
View File
@@ -19,7 +19,7 @@ from app.budgeting.models import (
from app.categorization.service import resolve_category_name
from app.errors import bad_request, conflict, not_found
from app.identity.models import User
from app.ledger.models import Account, Category, Operation
from app.ledger.models import Account, Category, Operation, Posting
from app.ledger.service import ensure_period_open_for_date as _ledger_guard # noqa: F401
@@ -96,8 +96,6 @@ def _closure_snapshot(db: Session, *, space_id: uuid.UUID, year: int, month: int
def _balance_until(db: Session, account: Account, end: date) -> int:
from app.ledger.models import Posting
total = (
db.query(func.coalesce(func.sum(Posting.amount_kopecks), 0))
.join(Operation, Operation.id == Posting.operation_id)
@@ -125,6 +123,10 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
- a refund on a credit card reduces debt and releases any surplus reserve;
- a same-period refund restores the parent purchase's category; a refund on
an uncategorized expense restores the pool;
- transfers into the system savings envelope are carved out of the pool as
its backing; transfers back out return to the pool;
- adjustments reconcile a stored balance through one signed posting and are
excluded from income/expense totals, category spend and cash flow;
- monthly categories fold their residual into the pool at close; savings
envelopes and credit reserves persist via all-time/ snapshot carries.
"""
@@ -132,7 +134,10 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
accounts = db.query(Account).filter_by(space_id=space_id).all()
account_by_id = {a.id: a for a in accounts}
categories = db.query(Category).filter_by(space_id=space_id, archived=False).all()
savings_account = next((a for a in accounts if a.system_key == "savings"), None)
# Archived categories stay in the computation: any plan/funding/operations
# history in the selected period must keep affecting totals.
categories = db.query(Category).filter_by(space_id=space_id).all()
ops = (
db.query(Operation)
@@ -155,6 +160,9 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
payments_by_account: dict[Any, int] = defaultdict(int)
refunds_to_credit_by_account: dict[Any, int] = defaultdict(int)
refund_back_uncategorized_period = 0
# Net transfers into the system savings envelope for this month (+ into,
# - back out). Adjustments are excluded from every flow aggregate.
savings_net_period = 0
for op in ops:
if op.type == "income":
@@ -177,6 +185,11 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
)
if counter is not None and counter.kind == "credit":
payments_by_account[counter.id] += op.amount_kopecks
source = account_by_id.get(op.account_id)
if counter is not None and counter.system_key == "savings":
savings_net_period += op.amount_kopecks
if source is not None and source.system_key == "savings":
savings_net_period -= op.amount_kopecks
elif op.type == "refund":
parent_account = account_by_id.get(op.account_id)
parent = db.get(Operation, op.parent_operation_id) if op.parent_operation_id else None
@@ -224,7 +237,7 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
# All-time envelope consumption up to period end.
for cat in categories:
if cat.kind != "savings_envelope":
if cat.kind != "savings_envelope" or cat.system_key == "savings":
continue
consumed = (
db.query(func.coalesce(func.sum(Operation.amount_kopecks), 0))
@@ -323,6 +336,7 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
- (payments_total - releases_payment_total)
+ surplus_release_total
- funding_total
- savings_net_period
)
monthly_rows: list[dict[str, Any]] = []
@@ -336,22 +350,65 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
{
"category_id": str(cat.id),
"name": resolve_category_name(cat),
"name_key": cat.system_key,
"archived": cat.archived,
"planned": 0,
"funded": funded_period[cat.id],
"spent": monthly_consumption[cat.id],
"available": available,
}
)
# All-time net transfer movement into the system savings account (+ in, - out).
savings_net_all_time = 0
if savings_account is not None:
savings_net_all_time = int(
db.query(func.coalesce(func.sum(Posting.amount_kopecks), 0))
.join(Operation, Operation.id == Posting.operation_id)
.filter(
Posting.account_id == savings_account.id,
Operation.status == "confirmed",
Operation.type == "transfer",
)
.scalar()
or 0
)
envelope_rows: list[dict[str, Any]] = []
for cat in categories:
if cat.kind != "savings_envelope" or cat.system_key == "credit_reserve":
continue
if cat.system_key == "savings":
# System savings envelope: funded shows the net transfer movement of
# the selected month, spent is always zero and available tracks the
# linked account balance at month end (adjustments included).
available = _balance_until(db, savings_account, end) if savings_account else 0
envelope_rows.append(
{
"category_id": str(cat.id),
"name": resolve_category_name(cat),
"name_key": cat.system_key,
"archived": cat.archived,
"system": True,
"funded_total": savings_net_all_time,
"planned": 0,
"funded": savings_net_period,
"spent": 0,
"available": available,
}
)
continue
available = funded_all_time[cat.id] - envelope_consumption_total[cat.id]
envelope_rows.append(
{
"category_id": str(cat.id),
"name": resolve_category_name(cat),
"name_key": cat.system_key,
"archived": cat.archived,
"system": cat.system_key is not None,
"funded_total": funded_all_time[cat.id],
"planned": 0,
"funded": funded_period[cat.id],
"spent": funded_all_time[cat.id] - available,
"available": available,
}
)
@@ -376,7 +433,11 @@ def compute_period_state(db: Session, *, space_id: uuid.UUID, period: BudgetPeri
matched_by_expected[m.expected_income_id] += m.amount_kopecks
uncategorized_count = sum(1 for op in ops if op.type == "expense" and op.category_id is None)
negative_envelopes = [str(row["name"]) for row in envelope_rows if int(row["available"]) < 0]
negative_envelopes = [
str(row["name"] or row["name_key"] or row["category_id"])
for row in envelope_rows
if int(row["available"]) < 0
]
warnings = []
if planned_total > carry_pool + expected_total:
@@ -508,7 +569,10 @@ def create_category(
) -> Category:
if kind not in ("monthly", "savings_envelope"):
raise bad_request("BUDGET_CATEGORY_KIND_INVALID", "Unknown category kind")
category = Category(space_id=space_id, kind=kind, custom_name=name)
trimmed = name.strip()
if not trimmed:
raise bad_request("BUDGET_CATEGORY_NAME_REQUIRED", "Category name is required")
category = Category(space_id=space_id, kind=kind, custom_name=trimmed[:200])
db.add(category)
db.flush()
audit.record(
@@ -554,7 +618,7 @@ def archive_category(
db: Session, *, space_id: uuid.UUID, user: User, category_id: uuid.UUID
) -> Category:
category = get_category(db, space_id=space_id, category_id=category_id)
if category.system_key == "credit_reserve":
if category.system_key is not None:
raise conflict("BUDGET_CATEGORY_SYSTEM", "System categories cannot be archived")
category.archived = True
audit.record(
@@ -567,21 +631,41 @@ def archive_category(
return category
def rename_category(
db: Session, *, space_id: uuid.UUID, user: User, category_id: uuid.UUID, name: str
def update_category_definition(
db: Session,
*,
space_id: uuid.UUID,
user: User,
category_id: uuid.UUID,
name: str | None = None,
archived: bool | None = None,
) -> Category:
"""Rename and/or archive/restore one user category definition.
System categories reject both changes; ``archived=False`` restores an
archived user category. History (plans, funding, operations) is preserved.
"""
category = get_category(db, space_id=space_id, category_id=category_id)
if category.system_key is not None:
category.name_override = name
else:
category.custom_name = name
audit.record(
db,
event_type="category.renamed",
space_id=space_id,
user_id=user.id,
detail={"category_id": str(category.id)},
)
raise conflict("BUDGET_CATEGORY_SYSTEM", "System categories cannot be renamed or archived")
changes: dict[str, bool | str] = {}
if name is not None:
trimmed = name.strip()
if not trimmed:
raise bad_request("BUDGET_CATEGORY_NAME_REQUIRED", "Category name is required")
category.custom_name = trimmed[:200]
changes["renamed"] = True
if archived is not None:
category.archived = archived
changes["archived"] = archived
if changes:
audit.record(
db,
event_type="category.updated",
space_id=space_id,
user_id=user.id,
detail={"category_id": str(category.id), **changes},
)
return category
@@ -597,6 +681,8 @@ def set_assignments(
result = []
for item in items:
category = get_category(db, space_id=space_id, category_id=item["category_id"])
if category.system_key is not None:
raise conflict("BUDGET_CATEGORY_SYSTEM", "System categories cannot be planned")
if category.archived:
raise conflict("BUDGET_CATEGORY_ARCHIVED", "Category is archived")
planned = item["planned_kopecks"]
@@ -713,7 +799,11 @@ def fund(
raise bad_request("BUDGET_FUNDING_KIND_INVALID", "Unknown funding kind")
if amount_kopecks <= 0:
raise bad_request("MONEY_AMOUNT_MUST_BE_POSITIVE", "Amount must be positive")
get_category(db, space_id=space_id, category_id=category_id)
category = get_category(db, space_id=space_id, category_id=category_id)
if category.system_key is not None:
raise conflict("BUDGET_CATEGORY_SYSTEM", "System categories cannot be funded")
if category.archived:
raise conflict("BUDGET_CATEGORY_ARCHIVED", "Category is archived")
movement = FundingMovement(
space_id=space_id,
period_id=period.id,
+12 -5
View File
@@ -5,15 +5,22 @@ from app.errors import conflict, not_found
from app.ledger.models import Category
def resolve_category_name(category: Category) -> str:
"""Standard categories resolve to a translation key; overrides/customs are literal."""
def resolve_category_name(category: Category) -> str | None:
"""Literal display name, or None when the name localizes via the system key.
System categories serialize as a pure ``nameKey`` (for example ``savings``),
never as a ``category.*`` prefixed string.
"""
if category.custom_name is not None:
return category.custom_name
if category.name_override is not None:
return category.name_override
if category.system_key is not None:
return f"category.{category.system_key}"
return "category.unnamed"
return None
def resolve_category_name_key(category: Category) -> str | None:
"""Pure localization key for system categories; None for user categories."""
return category.system_key
def get_income_source(db: Session, *, space_id, income_source_id) -> IncomeSource:
+44 -1
View File
@@ -29,6 +29,40 @@ DESCRIPTION_HEADERS = ("описание", "назначение", "коммен
CATEGORY_HEADERS = ("категория",)
ACCOUNT_HEADERS = ("номер карты", "номер счёта", "карта")
# Alfa «Копилка для сдачи» round-up service. The rule fails closed: only an
# exact normalized phrase with a source account equal to the statement account
# and an outgoing posted row produces the savings_transfer decision hint. The
# account numbers in the pattern are part of the bank's phrasing contract and
# are matched against the statement header, never hardcoded per user.
SAVINGS_SERVICE_RE = re.compile(
r"перечисление средств в рамках услуги \"копилка для сдачи\" "
r"со счета (\d{20}) на счет (\d{20})"
)
def _savings_rule_text(value: str) -> str:
text = value.replace("\u00a0", " ").replace("ё", "е").replace("Ё", "Е").lower()
text = re.sub(r"[«»„“”\"']", '"', text)
return " ".join(text.split())
def detect_savings_transfer(
description: str | None,
*,
direction: str,
bank_status: str,
statement_account: str,
) -> bool:
if direction != DIRECTION_OUT or bank_status != BANK_STATUS_POSTED or not description:
return False
match = SAVINGS_SERVICE_RE.search(_savings_rule_text(description))
if match is None:
return False
statement_digits = re.sub(r"\D", "", statement_account or "")
if not statement_digits:
return False
return match.group(1) == statement_digits
class AlfaXlsxAdapterBase:
"""Alfa statement contract: XLSX with a header row and bank marker 'Альфа'."""
@@ -277,7 +311,9 @@ class AlfaDebitXlsxAdapter:
header_idx, columns = _debit_find_header(self, rows)
meta = _debit_header_metadata(self, rows, header_idx)
period_start, period_end = _debit_statement_period(self, rows, header_idx)
parsed = _debit_operation_rows(self, rows, header_idx, columns)
parsed = _debit_operation_rows(
self, rows, header_idx, columns, statement_account=meta["account"]
)
if not parsed:
raise UnsupportedStatementLayout("no operation rows found in Alfa statement")
return StatementDraft(
@@ -413,6 +449,7 @@ def _debit_operation_rows(
rows: list[tuple],
header_idx: int,
columns: dict[str, int],
statement_account: str = "",
) -> list[SourceRow]:
parsed: list[SourceRow] = []
separated_from_operations = False
@@ -475,6 +512,12 @@ def _debit_operation_rows(
row_ref=f"sheet0:row{offset}",
warnings=tuple(warnings),
bank_status=bank_status,
savings_transfer=detect_savings_transfer(
description,
direction=direction,
bank_status=bank_status,
statement_account=statement_account,
),
)
)
separated_from_operations = False
+2 -1
View File
@@ -16,7 +16,7 @@ BANK_STATUSES = (BANK_STATUS_POSTED, BANK_STATUS_HOLD)
PARSER_VERSION = "1"
# Per-contract versions: bumped for the rewritten evidenced contracts so old
# parse runs can never be confused with the new canonical output.
ALFA_DEBIT_XLSX_VERSION = "2"
ALFA_DEBIT_XLSX_VERSION = "3"
OZON_DEBIT_PDF_VERSION = "2"
ROCKETBANK_DEBIT_PDF_VERSION = "2"
@@ -35,6 +35,7 @@ class SourceRow:
row_ref: str
warnings: tuple[str, ...] = ()
bank_status: str = BANK_STATUS_POSTED
savings_transfer: bool = False
def __post_init__(self) -> None:
if self.amount_kopecks < 0:
+36 -6
View File
@@ -1,7 +1,7 @@
import uuid
from typing import Annotated, Any
from fastapi import APIRouter, File, Form, UploadFile
from fastapi import APIRouter, File, Form, Query, UploadFile
from pydantic import BaseModel, ConfigDict, Field
from app.dependencies import Context, Csrf, Db
@@ -41,7 +41,7 @@ class HoldResolveBody(BaseModel):
account_id: uuid.UUID | None = Field(default=None, alias="accountId")
def summary(document: Any) -> dict:
def summary(document: Any, *, unresolved_hold_count: int = 0) -> dict:
return {
"id": document.id,
"fileName": document.original_filename,
@@ -52,14 +52,33 @@ def summary(document: Any) -> dict:
"periodFrom": None,
"periodTo": None,
"needsAccountMapping": document.needs_account_mapping,
"unresolvedHoldCount": unresolved_hold_count,
"errorCode": document.error_code,
"createdAt": document.created_at,
}
@router.get("")
def imports(db: Db, context: Context) -> list[dict]:
return [summary(item) for item in service.list_documents(db, space_id=context.space.id)]
def imports(
db: Db,
context: Context,
month: Annotated[str | None, Query()] = None,
) -> list[dict]:
month_filter = service.parse_month_filter(month)
documents = service.list_documents(db, space_id=context.space.id)
hold_counts = service.unresolved_hold_counts(
db,
space_id=context.space.id,
document_ids=[item.id for item in documents],
month=month_filter,
)
result = []
for item in documents:
hold_count = hold_counts.get(item.id, 0)
if month_filter is not None and item.status == "confirmed" and hold_count == 0:
continue
result.append(summary(item, unresolved_hold_count=hold_count))
return result
@router.post("", status_code=202)
@@ -106,7 +125,12 @@ async def upload(
def detail(document_id: uuid.UUID, db: Db, context: Context) -> dict:
raw = service.document_detail(db, space_id=context.space.id, document_id=document_id)
document = service._document(db, space_id=context.space.id, document_id=document_id)
base = summary(document)
base = summary(
document,
unresolved_hold_count=len(
service.unresolved_holds(db, space_id=context.space.id, document=document)
),
)
reconciliation = raw.get("reconciliation") or {}
rows = []
pending_candidate_row_ids: set[uuid.UUID] = set()
@@ -204,6 +228,7 @@ def detail(document_id: uuid.UUID, db: Db, context: Context) -> dict:
"discard": sum(row["decision"] == "discard" for row in rows),
"duplicate": sum(row["decision"] == "duplicate" for row in rows),
"transfer": sum(row["decision"] == "transfer" for row in rows),
"savingsTransfer": sum(row["decision"] == "savings_transfer" for row in rows),
"pending": sum(row["decision"] == "pending" for row in rows),
},
}
@@ -217,7 +242,12 @@ def review(document_id: uuid.UUID, body: ReviewBody, db: Db, context: Context, _
document_id=document_id,
**body.model_dump(),
)
return summary(document)
return summary(
document,
unresolved_hold_count=len(
service.unresolved_holds(db, space_id=context.space.id, document=document)
),
)
@router.patch("/{document_id}/rows/{row_id}")
+116 -1
View File
@@ -5,6 +5,7 @@ from datetime import date, timedelta
from pathlib import Path
from typing import Any
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.audit import service as audit
@@ -164,6 +165,7 @@ def _source_from_row(
or row.direction not in {"in", "out"}
),
record_fp=record_fingerprint(row.occurred_on, abs(row.amount_kopecks), row.description),
review_decision="savings_transfer" if row.savings_transfer else "create",
)
@@ -522,6 +524,72 @@ def list_documents(db: Session, *, space_id: uuid.UUID) -> list[StatementDocumen
)
def unresolved_holds(
db: Session, *, space_id: uuid.UUID, document: StatementDocument
) -> list[SourceRecord]:
"""Unresolved HOLD rows of the document's active parse run."""
if not document.active_parse_run_id:
return []
return (
db.query(SourceRecord)
.outerjoin(HoldResolution, HoldResolution.hold_source_record_id == SourceRecord.id)
.filter(
SourceRecord.space_id == space_id,
SourceRecord.parse_run_id == document.active_parse_run_id,
SourceRecord.bank_status == "hold",
HoldResolution.id.is_(None),
)
.all()
)
def unresolved_hold_counts(
db: Session,
*,
space_id: uuid.UUID,
document_ids: list[uuid.UUID],
month: tuple[int, int] | None = None,
) -> dict[uuid.UUID, int]:
"""Count unresolved HOLD rows for active parse runs in one query."""
if not document_ids:
return {}
query = (
db.query(StatementDocument.id, func.count(SourceRecord.id))
.join(
SourceRecord,
(SourceRecord.document_id == StatementDocument.id)
& (SourceRecord.parse_run_id == StatementDocument.active_parse_run_id),
)
.outerjoin(HoldResolution, HoldResolution.hold_source_record_id == SourceRecord.id)
.filter(
StatementDocument.space_id == space_id,
StatementDocument.id.in_(document_ids),
SourceRecord.bank_status == "hold",
HoldResolution.id.is_(None),
)
)
if month is not None:
year, month_number = month
start = date(year, month_number, 1)
end = date(year + 1, 1, 1) if month_number == 12 else date(year, month_number + 1, 1)
query = query.filter(SourceRecord.occurred_on >= start, SourceRecord.occurred_on < end)
return {document_id: count for document_id, count in query.group_by(StatementDocument.id)}
def parse_month_filter(value: str | None) -> tuple[int, int] | None:
if value is None:
return None
try:
year_text, month_text = value.split("-", 1)
year, month = int(year_text), int(month_text)
except (ValueError, AttributeError) as exc:
raise bad_request("IMPORT_MONTH_INVALID", "Month filter must use YYYY-MM") from exc
if not 1 <= month <= 12 or year < 2000:
raise bad_request("IMPORT_MONTH_INVALID", "Month filter must use YYYY-MM")
return year, month
def document_detail(db: Session, *, space_id: uuid.UUID, document_id: uuid.UUID) -> dict:
document = _document(db, space_id=space_id, document_id=document_id)
records = []
@@ -622,8 +690,17 @@ def decide_source_record(
)
if source is None:
raise not_found("IMPORT_SOURCE_RECORD_NOT_FOUND", "Import row not found")
if decision not in {"create", "discard", "duplicate", "transfer"}:
if decision not in {"create", "discard", "duplicate", "transfer", "savings_transfer"}:
raise conflict("IMPORT_DECISION_INVALID", "Unsupported row decision")
if source.bank_status == "hold" and decision != "discard":
raise conflict("IMPORT_DECISION_INVALID", "HOLD rows are resolved via hold resolution")
if decision == "savings_transfer" and (
source.bank_status != "posted" or source.direction != "out"
):
raise conflict(
"IMPORT_DECISION_INVALID",
"Only posted outflows can be transferred to savings",
)
candidates = db.query(DedupCandidate).filter_by(source_record_id=source.id).all()
matching = [item for item in candidates if item.candidate_kind == decision]
if decision == "duplicate" and duplicate_operation_id is None and len(matching) == 1:
@@ -684,6 +761,11 @@ def set_review_confirmation(
account = db.query(Account).filter_by(id=account_id, space_id=space_id).one_or_none()
if account is None:
raise not_found("LEDGER_ACCOUNT_NOT_FOUND", "Account not found")
if account.system_key is not None:
raise conflict(
"IMPORT_SYSTEM_ACCOUNT_INVALID",
"System accounts cannot be used as statement accounts",
)
if confirmed_without_full_reconciliation and not reason:
raise conflict("IMPORT_RECONCILIATION_REASON_REQUIRED", "A confirmation reason is required")
document.account_id = account.id
@@ -988,6 +1070,39 @@ def confirm_document(
]
)
continue
if source.review_decision == "savings_transfer":
from app.ledger.savings import ensure_savings_resources
savings_account, _savings_category = ensure_savings_resources(
db, space_id=space_id
)
if document.account_id == savings_account.id:
raise conflict(
"IMPORT_SAVINGS_SOURCE_INVALID",
"The mapped statement account cannot be the savings account itself",
)
assert source.occurred_on is not None
operation = create_transfer(
db,
space_id=space_id,
user=user,
source_account_id=document.account_id,
target_account_id=savings_account.id,
amount_kopecks=source.amount_kopecks,
occurred_on=source.occurred_on,
posted_on=source.posted_on,
description=source.description,
request_key=f"import-savings:{source.id}",
)
db.add(
SourceRecordLink(
space_id=space_id,
source_record_id=source.id,
operation_id=operation.id,
kind="created",
)
)
continue
if source.review_decision == "duplicate" and source.duplicate_operation_id:
duplicate_operation = (
db.query(Operation)
+16 -4
View File
@@ -17,9 +17,9 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base, PkMixin, TimestampMixin
ACCOUNT_KINDS = ("cash", "debit", "credit")
ACCOUNT_KINDS = ("cash", "debit", "credit", "savings")
ACCOUNT_STATUSES = ("active", "archived")
OPERATION_TYPES = ("expense", "income", "transfer", "refund")
OPERATION_TYPES = ("expense", "income", "transfer", "refund", "adjustment")
OPERATION_STATUSES = ("confirmed", "voided")
@@ -28,10 +28,13 @@ class Account(Base, PkMixin, TimestampMixin):
__tablename__ = "accounts"
__table_args__ = (
CheckConstraint("kind IN ('cash', 'debit', 'credit')", name="kind_valid"),
CheckConstraint(
"kind IN ('cash', 'debit', 'credit', 'savings')", name="kind_valid"
),
CheckConstraint("status IN ('active', 'archived')", name="status_valid"),
CheckConstraint("currency = 'RUB'", name="currency_rub_only"),
UniqueConstraint("space_id", "id", name="uq_accounts_space_id"),
UniqueConstraint("space_id", "system_key", name="uq_accounts_space_system_key"),
)
space_id: Mapped[uuid.UUID] = mapped_column(
@@ -45,6 +48,7 @@ class Account(Base, PkMixin, TimestampMixin):
bank_code: Mapped[str | None] = mapped_column(String(32), nullable=True)
masked_identifier: Mapped[str | None] = mapped_column(String(32), nullable=True)
fingerprint: Mapped[str | None] = mapped_column(String(128), nullable=True)
system_key: Mapped[str | None] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
@@ -56,7 +60,10 @@ class Operation(Base, PkMixin, TimestampMixin):
__tablename__ = "operations"
__table_args__ = (
CheckConstraint("type IN ('expense', 'income', 'transfer', 'refund')", name="type_valid"),
CheckConstraint(
"type IN ('expense', 'income', 'transfer', 'refund', 'adjustment')",
name="type_valid",
),
CheckConstraint("status IN ('confirmed', 'voided')", name="status_valid"),
CheckConstraint("amount_kopecks > 0", name="amount_positive"),
CheckConstraint(
@@ -114,6 +121,8 @@ class Operation(Base, PkMixin, TimestampMixin):
description: Mapped[str | None] = mapped_column(String(500), nullable=True)
void_reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
request_key: Mapped[str | None] = mapped_column(String(120), nullable=True)
converted_from_expense: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
previous_category_id: Mapped[uuid.UUID | None] = mapped_column(Uuid, nullable=True)
created_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
Uuid, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
@@ -168,6 +177,9 @@ class Category(Base, PkMixin, TimestampMixin):
name="fk_categories_linked_account_tenant",
),
UniqueConstraint("space_id", "id", name="uq_categories_space_id"),
UniqueConstraint(
"space_id", "system_key", "linked_account_id", name="uq_categories_system_pair"
),
)
space_id: Mapped[uuid.UUID] = mapped_column(
+54
View File
@@ -52,6 +52,14 @@ class OperationPatchBody(BaseModel):
category_id: uuid.UUID | None = Field(default=None, alias="categoryId")
class AdjustBalanceBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
target_balance_kopecks: int = Field(ge=0, alias="targetBalanceKopecks")
occurred_on: date = Field(alias="occurredOn")
reason: str = Field(min_length=1, max_length=500)
def account_json(db: Db, account: Any) -> dict:
return {
"id": account.id,
@@ -62,6 +70,8 @@ def account_json(db: Db, account: Any) -> dict:
"openedOn": account.opened_on,
"bankCode": account.bank_code,
"maskedNumber": account.masked_identifier,
"systemKey": account.system_key,
"nameKey": f"account.{account.system_key}" if account.system_key else None,
"status": account.status,
"balanceKopecks": service.account_balance(db, account),
"version": account.version,
@@ -91,6 +101,7 @@ def operation_json(db: Db, operation: Any) -> dict:
"postedOn": operation.posted_on,
"description": operation.description,
"voidReason": operation.void_reason,
"convertedFromExpense": operation.converted_from_expense,
"version": operation.version,
"createdAt": operation.created_at,
}
@@ -276,3 +287,46 @@ def patch_operation(
category_id=body.category_id,
)
return operation_json(db, operation)
@router.post("/accounts/{account_id}/adjust-balance")
def adjust_balance(
account_id: uuid.UUID, body: AdjustBalanceBody, db: Db, context: Context, _csrf: Csrf
) -> dict:
from app.ledger import savings
operation, old_balance, new_balance = savings.adjust_balance(
db,
space_id=context.space.id,
user=context.user,
account_id=account_id,
target_balance_kopecks=body.target_balance_kopecks,
occurred_on=body.occurred_on,
reason=body.reason,
)
payload = operation_json(db, operation)
payload["oldBalanceKopecks"] = old_balance
payload["newBalanceKopecks"] = new_balance
return payload
@router.post("/operations/{operation_id}/savings-transfer")
def savings_transfer(operation_id: uuid.UUID, db: Db, context: Context, _csrf: Csrf) -> dict:
from app.ledger import savings
operation = savings.convert_expense_to_savings(
db, space_id=context.space.id, user=context.user, operation_id=operation_id
)
return operation_json(db, operation)
@router.post("/operations/{operation_id}/savings-transfer/revert")
def savings_transfer_revert(
operation_id: uuid.UUID, db: Db, context: Context, _csrf: Csrf
) -> dict:
from app.ledger import savings
operation = savings.revert_savings_conversion(
db, space_id=context.space.id, user=context.user, operation_id=operation_id
)
return operation_json(db, operation)
+334
View File
@@ -0,0 +1,334 @@
"""System savings account/envelope, balance adjustments and reversible conversions.
The savings "convert" identity is defined exclusively by ``system_key``:
user-created accounts or categories that merely share the name «Накопления»
are never captured. Every command is tenant-scoped, period-guarded and
audited; balances stay derived (postings only, never stored mutations).
"""
import uuid
from datetime import date
from sqlalchemy.orm import Session
from app.audit import service as audit
from app.errors import bad_request, conflict, not_found
from app.identity.models import User
from app.ledger.models import Account, Category, Operation, Posting
SAVINGS_SYSTEM_KEY = "savings"
SAVINGS_ACCOUNT_NAME = "Накопления"
def get_savings_account(db: Session, *, space_id: uuid.UUID) -> Account | None:
return (
db.query(Account)
.filter_by(space_id=space_id, system_key=SAVINGS_SYSTEM_KEY)
.one_or_none()
)
def _savings_category(db: Session, *, space_id: uuid.UUID) -> Category | None:
return (
db.query(Category)
.filter_by(space_id=space_id, system_key=SAVINGS_SYSTEM_KEY)
.one_or_none()
)
def ensure_savings_resources(db: Session, *, space_id: uuid.UUID) -> tuple[Account, Category]:
"""Idempotently return the single system savings account and its envelope.
Any duplicate or inconsistent system pair is an explicit conflict, never a
random pick: identity is keyed by ``system_key`` only.
"""
accounts = db.query(Account).filter_by(space_id=space_id, system_key=SAVINGS_SYSTEM_KEY).all()
if len(accounts) > 1:
raise conflict(
"LEDGER_SAVINGS_CONFLICT",
"Multiple system savings accounts exist in this space",
)
account: Account | None = accounts[0] if accounts else None
created = False
if account is None:
account = Account(
space_id=space_id,
name=SAVINGS_ACCOUNT_NAME,
kind="savings",
system_key=SAVINGS_SYSTEM_KEY,
opened_on=date.today(),
opening_amount_kopecks=0,
)
db.add(account)
db.flush()
created = True
categories = (
db.query(Category).filter_by(space_id=space_id, system_key=SAVINGS_SYSTEM_KEY).all()
)
if len(categories) > 1:
raise conflict(
"LEDGER_SAVINGS_CONFLICT",
"Multiple system savings categories exist in this space",
)
category: Category | None = categories[0] if categories else None
if category is not None and category.linked_account_id != account.id:
raise conflict(
"LEDGER_SAVINGS_CONFLICT",
"System savings category is linked to a different account",
)
if category is None:
category = Category(
space_id=space_id,
kind="savings_envelope",
system_key=SAVINGS_SYSTEM_KEY,
linked_account_id=account.id,
)
db.add(category)
db.flush()
created = True
if created:
audit.record(
db,
event_type="savings.resources_ensured",
space_id=space_id,
detail={
"account_id": str(account.id),
"category_id": str(category.id),
},
)
return account, category
def transfer_category_for_accounts(
db: Session, *, space_id: uuid.UUID, source: Account, target: Account
) -> Category | None:
"""System category for a manual transfer touching the savings account."""
if SAVINGS_SYSTEM_KEY not in {source.system_key, target.system_key}:
return None
_, category = ensure_savings_resources(db, space_id=space_id)
return category
def adjust_balance(
db: Session,
*,
space_id: uuid.UUID,
user: User,
account_id: uuid.UUID,
target_balance_kopecks: int,
occurred_on: date,
reason: str,
) -> tuple[Operation, int, int]:
"""Reconcile a derived balance with reality via one audited adjustment.
The operation carries one signed posting for the delta; ``amount_kopecks``
stays positive and the sign lives in the posting. Adjustments never touch
income/expense totals, category spend, cash flow or the budget pool.
"""
if not reason.strip():
raise bad_request("LEDGER_ADJUST_REASON_REQUIRED", "An adjustment reason is required")
account = (
db.query(Account)
.filter_by(id=account_id, space_id=space_id)
.with_for_update()
.one_or_none()
)
if account is None:
raise not_found("LEDGER_ACCOUNT_NOT_FOUND", "Account not found")
if account.status != "active":
raise conflict("LEDGER_ACCOUNT_ARCHIVED", "Account is archived")
if account.kind == "credit":
raise conflict(
"LEDGER_ADJUST_CREDIT_UNSUPPORTED",
"Credit account balances cannot be adjusted with a non-negative target",
)
if target_balance_kopecks < 0:
raise bad_request(
"LEDGER_ADJUST_TARGET_NEGATIVE", "Target balance cannot be negative"
)
from app.ledger.service import account_balance, ensure_period_open_for_date
ensure_period_open_for_date(db, space_id=space_id, day=occurred_on)
old_balance = account_balance(db, account)
delta = target_balance_kopecks - old_balance
if delta == 0:
raise conflict(
"LEDGER_ADJUST_NOOP",
"Balance already equals the target; nothing to adjust",
details={"balance_kopecks": old_balance},
)
operation = Operation(
space_id=space_id,
type="adjustment",
amount_kopecks=abs(delta),
account_id=account.id,
occurred_on=occurred_on,
description=reason.strip(),
created_by_user_id=user.id,
)
db.add(operation)
db.flush()
db.add(
Posting(
space_id=space_id,
operation_id=operation.id,
account_id=account.id,
amount_kopecks=delta,
)
)
audit.record(
db,
event_type="account.balance_adjusted",
space_id=space_id,
user_id=user.id,
detail={
"account_id": str(account.id),
"operation_id": str(operation.id),
"old_balance_kopecks": old_balance,
"new_balance_kopecks": target_balance_kopecks,
"delta_kopecks": delta,
"reason": reason.strip(),
},
)
return operation, old_balance, target_balance_kopecks
def convert_expense_to_savings(
db: Session, *, space_id: uuid.UUID, user: User, operation_id: uuid.UUID
) -> Operation:
"""Turn a confirmed expense into a transfer into the system savings account.
Keeps the original negative posting plus description, payee, request key
and import provenance; adds one positive posting on the savings account and
remembers the previous category for exact reversion.
"""
operation = (
db.query(Operation)
.filter_by(id=operation_id, space_id=space_id)
.with_for_update()
.one_or_none()
)
if operation is None:
raise not_found("LEDGER_OPERATION_NOT_FOUND", "Operation not found")
if operation.status != "confirmed":
raise conflict(
"LEDGER_SAVINGS_CONVERT_INVALID",
"Only confirmed operations can be converted",
)
if operation.type != "expense":
raise conflict(
"LEDGER_SAVINGS_CONVERT_INVALID",
"Only expenses can be converted into savings transfers",
)
if operation.converted_from_expense:
raise conflict(
"LEDGER_SAVINGS_CONVERT_INVALID",
"Operation is already a savings transfer",
)
source_account = (
db.query(Account).filter_by(id=operation.account_id, space_id=space_id).one_or_none()
)
if source_account is None:
raise not_found("LEDGER_ACCOUNT_NOT_FOUND", "Account not found")
if source_account.system_key is not None:
raise conflict(
"LEDGER_SAVINGS_CONVERT_INVALID",
"Operations on system accounts cannot be converted",
)
confirmed_refund = (
db.query(Operation.id)
.filter_by(
space_id=space_id,
parent_operation_id=operation.id,
type="refund",
status="confirmed",
)
.first()
)
if confirmed_refund is not None:
raise conflict(
"LEDGER_SAVINGS_CONVERT_HAS_REFUNDS",
"Expenses with confirmed refunds cannot be converted into savings transfers",
)
from app.ledger.service import ensure_period_open_for_date
ensure_period_open_for_date(db, space_id=space_id, day=operation.occurred_on)
savings_account, savings_category = ensure_savings_resources(db, space_id=space_id)
previous_category_id = operation.category_id
operation.previous_category_id = previous_category_id
operation.converted_from_expense = True
operation.type = "transfer"
operation.counter_account_id = savings_account.id
operation.category_id = savings_category.id
db.add(
Posting(
space_id=space_id,
operation_id=operation.id,
account_id=savings_account.id,
amount_kopecks=operation.amount_kopecks,
)
)
audit.record(
db,
event_type="operation.savings_transfer",
space_id=space_id,
user_id=user.id,
detail={
"operation_id": str(operation.id),
"savings_account_id": str(savings_account.id),
"amount_kopecks": operation.amount_kopecks,
"previous_category_id": (
str(previous_category_id) if previous_category_id else None
),
},
)
return operation
def revert_savings_conversion(
db: Session, *, space_id: uuid.UUID, user: User, operation_id: uuid.UUID
) -> Operation:
"""Undo a marked conversion: restore the expense type, category and postings."""
operation = (
db.query(Operation)
.filter_by(id=operation_id, space_id=space_id)
.with_for_update()
.one_or_none()
)
if operation is None:
raise not_found("LEDGER_OPERATION_NOT_FOUND", "Operation not found")
if operation.status != "confirmed":
raise conflict(
"LEDGER_SAVINGS_REVERT_INVALID",
"Only confirmed operations can be reverted",
)
if operation.type != "transfer" or not operation.converted_from_expense:
raise conflict(
"LEDGER_SAVINGS_REVERT_INVALID",
"Only converted expenses can be reverted from savings",
)
from app.ledger.service import ensure_period_open_for_date
ensure_period_open_for_date(db, space_id=space_id, day=operation.occurred_on)
counter_account_id = operation.counter_account_id
if counter_account_id is not None:
savings_posting = (
db.query(Posting)
.filter_by(operation_id=operation.id, account_id=counter_account_id)
.one_or_none()
)
if savings_posting is not None:
db.delete(savings_posting)
operation.type = "expense"
operation.counter_account_id = None
operation.category_id = operation.previous_category_id
operation.converted_from_expense = False
operation.previous_category_id = None
audit.record(
db,
event_type="operation.savings_transfer_reverted",
space_id=space_id,
user_id=user.id,
detail={"operation_id": str(operation.id)},
)
return operation
+24
View File
@@ -48,6 +48,15 @@ def _require_active_account(db: Session, *, space_id: uuid.UUID, account_id: uui
return account
def _reject_system_account(account: Account) -> None:
"""System accounts (savings) are journal-internal and never statement-facing."""
if account.system_key is not None:
raise bad_request(
"LEDGER_SYSTEM_ACCOUNT_NOT_EXTERNAL",
"System accounts cannot host external income or expense operations",
)
def _validate_category(db: Session, *, space_id: uuid.UUID, category_id: uuid.UUID | None) -> None:
if category_id is None:
return
@@ -58,6 +67,11 @@ def _validate_category(db: Session, *, space_id: uuid.UUID, category_id: uuid.UU
raise not_found("BUDGET_CATEGORY_NOT_FOUND", "Category not found")
if category.archived:
raise conflict("BUDGET_CATEGORY_ARCHIVED", "Category is archived")
if category.system_key is not None:
raise conflict(
"BUDGET_CATEGORY_SYSTEM",
"System categories cannot be assigned to regular operations",
)
def account_balance(db: Session, account: Account) -> int:
@@ -155,6 +169,7 @@ def create_expense(
if existing is not None:
return existing
account = _require_active_account(db, space_id=space_id, account_id=account_id)
_reject_system_account(account)
_validate_category(db, space_id=space_id, category_id=category_id)
ensure_period_open_for_date(db, space_id=space_id, day=occurred_on)
operation = Operation(
@@ -210,6 +225,7 @@ def create_income(
if existing is not None:
return existing
account = _require_active_account(db, space_id=space_id, account_id=account_id)
_reject_system_account(account)
if income_source_id is not None:
categorization.get_income_source(db, space_id=space_id, income_source_id=income_source_id)
ensure_period_open_for_date(db, space_id=space_id, day=occurred_on)
@@ -268,12 +284,16 @@ def create_transfer(
source = _require_active_account(db, space_id=space_id, account_id=source_account_id)
target = _require_active_account(db, space_id=space_id, account_id=target_account_id)
ensure_period_open_for_date(db, space_id=space_id, day=occurred_on)
from app.ledger.savings import transfer_category_for_accounts
category = transfer_category_for_accounts(db, space_id=space_id, source=source, target=target)
operation = Operation(
space_id=space_id,
type="transfer",
amount_kopecks=amount_kopecks,
account_id=source.id,
counter_account_id=target.id,
category_id=category.id if category is not None else None,
occurred_on=occurred_on,
posted_on=posted_on,
description=description,
@@ -463,6 +483,8 @@ def archive_account(
db: Session, *, space_id: uuid.UUID, user: User, account_id: uuid.UUID
) -> Account:
account = get_account(db, space_id=space_id, account_id=account_id)
if account.system_key is not None:
raise conflict("LEDGER_ACCOUNT_SYSTEM", "System accounts cannot be archived")
if account.status == "archived":
return account
if account_balance(db, account) != 0:
@@ -483,6 +505,8 @@ def archive_account(
def delete_account(db: Session, *, space_id: uuid.UUID, user: User, account_id: uuid.UUID) -> None:
account = get_account(db, space_id=space_id, account_id=account_id)
if account.system_key is not None:
raise conflict("LEDGER_ACCOUNT_SYSTEM", "System accounts cannot be deleted")
used = (
db.query(Operation.id)
.filter((Operation.account_id == account.id) | (Operation.counter_account_id == account.id))
+3
View File
@@ -15,6 +15,9 @@ def create_space(db: Session, *, user: User, name: str) -> FinancialSpace:
db.flush()
set_space_context(db, space.id)
db.add(Membership(space_id=space.id, user_id=user.id, role="owner"))
from app.ledger.savings import ensure_savings_resources
ensure_savings_resources(db, space_id=space.id)
audit.record(db, event_type="space.created", space_id=space.id, user_id=user.id)
return space
+122 -2
View File
@@ -14,7 +14,11 @@ from openpyxl import Workbook
from app.errors import AppError
from app.imports.adapters import ADAPTERS, detect_adapter, magic_kind
from app.imports.adapters import alfa_xlsx as alfa_module
from app.imports.adapters.alfa_xlsx import AlfaCreditXlsxAdapter, AlfaDebitXlsxAdapter
from app.imports.adapters.alfa_xlsx import (
AlfaCreditXlsxAdapter,
AlfaDebitXlsxAdapter,
detect_savings_transfer,
)
from app.imports.adapters.base import (
ALFA_DEBIT_XLSX_VERSION,
BANK_STATUS_HOLD,
@@ -89,7 +93,7 @@ class TestBaseContract:
def test_per_contract_parser_versions(self) -> None:
assert PARSER_VERSION == "1"
assert ALFA_DEBIT_XLSX_VERSION == "2"
assert ALFA_DEBIT_XLSX_VERSION == "3"
assert OZON_DEBIT_PDF_VERSION == "2"
assert ROCKETBANK_DEBIT_PDF_VERSION == "2"
assert AlfaDebitXlsxAdapter.parser_version == ALFA_DEBIT_XLSX_VERSION
@@ -472,6 +476,122 @@ class TestAlfaDebitContract:
assert "quota" in exc.value.message
class TestAlfaSavingsRule:
"""«Копилка для сдачи» contract: exact normalized phrase, statement-side
source account, outgoing posted rows only. Every input is synthetic."""
STATEMENT_ACCOUNT = "00000000000000000001"
SERVICE_ACCOUNT = "00000000000000000306"
PHRASE = (
'Перечисление средств в рамках услуги "Копилка для сдачи" '
"со счета {source} на счет {target}"
)
def rule(
self,
description: str | None,
*,
direction: str = "out",
bank_status: str = "posted",
statement_account: str = STATEMENT_ACCOUNT,
) -> bool:
return detect_savings_transfer(
description,
direction=direction,
bank_status=bank_status,
statement_account=statement_account,
)
def test_exact_phrase_matches(self) -> None:
assert self.rule(
self.PHRASE.format(source=self.STATEMENT_ACCOUNT, target=self.SERVICE_ACCOUNT)
)
def test_spaces_case_and_quotes_are_normalized(self) -> None:
noisy = (
" Перечисление\u00a0средств в рамках услуги «КОПИЛКА ДЛЯ СДАЧИ» "
f"со счёта {self.STATEMENT_ACCOUNT} на счет {self.SERVICE_ACCOUNT} "
)
assert self.rule(noisy)
def test_mismatched_source_account_fails_closed(self) -> None:
assert not self.rule(
self.PHRASE.format(source="00000000000000000099", target=self.SERVICE_ACCOUNT)
)
def test_incoming_row_never_matches(self) -> None:
assert not self.rule(
self.PHRASE.format(source=self.STATEMENT_ACCOUNT, target=self.SERVICE_ACCOUNT),
direction="in",
)
def test_hold_row_never_matches(self) -> None:
assert not self.rule(
self.PHRASE.format(source=self.STATEMENT_ACCOUNT, target=self.SERVICE_ACCOUNT),
bank_status="hold",
)
def test_similar_description_without_full_pattern_fails_closed(self) -> None:
assert not self.rule("Копилка для сдачи: пополнение")
assert not self.rule(
'Перечисление в рамках услуги "Копилка для сдачи" со счета 123 на счет 306'
)
def test_masked_statement_account_fails_closed(self) -> None:
assert not self.rule(
self.PHRASE.format(source=self.STATEMENT_ACCOUNT, target=self.SERVICE_ACCOUNT),
statement_account="0000********0001",
)
def savings_statement_rows(self) -> list[list[object]]:
rows = [list(row) for row in synthetic_alfa_rows()]
rows[9] = [
None, None, None, None, None, None, None, None, None, None,
"Расходы", None, "416,90 RUR",
]
savings_row = [
"03.09.2026",
"03.09.2026",
None,
"000000000000009",
"Переводы",
None,
None,
None,
None,
None,
None,
self.PHRASE.format(source=self.STATEMENT_ACCOUNT, target=self.SERVICE_ACCOUNT),
"-123,45",
"Выполнен",
]
rows.insert(17, savings_row)
return rows
def test_parse_marks_savings_rows_and_bumps_version(self) -> None:
adapter = AlfaDebitXlsxAdapter()
raw = alfa_workbook_bytes(self.savings_statement_rows())
draft = adapter.parse(raw)
assert draft.parser_version == ALFA_DEBIT_XLSX_VERSION
by_code = {row.external_id: row for row in draft.rows}
assert len(draft.rows) == 6
marked = by_code["000000000000009"]
assert marked.savings_transfer is True
assert marked.direction == "out"
assert marked.bank_status == "posted"
assert marked.amount_kopecks == 12345
assert all(
row.savings_transfer is False
for code, row in by_code.items()
if code != "000000000000009"
)
def test_parse_leaves_plain_expenses_unmarked(self) -> None:
adapter = AlfaDebitXlsxAdapter()
draft = adapter.parse(alfa_workbook_bytes(synthetic_alfa_rows()))
assert all(not row.savings_transfer for row in draft.rows)
def ozon_extracted() -> tuple[list[str], list[list[list[object]]]]:
pages_text = [
"\n".join(
+337
View File
@@ -0,0 +1,337 @@
"""Budget semantics for savings transfers, adjustments and archived history."""
from datetime import date
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from app.budgeting.service import (
compute_period_state,
create_category,
fund,
get_or_create_period,
set_assignments,
)
from app.errors import AppError
from app.identity.models import User
from app.ledger.savings import adjust_balance, ensure_savings_resources
from app.ledger.service import create_account, create_expense, create_income, create_transfer
from app.spaces.service import create_space
def seed(db: Session):
user = User(email=f"{uuid4().hex}@example.com", password_hash="unused")
db.add(user)
db.flush()
space = create_space(db, user=user, name="BudgetSavings")
account = create_account(
db,
space_id=space.id,
user=user,
name="Debit",
kind="debit",
opened_on=date(2026, 5, 1),
opening_amount_kopecks=1_000_000,
)
return user, space, account
def savings_row(state: dict) -> dict:
return next(row for row in state["envelopes"] if row["name_key"] == "savings")
def test_transfer_to_savings_moves_pool_into_envelope(db: Session) -> None:
user, space, account = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
before = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
assert before["pool"] == 0
assert savings_row(before)["available"] == 0
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=250_000,
occurred_on=date(2026, 5, 10),
)
after = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
row = savings_row(after)
assert after["pool"] == -250_000
assert row["funded"] == 250_000
assert row["spent"] == 0
assert row["available"] == 250_000
assert after["income_total"] == 0
def test_transfer_back_from_savings_returns_pool(db: Session) -> None:
user, space, account = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=250_000,
occurred_on=date(2026, 5, 10),
)
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=savings_account.id,
target_account_id=account.id,
amount_kopecks=100_000,
occurred_on=date(2026, 5, 12),
)
state = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
row = savings_row(state)
assert state["pool"] == -150_000
assert row["funded"] == 150_000
assert row["available"] == 150_000
def test_adjustment_changes_only_envelope_available_not_pool(db: Session) -> None:
user, space, account = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=100_000,
occurred_on=date(2026, 5, 3),
)
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=savings_account.id,
target_balance_kopecks=80_000,
occurred_on=date(2026, 5, 20),
reason="Процентная корректировка",
)
state = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
row = savings_row(state)
assert row["available"] == 80_000
assert row["funded"] == 100_000
assert state["income_total"] == 0
assert state["pool"] == -100_000
def test_adjustment_on_regular_account_keeps_pool_and_totals(db: Session) -> None:
user, space, account = seed(db)
create_income(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=300_000,
occurred_on=date(2026, 5, 2),
)
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=1_000_000,
occurred_on=date(2026, 5, 21),
reason="Списание банка не отразилось",
)
state = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
assert state["income_total"] == 300_000
# The adjustment reconciles the account but never enters the budget pool.
assert state["pool"] == 300_000
assert state["uncategorized_expenses"] == 0
assert state["monthly_categories"] == []
def test_savings_envelope_available_uses_month_end_balance(db: Session) -> None:
user, space, account = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=50_000,
occurred_on=date(2026, 5, 28),
)
# A transfer in a later month must not affect the May envelope view.
create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=70_000,
occurred_on=date(2026, 6, 2),
)
may = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
june = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=6),
)
assert savings_row(may)["available"] == 50_000
assert savings_row(may)["funded"] == 50_000
assert savings_row(june)["available"] == 120_000
assert savings_row(june)["funded"] == 70_000
def test_archived_category_history_stays_in_totals(db: Session) -> None:
user, space, account = seed(db)
category = create_category(db, space_id=space.id, user=user, kind="monthly", name="Transport")
set_assignments(
db,
space_id=space.id,
user=user,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
items=[{"category_id": category.id, "planned_kopecks": 20_000}],
)
create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=5_000,
occurred_on=date(2026, 5, 6),
category_id=category.id,
)
category.archived = True
db.flush()
state = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
rows = [row for row in state["monthly_categories"] if row["category_id"] == str(category.id)]
assert len(rows) == 1
row = rows[0]
assert row["archived"] is True
assert row["spent"] == 5_000
assert row["planned"] == 20_000
# An archived category refuses new assignments...
try:
set_assignments(
db,
space_id=space.id,
user=user,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
items=[{"category_id": category.id, "planned_kopecks": 1}],
)
raise AssertionError("archived assignment must fail")
except AppError as exc:
assert exc.code == "BUDGET_CATEGORY_ARCHIVED"
# ...but its history still counts in the funding/spent totals.
summary_funded = sum(row["funded"] for row in state["monthly_categories"])
assert summary_funded == 0
def test_system_category_rejects_planning_funding_and_regular_expense(db: Session) -> None:
user, space, account = seed(db)
_, savings_category = ensure_savings_resources(db, space_id=space.id)
period = get_or_create_period(db, space_id=space.id, year=2026, month=5)
with pytest.raises(AppError) as exc:
set_assignments(
db,
space_id=space.id,
user=user,
period=period,
items=[{"category_id": savings_category.id, "planned_kopecks": 10_000}],
)
assert exc.value.code == "BUDGET_CATEGORY_SYSTEM"
with pytest.raises(AppError) as exc:
fund(
db,
space_id=space.id,
user=user,
period=period,
category_id=savings_category.id,
amount_kopecks=10_000,
kind="fund",
)
assert exc.value.code == "BUDGET_CATEGORY_SYSTEM"
with pytest.raises(AppError) as exc:
create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=10_000,
occurred_on=date(2026, 5, 10),
category_id=savings_category.id,
)
assert exc.value.code == "BUDGET_CATEGORY_SYSTEM"
def test_archived_category_rejects_new_funding(db: Session) -> None:
user, space, _ = seed(db)
category = create_category(db, space_id=space.id, user=user, kind="monthly", name="Old")
category.archived = True
period = get_or_create_period(db, space_id=space.id, year=2026, month=5)
with pytest.raises(AppError) as exc:
fund(
db,
space_id=space.id,
user=user,
period=period,
category_id=category.id,
amount_kopecks=1_000,
kind="fund",
)
assert exc.value.code == "BUDGET_CATEGORY_ARCHIVED"
def test_blockers_carry_discriminated_data(db: Session) -> None:
user, space, account = seed(db)
create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=5_000,
occurred_on=date(2026, 5, 6),
)
state = compute_period_state(
db,
space_id=space.id,
period=get_or_create_period(db, space_id=space.id, year=2026, month=5),
)
by_code = {blocker["code"]: blocker for blocker in state["close_blockers"]}
assert by_code["BUDGET_UNCATEGORIZED_EXPENSES"]["count"] == 1
assert "IMPORTS_UNRESOLVED" not in by_code
assert "IMPORT_UNRESOLVED_HOLDS" not in by_code
+216
View File
@@ -0,0 +1,216 @@
"""HTTP contract for category definitions, system protections and CSRF."""
from fastapi.testclient import TestClient
def bootstrap(client: TestClient) -> str:
invite = client.post(
"/api/v1/admin/invitations",
headers={"X-Admin-Token": "test-admin-token"},
json={"email": "categories@Example.com"},
)
assert invite.status_code == 201, invite.text
accepted = client.post(
"/api/v1/auth/invitations/accept",
json={
"token": invite.json()["token"],
"password": "a-long-password-for-tests",
"fullName": "Category Tester",
"locale": "en",
},
)
assert accepted.status_code == 201, accepted.text
return client.cookies["csrf_token"]
def test_space_has_protected_savings_pair(client: TestClient) -> None:
csrf = bootstrap(client)
accounts = client.get("/api/v1/accounts").json()
savings = [item for item in accounts if item["systemKey"] == "savings"]
assert len(savings) == 1
assert savings[0]["type"] == "savings"
assert savings[0]["nameKey"] == "account.savings"
assert savings[0]["balanceKopecks"] == 0
definitions = client.get(
"/api/v1/budget/category-definitions", params={"includeArchived": "true"}
).json()
savings_definitions = [item for item in definitions if item["systemKey"] == "savings"]
assert len(savings_definitions) == 1
assert savings_definitions[0]["nameKey"] == "savings"
assert savings_definitions[0]["name"] is None
assert savings_definitions[0]["archived"] is False
assert savings_definitions[0]["kind"] == "savings_envelope"
assert savings_definitions[0]["linkedAccountId"] == savings[0]["id"]
# CSRF is enforced on the new mutation endpoints.
denied = client.patch(
f"/api/v1/budget/category-definitions/{savings_definitions[0]['id']}",
json={"name": "My stash"},
)
assert denied.status_code == 403
# System categories reject rename and archive.
for payload in ({"name": "My stash"}, {"archived": True}):
rejected = client.patch(
f"/api/v1/budget/category-definitions/{savings_definitions[0]['id']}",
json=payload,
headers={"X-CSRF-Token": csrf},
)
assert rejected.status_code == 409, rejected.text
# System accounts reject archive and delete.
account_id = savings[0]["id"]
archive_response = client.post(
f"/api/v1/accounts/{account_id}/archive", headers={"X-CSRF-Token": csrf}
)
assert archive_response.status_code == 409
delete_response = client.delete(
f"/api/v1/accounts/{account_id}", headers={"X-CSRF-Token": csrf}
)
assert delete_response.status_code == 409
def test_category_lifecycle_create_rename_archive_restore(client: TestClient) -> None:
csrf = bootstrap(client)
created = client.post(
"/api/v1/budget/categories",
headers={"X-CSRF-Token": csrf},
json={"name": " Groceries ", "kind": "monthly"},
)
assert created.status_code == 201, created.text
body = created.json()
assert body["name"] == "Groceries"
assert body["kind"] == "monthly"
assert body["systemKey"] is None
assert body["archived"] is False
category_id = body["id"]
renamed = client.patch(
f"/api/v1/budget/category-definitions/{category_id}",
headers={"X-CSRF-Token": csrf},
json={"name": "Food"},
)
assert renamed.status_code == 200, renamed.text
assert renamed.json()["name"] == "Food"
archived = client.patch(
f"/api/v1/budget/category-definitions/{category_id}",
headers={"X-CSRF-Token": csrf},
json={"archived": True},
)
assert archived.status_code == 200
assert archived.json()["archived"] is True
active_only = client.get("/api/v1/budget/category-definitions").json()
assert all(item["id"] != category_id for item in active_only)
with_archived = client.get(
"/api/v1/budget/category-definitions", params={"includeArchived": "true"}
).json()
assert any(item["id"] == category_id and item["archived"] for item in with_archived)
restored = client.patch(
f"/api/v1/budget/category-definitions/{category_id}",
headers={"X-CSRF-Token": csrf},
json={"archived": False},
)
assert restored.status_code == 200
assert restored.json()["archived"] is False
# Empty names are rejected after trim.
empty = client.post(
"/api/v1/budget/categories",
headers={"X-CSRF-Token": csrf},
json={"name": " ", "kind": "monthly"},
)
assert empty.status_code == 400
blank_rename = client.patch(
f"/api/v1/budget/category-definitions/{category_id}",
headers={"X-CSRF-Token": csrf},
json={"name": " "},
)
assert blank_rename.status_code == 400
def test_openapi_contains_new_contracts(client: TestClient) -> None:
bootstrap(client)
paths = client.get("/api/v1/openapi.json").json()["paths"]
assert "/api/v1/accounts/{account_id}/adjust-balance" in paths
assert "/api/v1/operations/{operation_id}/savings-transfer" in paths
assert "/api/v1/operations/{operation_id}/savings-transfer/revert" in paths
assert "/api/v1/budget/category-definitions" in paths
assert "/api/v1/budget/category-definitions/{category_id}" in paths
assert "/api/v1/imports/{document_id}/rows/{row_id}/resolve" in paths
def test_adjust_and_savings_conversion_http_contracts(client: TestClient) -> None:
csrf = bootstrap(client)
account = client.post(
"/api/v1/accounts",
headers={"X-CSRF-Token": csrf},
json={
"name": "Debit",
"type": "debit",
"openedOn": "2026-09-01",
"openingBalanceKopecks": 100_000,
},
)
assert account.status_code == 201, account.text
account_id = account.json()["id"]
adjustment_body = {
"targetBalanceKopecks": 90_000,
"occurredOn": "2026-09-10",
"reason": "Statement reconciliation",
}
denied = client.post(
f"/api/v1/accounts/{account_id}/adjust-balance", json=adjustment_body
)
assert denied.status_code == 403
adjusted = client.post(
f"/api/v1/accounts/{account_id}/adjust-balance",
headers={"X-CSRF-Token": csrf},
json=adjustment_body,
)
assert adjusted.status_code == 200, adjusted.text
assert adjusted.json()["oldBalanceKopecks"] == 100_000
assert adjusted.json()["newBalanceKopecks"] == 90_000
assert adjusted.json()["kind"] == "adjustment"
category = client.post(
"/api/v1/budget/categories",
headers={"X-CSRF-Token": csrf},
json={"name": "Food", "kind": "monthly"},
)
assert category.status_code == 201, category.text
expense = client.post(
"/api/v1/operations",
headers={"X-CSRF-Token": csrf},
json={
"kind": "expense",
"amountKopecks": 5_000,
"accountId": account_id,
"categoryId": category.json()["id"],
"occurredOn": "2026-09-11",
},
)
assert expense.status_code == 201, expense.text
operation_id = expense.json()["id"]
denied = client.post(f"/api/v1/operations/{operation_id}/savings-transfer")
assert denied.status_code == 403
converted = client.post(
f"/api/v1/operations/{operation_id}/savings-transfer",
headers={"X-CSRF-Token": csrf},
)
assert converted.status_code == 200, converted.text
assert converted.json()["kind"] == "transfer"
assert converted.json()["convertedFromExpense"] is True
reverted = client.post(
f"/api/v1/operations/{operation_id}/savings-transfer/revert",
headers={"X-CSRF-Token": csrf},
)
assert reverted.status_code == 200, reverted.text
assert reverted.json()["kind"] == "expense"
assert reverted.json()["convertedFromExpense"] is False
+386
View File
@@ -0,0 +1,386 @@
"""Import contract for the «Копилка для сдачи» savings_transfer decision."""
import uuid
from datetime import date
from types import SimpleNamespace
import pytest
from sqlalchemy.orm import Session
from app.errors import AppError
from app.identity.models import User
from app.imports import router as imports_router
from app.imports import service
from app.imports.adapters.alfa_xlsx import detect_savings_transfer
from app.imports.models import (
DedupCandidate,
ParseRun,
SourceRecord,
SourceRecordLink,
StatementDocument,
)
from app.ledger.models import Operation
from app.ledger.savings import get_savings_account
from app.ledger.service import create_account
from app.spaces.service import create_space
SAVINGS_PHRASE = (
'Перечисление средств в рамках услуги "Копилка для сдачи" '
"со счета 00000000000000000001 на счет 00000000000000000306"
)
def seed(db: Session):
user = User(email=f"{uuid.uuid4().hex}@example.com", password_hash="unused")
db.add(user)
db.flush()
space = create_space(db, user=user, name="ImportSavings")
account = create_account(
db,
space_id=space.id,
user=user,
name="Alfa Debit",
kind="debit",
opened_on=date(2026, 1, 1),
)
return user, space, account
def make_document(db: Session, space, account, *, user: User) -> tuple[StatementDocument, ParseRun]:
document = StatementDocument(
space_id=space.id,
account_id=account.id,
original_filename=f"{uuid.uuid4().hex}.xlsx",
size_bytes=100,
content_sha256=uuid.uuid4().hex + uuid.uuid4().hex,
object_key=uuid.uuid4().hex,
status="ready",
reconciliation={"full": True, "matched": True},
uploaded_by_user_id=user.id,
)
db.add(document)
db.flush()
run = ParseRun(
space_id=space.id,
document_id=document.id,
adapter_id="alfa_debit_xlsx",
status="succeeded",
)
db.add(run)
db.flush()
document.active_parse_run_id = run.id
return document, run
def add_record(
db: Session,
document: StatementDocument,
run: ParseRun,
*,
bank_status: str = "posted",
direction: str = "out",
external_id: str | None = None,
description: str | None = None,
occurred_on: date = date(2026, 5, 10),
) -> SourceRecord:
source = SourceRecord(
space_id=document.space_id,
document_id=document.id,
parse_run_id=run.id,
external_id=external_id,
occurred_on=occurred_on,
amount_kopecks=12_345,
direction=direction,
bank_status=bank_status,
description=description,
row_ref=f"sheet0:row{uuid.uuid4().int % 1000}",
record_fp=uuid.uuid4().hex,
review_decision="savings_transfer"
if detect_savings_transfer(
description,
direction=direction,
bank_status=bank_status,
statement_account="00000000000000000001",
)
else "create",
)
db.add(source)
db.flush()
return source
def test_parsed_savings_hint_becomes_initial_review_decision(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
source = add_record(db, document, run, description=SAVINGS_PHRASE)
assert source.review_decision == "savings_transfer"
def test_confirm_creates_savings_transfer_with_system_category(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
source = add_record(
db,
document,
run,
external_id="ALFA-1",
description=SAVINGS_PHRASE,
occurred_on=date(2026, 5, 10),
)
assert source.review_decision == "savings_transfer"
service.confirm_document(db, space_id=space.id, document_id=document.id, user=user)
db.flush()
savings_account = get_savings_account(db, space_id=space.id)
operations = db.query(Operation).filter_by(space_id=space.id).all()
assert len(operations) == 1
transfer = operations[0]
assert transfer.type == "transfer"
assert transfer.account_id == account.id
assert transfer.counter_account_id == savings_account.id
from app.ledger.models import Category
category = db.get(Category, transfer.category_id)
assert category is not None
assert category.system_key == "savings"
assert transfer.request_key == f"import-savings:{source.id}"
assert transfer.description == SAVINGS_PHRASE
link = db.query(SourceRecordLink).filter_by(source_record_id=source.id).one()
assert link.operation_id == transfer.id
assert link.kind == "created"
assert document.status == "confirmed"
def test_revert_removes_created_savings_transfer(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
add_record(db, document, run, description=SAVINGS_PHRASE)
service.confirm_document(db, space_id=space.id, document_id=document.id, user=user)
assert db.query(Operation).filter_by(space_id=space.id).count() == 1
service.revert_document(db, space_id=space.id, document_id=document.id, user=user)
db.flush()
assert db.query(Operation).filter_by(space_id=space.id).count() == 0
assert db.query(SourceRecordLink).filter_by(space_id=space.id).count() == 0
assert document.status == "ready"
source = (
db.query(SourceRecord).filter_by(parse_run_id=document.active_parse_run_id).one()
)
# Repeated parse gives the same decision: the hint survives revert.
assert source.review_decision == "savings_transfer"
def test_user_can_switch_savings_decision_to_create(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
source = add_record(db, document, run, description=SAVINGS_PHRASE)
service.decide_source_record(
db,
space_id=space.id,
document_id=document.id,
source_record_id=source.id,
decision="create",
duplicate_operation_id=None,
user=user,
)
assert source.review_decision == "create"
service.confirm_document(db, space_id=space.id, document_id=document.id, user=user)
operations = db.query(Operation).filter_by(space_id=space.id).all()
assert len(operations) == 1
assert operations[0].type == "expense"
def test_user_can_switch_savings_decision_to_discard(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
source = add_record(db, document, run, description=SAVINGS_PHRASE)
service.decide_source_record(
db,
space_id=space.id,
document_id=document.id,
source_record_id=source.id,
decision="discard",
duplicate_operation_id=None,
user=user,
)
assert source.review_decision == "discard"
service.confirm_document(db, space_id=space.id, document_id=document.id, user=user)
assert db.query(Operation).filter_by(space_id=space.id).count() == 0
def test_savings_decision_rejects_incoming_rows(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
source = add_record(
db,
document,
run,
direction="in",
description="Incoming transfer",
)
with pytest.raises(AppError) as exc:
service.decide_source_record(
db,
space_id=space.id,
document_id=document.id,
source_record_id=source.id,
decision="savings_transfer",
duplicate_operation_id=None,
user=user,
)
assert exc.value.code == "IMPORT_DECISION_INVALID"
def test_statement_mapping_rejects_system_account(db: Session) -> None:
user, space, account = seed(db)
document, _run = make_document(db, space, account, user=user)
savings_account = get_savings_account(db, space_id=space.id)
with pytest.raises(AppError) as exc:
service.set_review_confirmation(
db,
space_id=space.id,
document_id=document.id,
account_id=savings_account.id,
confirmed_without_full_reconciliation=True,
reason="invalid mapping",
)
assert exc.value.code == "IMPORT_SYSTEM_ACCOUNT_INVALID"
def test_existing_dedup_wins_over_savings_creation(db: Session) -> None:
user, space, account = seed(db)
first, first_run = make_document(db, space, account, user=user)
external_id = "ALFA-DUP-1"
first_source = SourceRecord(
space_id=space.id,
document_id=first.id,
parse_run_id=first_run.id,
external_id=external_id,
occurred_on=date(2026, 5, 3),
amount_kopecks=12_345,
direction="out",
description="Groceries",
row_ref="sheet0:row3",
record_fp="fp-existing",
)
db.add(first_source)
db.flush()
service.confirm_document(db, space_id=space.id, document_id=first.id, user=user)
created = db.query(Operation).filter_by(space_id=space.id).one()
second, second_run = make_document(db, space, account, user=user)
duplicate = add_record(
db,
second,
second_run,
external_id=external_id,
description=SAVINGS_PHRASE,
occurred_on=date(2026, 5, 10),
)
assert service._build_candidates(db, document=second, run=second_run)
candidates = db.query(DedupCandidate).filter_by(source_record_id=duplicate.id).all()
assert len(candidates) == 1
assert candidates[0].candidate_kind == "duplicate"
assert candidates[0].existing_operation_id == created.id
service.decide_source_record(
db,
space_id=space.id,
document_id=second.id,
source_record_id=duplicate.id,
decision="duplicate",
duplicate_operation_id=created.id,
user=user,
)
service.confirm_document(db, space_id=space.id, document_id=second.id, user=user)
db.flush()
operations = db.query(Operation).filter_by(space_id=space.id).all()
assert len(operations) == 1
assert operations[0].id == created.id
def test_savings_transfer_on_hold_row_never_matches(db: Session) -> None:
assert (
detect_savings_transfer(
SAVINGS_PHRASE,
direction="out",
bank_status="hold",
statement_account="00000000000000000001",
)
is False
)
def test_unresolved_hold_counts_and_month_filter(db: Session) -> None:
user, space, account = seed(db)
document, run = make_document(db, space, account, user=user)
add_record(
db,
document,
run,
bank_status="hold",
description="Coffee shop",
occurred_on=date(2026, 5, 10),
)
add_record(
db,
document,
run,
bank_status="hold",
description="Train ticket",
occurred_on=date(2026, 6, 1),
)
resolved = add_record(
db,
document,
run,
bank_status="hold",
description="Resolved one",
occurred_on=date(2026, 5, 12),
)
db.add(
service.HoldResolution(
space_id=space.id,
hold_source_record_id=resolved.id,
resolution="confirmed_as_posted",
reason="verified",
)
)
db.flush()
unresolved = service.unresolved_holds(db, space_id=space.id, document=document)
assert len(unresolved) == 2
assert service.unresolved_hold_counts(
db, space_id=space.id, document_ids=[document.id]
) == {document.id: 2}
may = service.parse_month_filter("2026-05")
assert may == (2026, 5)
may_holds = [h for h in unresolved if h.occurred_on and h.occurred_on.month == 5]
assert len(may_holds) == 1
assert service.unresolved_hold_counts(
db, space_id=space.id, document_ids=[document.id], month=may
) == {document.id: 1}
context = SimpleNamespace(space=space)
july_items = imports_router.imports(db, context, month="2026-07")
assert july_items[0]["id"] == document.id
assert july_items[0]["unresolvedHoldCount"] == 0
document.status = "confirmed"
assert imports_router.imports(db, context, month="2026-07") == []
may_items = imports_router.imports(db, context, month="2026-05")
assert may_items[0]["id"] == document.id
assert may_items[0]["unresolvedHoldCount"] == 1
assert service.parse_month_filter(None) is None
with pytest.raises(AppError) as exc:
service.parse_month_filter("2026-13")
assert exc.value.code == "IMPORT_MONTH_INVALID"
def test_confirm_savings_transfer_rejects_savings_statement_account(db: Session) -> None:
user, space, account = seed(db)
savings_account = get_savings_account(db, space_id=space.id)
document, run = make_document(db, space, savings_account, user=user)
document.account_id = savings_account.id
add_record(db, document, run, description=SAVINGS_PHRASE)
with pytest.raises(AppError) as exc:
service.confirm_document(db, space_id=space.id, document_id=document.id, user=user)
assert exc.value.code == "IMPORT_SAVINGS_SOURCE_INVALID"
+495
View File
@@ -0,0 +1,495 @@
"""Savings system resources, adjustments and convert/revert contracts."""
from datetime import date
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from app.audit.models import AuditEvent
from app.budgeting.service import close_period, get_or_create_period
from app.errors import AppError
from app.identity.models import User
from app.ledger.models import Account, Category, Operation, Posting
from app.ledger.savings import (
adjust_balance,
convert_expense_to_savings,
ensure_savings_resources,
get_savings_account,
revert_savings_conversion,
)
from app.ledger.service import (
account_balance,
create_account,
create_expense,
create_income,
create_refund,
create_transfer,
)
from app.spaces.service import create_space
def seed(db: Session):
user = User(email=f"{uuid4().hex}@example.com", password_hash="unused")
db.add(user)
db.flush()
space = create_space(db, user=user, name="Savings")
account = create_account(
db,
space_id=space.id,
user=user,
name="Debit",
kind="debit",
opened_on=date(2026, 3, 1),
opening_amount_kopecks=500_000,
)
return user, space, account
def test_space_creation_builds_exactly_one_system_pair(db: Session) -> None:
user, space, _ = seed(db)
account, category = ensure_savings_resources(db, space_id=space.id)
assert account.kind == "savings"
assert account.system_key == "savings"
assert category.kind == "savings_envelope"
assert category.system_key == "savings"
assert category.linked_account_id == account.id
assert get_savings_account(db, space_id=space.id) is account
assert db.query(Account).filter_by(space_id=space.id, kind="savings").count() == 1
# Idempotent: repeated ensure returns the same pair and adds no rows.
again_account, again_category = ensure_savings_resources(db, space_id=space.id)
assert (again_account.id, again_category.id) == (account.id, category.id)
assert db.query(Account).filter_by(space_id=space.id).count() == 2
assert user is not None
def test_same_named_user_account_is_not_captured(db: Session) -> None:
user, space, _ = seed(db)
impostor = create_account(
db,
space_id=space.id,
user=user,
name="Накопления",
kind="cash",
opened_on=date(2026, 3, 1),
)
system_account, category = ensure_savings_resources(db, space_id=space.id)
assert impostor.id != system_account.id
assert impostor.system_key is None
assert category.linked_account_id == system_account.id
def test_adjust_balance_creates_single_signed_posting(db: Session) -> None:
user, space, account = seed(db)
operation, old_balance, new_balance = adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=475_000,
occurred_on=date(2026, 3, 15),
reason="Купюры пересчитаны вручную",
)
assert (old_balance, new_balance) == (500_000, 475_000)
assert operation.type == "adjustment"
assert operation.amount_kopecks == 25_000
postings = db.query(Posting).filter_by(operation_id=operation.id).all()
assert len(postings) == 1
assert postings[0].amount_kopecks == -25_000
assert account_balance(db, account) == 475_000
event = (
db.query(AuditEvent).filter_by(event_type="account.balance_adjusted").one()
)
assert event.detail["old_balance_kopecks"] == 500_000
assert event.detail["new_balance_kopecks"] == 475_000
assert event.detail["delta_kopecks"] == -25_000
def test_adjust_balance_positive_delta_and_upward_adjustment(db: Session) -> None:
user, space, account = seed(db)
operation, _, _ = adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=510_000,
occurred_on=date(2026, 3, 15),
reason="Найдена купюра",
)
assert operation.amount_kopecks == 10_000
postings = db.query(Posting).filter_by(operation_id=operation.id).all()
assert postings[0].amount_kopecks == 10_000
assert account_balance(db, account) == 510_000
def test_adjust_balance_rejects_credit_accounts(db: Session) -> None:
user, space, _ = seed(db)
credit = create_account(
db,
space_id=space.id,
user=user,
name="Credit",
kind="credit",
opened_on=date(2026, 3, 1),
opening_amount_kopecks=-500_000,
)
with pytest.raises(AppError) as exc:
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=credit.id,
target_balance_kopecks=0,
occurred_on=date(2026, 3, 16),
reason="Invalid sign",
)
assert exc.value.code == "LEDGER_ADJUST_CREDIT_UNSUPPORTED"
def test_adjust_balance_rejects_noop_negative_target_and_missing_reason(
db: Session,
) -> None:
user, space, account = seed(db)
with pytest.raises(AppError) as exc:
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=500_000,
occurred_on=date(2026, 3, 15),
reason="same",
)
assert exc.value.code == "LEDGER_ADJUST_NOOP"
with pytest.raises(AppError) as exc:
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=-1,
occurred_on=date(2026, 3, 15),
reason="below zero",
)
assert exc.value.code == "LEDGER_ADJUST_TARGET_NEGATIVE"
with pytest.raises(AppError) as exc:
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=1,
occurred_on=date(2026, 3, 15),
reason=" ",
)
assert exc.value.code == "LEDGER_ADJUST_REASON_REQUIRED"
def test_adjust_balance_protects_closed_period(db: Session) -> None:
user, space, account = seed(db)
period = get_or_create_period(db, space_id=space.id, year=2026, month=3)
close_period(db, space_id=space.id, user=user, period=period)
with pytest.raises(AppError) as exc:
adjust_balance(
db,
space_id=space.id,
user=user,
account_id=account.id,
target_balance_kopecks=1,
occurred_on=date(2026, 3, 20),
reason="late fix",
)
assert exc.value.code == "BUDGET_PERIOD_CLOSED"
def test_convert_expense_to_savings_and_revert_roundtrip(db: Session) -> None:
user, space, account = seed(db)
savings_account, savings_category = ensure_savings_resources(db, space_id=space.id)
category = Category(space_id=space.id, kind="monthly", custom_name="Food")
db.add(category)
db.flush()
expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=12_345,
occurred_on=date(2026, 3, 5),
category_id=category.id,
description="Groceries",
request_key="op-1",
)
converted = convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=expense.id
)
assert converted.type == "transfer"
assert converted.counter_account_id == savings_account.id
assert converted.category_id == savings_category.id
assert converted.converted_from_expense is True
assert converted.previous_category_id == category.id
assert converted.description == "Groceries"
assert converted.request_key == "op-1"
postings = db.query(Posting).filter_by(operation_id=converted.id).all()
assert len(postings) == 2
assert sum(item.amount_kopecks for item in postings) == 0
assert account_balance(db, account) == 500_000 - 12_345
assert account_balance(db, savings_account) == 12_345
reverted = revert_savings_conversion(
db, space_id=space.id, user=user, operation_id=expense.id
)
assert reverted.type == "expense"
assert reverted.counter_account_id is None
assert reverted.category_id == category.id
assert reverted.converted_from_expense is False
assert reverted.previous_category_id is None
postings_after = db.query(Posting).filter_by(operation_id=reverted.id).all()
assert len(postings_after) == 1
assert postings_after[0].amount_kopecks == -12_345
assert account_balance(db, account) == 500_000 - 12_345
assert account_balance(db, savings_account) == 0
def test_convert_rejects_income_refund_transfer_and_double_conversion(
db: Session,
) -> None:
user, space, account = seed(db)
income = create_income(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=1_000,
occurred_on=date(2026, 3, 2),
)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=income.id
)
assert exc.value.code == "LEDGER_SAVINGS_CONVERT_INVALID"
refundable_expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=2_000,
occurred_on=date(2026, 3, 3),
)
refund = create_refund(
db,
space_id=space.id,
user=user,
parent_operation_id=refundable_expense.id,
amount_kopecks=500,
occurred_on=date(2026, 3, 4),
)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=refund.id
)
assert exc.value.code == "LEDGER_SAVINGS_CONVERT_INVALID"
expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=2_000,
occurred_on=date(2026, 3, 5),
)
convert_expense_to_savings(db, space_id=space.id, user=user, operation_id=expense.id)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=expense.id
)
assert exc.value.code == "LEDGER_SAVINGS_CONVERT_INVALID"
transfer = create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=get_savings_account(db, space_id=space.id).id,
amount_kopecks=1_000,
occurred_on=date(2026, 3, 6),
)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=transfer.id
)
assert exc.value.code == "LEDGER_SAVINGS_CONVERT_INVALID"
def test_convert_rejects_expense_with_confirmed_refund(db: Session) -> None:
user, space, account = seed(db)
expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=2_000,
occurred_on=date(2026, 3, 3),
)
create_refund(
db,
space_id=space.id,
user=user,
parent_operation_id=expense.id,
amount_kopecks=500,
occurred_on=date(2026, 3, 4),
)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=expense.id
)
assert exc.value.code == "LEDGER_SAVINGS_CONVERT_HAS_REFUNDS"
def test_convert_rejects_closed_period_and_cross_space_operation(db: Session) -> None:
user, space, account = seed(db)
other_space = create_space(db, user=user, name="Other")
category = Category(space_id=space.id, kind="monthly", custom_name="Food")
db.add(category)
db.flush()
expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=3_000,
occurred_on=date(2026, 3, 7),
category_id=category.id,
)
period = get_or_create_period(db, space_id=space.id, year=2026, month=3)
close_period(db, space_id=space.id, user=user, period=period)
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=space.id, user=user, operation_id=expense.id
)
assert exc.value.code == "BUDGET_PERIOD_CLOSED"
with pytest.raises(AppError) as exc:
convert_expense_to_savings(
db, space_id=other_space.id, user=user, operation_id=expense.id
)
assert exc.value.code == "LEDGER_OPERATION_NOT_FOUND"
def test_revert_rejects_plain_transfers_and_unknown_operations(db: Session) -> None:
user, space, account = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
plain = create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=500,
occurred_on=date(2026, 3, 8),
)
with pytest.raises(AppError) as exc:
revert_savings_conversion(db, space_id=space.id, user=user, operation_id=plain.id)
assert exc.value.code == "LEDGER_SAVINGS_REVERT_INVALID"
with pytest.raises(AppError) as exc:
revert_savings_conversion(db, space_id=space.id, user=user, operation_id=uuid4())
assert exc.value.code == "LEDGER_OPERATION_NOT_FOUND"
def test_system_account_rejects_external_operations(db: Session) -> None:
user, space, _ = seed(db)
savings_account, savings_category = ensure_savings_resources(db, space_id=space.id)
with pytest.raises(AppError) as exc:
create_expense(
db,
space_id=space.id,
user=user,
account_id=savings_account.id,
amount_kopecks=100,
occurred_on=date(2026, 3, 9),
)
assert exc.value.code == "LEDGER_SYSTEM_ACCOUNT_NOT_EXTERNAL"
with pytest.raises(AppError) as exc:
create_income(
db,
space_id=space.id,
user=user,
account_id=savings_account.id,
amount_kopecks=100,
occurred_on=date(2026, 3, 9),
)
assert exc.value.code == "LEDGER_SYSTEM_ACCOUNT_NOT_EXTERNAL"
assert savings_category is not None
def test_manual_transfer_with_savings_gets_system_category(db: Session) -> None:
user, space, account = seed(db)
cash = create_account(
db,
space_id=space.id,
user=user,
name="Cash",
kind="cash",
opened_on=date(2026, 3, 1),
)
savings_account, savings_category = ensure_savings_resources(db, space_id=space.id)
into = create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=savings_account.id,
amount_kopecks=700,
occurred_on=date(2026, 3, 10),
)
assert into.category_id == savings_category.id
out_of = create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=savings_account.id,
target_account_id=cash.id,
amount_kopecks=200,
occurred_on=date(2026, 3, 11),
)
assert out_of.category_id == savings_category.id
regular = create_transfer(
db,
space_id=space.id,
user=user,
source_account_id=account.id,
target_account_id=cash.id,
amount_kopecks=300,
occurred_on=date(2026, 3, 12),
)
assert regular.category_id is None
def test_system_account_cannot_be_archived_or_deleted(db: Session) -> None:
user, space, _ = seed(db)
savings_account, _ = ensure_savings_resources(db, space_id=space.id)
from app.ledger.service import archive_account, delete_account
with pytest.raises(AppError) as exc:
archive_account(db, space_id=space.id, user=user, account_id=savings_account.id)
assert exc.value.code == "LEDGER_ACCOUNT_SYSTEM"
with pytest.raises(AppError) as exc:
delete_account(db, space_id=space.id, user=user, account_id=savings_account.id)
assert exc.value.code == "LEDGER_ACCOUNT_SYSTEM"
def test_operations_on_other_spaces_are_isolated(db: Session) -> None:
user, space, account = seed(db)
other_space = create_space(db, user=user, name="Elsewhere")
expense = create_expense(
db,
space_id=space.id,
user=user,
account_id=account.id,
amount_kopecks=1_500,
occurred_on=date(2026, 3, 14),
)
convert_expense_to_savings(db, space_id=space.id, user=user, operation_id=expense.id)
assert (
db.query(Operation).filter_by(space_id=other_space.id).count() == 0
)
+68
View File
@@ -0,0 +1,68 @@
from datetime import date
from pathlib import Path
from alembic.config import Config
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from alembic import command
from app.config import get_settings
from app.identity.models import User
from app.ledger.models import Account, Category
from app.spaces.models import FinancialSpace, Membership
def test_upgrade_backfills_one_pair_without_claiming_same_named_rows(
tmp_path: Path, monkeypatch,
) -> None:
database_url = f"sqlite:///{tmp_path / 'migration.db'}"
monkeypatch.setenv("DATABASE_URL", database_url)
get_settings.cache_clear()
config = Config(str(Path(__file__).parents[1] / "alembic.ini"))
config.set_main_option("script_location", str(Path(__file__).parents[1] / "alembic"))
try:
command.upgrade(config, "0002")
engine = create_engine(database_url)
with Session(engine) as db:
user = User(email="migration@example.com", password_hash="unused")
space = FinancialSpace(name="Legacy")
db.add_all([user, space])
db.flush()
db.add(Membership(space_id=space.id, user_id=user.id, role="owner"))
db.add(
Account(
space_id=space.id,
name="Savings",
kind="debit",
opened_on=date(2026, 1, 1),
)
)
db.add(
Category(
space_id=space.id,
name_override="Savings",
kind="monthly",
)
)
db.commit()
space_id = space.id
command.upgrade(config, "head")
command.upgrade(config, "head")
with Session(engine) as db:
accounts = db.query(Account).filter_by(space_id=space_id).all()
categories = db.query(Category).filter_by(space_id=space_id).all()
system_account = [item for item in accounts if item.system_key == "savings"]
system_category = [item for item in categories if item.system_key == "savings"]
assert len(system_account) == 1
assert len(system_category) == 1
assert system_category[0].linked_account_id == system_account[0].id
assert any(item.name == "Savings" and item.system_key is None for item in accounts)
assert any(
item.name_override == "Savings" and item.system_key is None
for item in categories
)
finally:
get_settings.cache_clear()