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