Update file metadata in manifest.json and change MinIO image source in docker-compose.yml
This commit is contained in:
@@ -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(
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
)
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user