mirror of
https://github.com/Zproger/Aurum.git
synced 2026-11-17 23:52:49 +07:00
feat: отчёт по тегам в Отчётах, версия 1.1.9
This commit is contained in:
@@ -60,7 +60,7 @@ class CategoryRollupItem:
|
||||
children: list[CategoryRollupChildItem] = field(default_factory=list)
|
||||
|
||||
|
||||
async def _raw_category_contributions(
|
||||
async def raw_category_contributions(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
transaction_type: TransactionType,
|
||||
@@ -103,7 +103,7 @@ async def rollup_spending_by_top_level_category(
|
||||
"""Every top-level category's total for the period, sorted by amount
|
||||
desc (category sort_order as tiebreak — same order the SQL-only version
|
||||
used to produce)."""
|
||||
contributions = await _raw_category_contributions(
|
||||
contributions = await raw_category_contributions(
|
||||
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date
|
||||
)
|
||||
if not contributions:
|
||||
|
||||
@@ -3,17 +3,25 @@ breakdown can't answer on its own: "how much did I spend on X this month,
|
||||
and how much in total over N years" (single-category detail), and "which
|
||||
categories cost the most over this whole period" (ranking, across all
|
||||
categories of one kind at once, not just the current month).
|
||||
|
||||
The same two shapes exist tag-side (get_tag_ranking_report /
|
||||
get_tag_spending_report): a category answers "what kind of spend was this",
|
||||
a tag answers "which event/project did it belong to" (models/tag.py), so
|
||||
the tag reports are what answer "how much did this trip / these gifts cost
|
||||
me", cutting across categories instead of along them.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from datetime import date as date_
|
||||
from decimal import Decimal
|
||||
from typing import NamedTuple
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.category import Category
|
||||
from app.models.enums import CategoryKind, TransactionType
|
||||
from app.models.tag import Tag, transaction_tags
|
||||
from app.models.transaction import Transaction, TransactionSplit
|
||||
from app.schemas.reports import (
|
||||
CategoryRankingChildItem,
|
||||
@@ -21,14 +29,74 @@ from app.schemas.reports import (
|
||||
CategoryRankingReport,
|
||||
CategorySpendingPoint,
|
||||
CategorySpendingReport,
|
||||
TagRankingCategoryItem,
|
||||
TagRankingItem,
|
||||
TagRankingReport,
|
||||
TagSpendingReport,
|
||||
)
|
||||
from app.services.category_rollup import rollup_spending_by_top_level_category
|
||||
from app.services.tag_rollup import rollup_spending_by_tag
|
||||
|
||||
|
||||
def _next_month(year: int, month: int) -> tuple[int, int]:
|
||||
return (year + 1, 1) if month == 12 else (year, month + 1)
|
||||
|
||||
|
||||
class _MonthlySummary(NamedTuple):
|
||||
start_date: date_
|
||||
end_date: date_
|
||||
total_amount: Decimal
|
||||
transaction_count: int
|
||||
average_per_month: Decimal
|
||||
series: list[CategorySpendingPoint]
|
||||
|
||||
|
||||
def _summarize_by_month(
|
||||
contributions: list[tuple[int, date_, Decimal]], start_date: date_ | None, end_date: date_ | None
|
||||
) -> _MonthlySummary:
|
||||
"""Turns (transaction_id, date, amount) rows into the month-by-month
|
||||
shape both detail reports return — gap months included as zeroes so the
|
||||
chart's bars stay evenly spaced in time, and the period falling back to
|
||||
the data's own first/last month when the caller didn't bound it.
|
||||
|
||||
Shared by the category and tag detail reports so the two can't drift on
|
||||
what "average per month" or "transaction count" mean. Callers must
|
||||
handle an empty `contributions` list themselves: with no rows there is
|
||||
no period to fall back to.
|
||||
"""
|
||||
dates = [txn_date for _, txn_date, _ in contributions]
|
||||
effective_start = start_date or min(dates)
|
||||
effective_end = end_date or max(dates)
|
||||
|
||||
by_month: dict[tuple[int, int], Decimal] = defaultdict(Decimal)
|
||||
for _, txn_date, amount in contributions:
|
||||
by_month[(txn_date.year, txn_date.month)] += amount
|
||||
|
||||
total_amount = sum((amount for _, _, amount in contributions), Decimal("0"))
|
||||
# Distinct transactions, not rows — a transaction split across two
|
||||
# categories (e.g. parent + one of its children) must count once, the
|
||||
# same as a plain transaction filed under just one of them.
|
||||
total_count = len({transaction_id for transaction_id, _, _ in contributions})
|
||||
|
||||
series: list[CategorySpendingPoint] = []
|
||||
year, month = effective_start.year, effective_start.month
|
||||
while (year, month) <= (effective_end.year, effective_end.month):
|
||||
series.append(CategorySpendingPoint(year=year, month=month, amount=by_month.get((year, month), Decimal("0"))))
|
||||
year, month = _next_month(year, month)
|
||||
|
||||
months_count = len(series)
|
||||
average_per_month = (total_amount / months_count).quantize(Decimal("0.01")) if months_count else Decimal("0")
|
||||
|
||||
return _MonthlySummary(
|
||||
start_date=effective_start,
|
||||
end_date=effective_end,
|
||||
total_amount=total_amount,
|
||||
transaction_count=total_count,
|
||||
average_per_month=average_per_month,
|
||||
series=series,
|
||||
)
|
||||
|
||||
|
||||
async def get_category_spending_report(
|
||||
session: AsyncSession, category_id: int, start_date: date_ | None, end_date: date_ | None
|
||||
) -> CategorySpendingReport:
|
||||
@@ -83,40 +151,19 @@ async def get_category_spending_report(
|
||||
if not contributions:
|
||||
return empty
|
||||
|
||||
dates = [txn_date for _, txn_date, _ in contributions]
|
||||
effective_start = start_date or min(dates)
|
||||
effective_end = end_date or max(dates)
|
||||
|
||||
by_month: dict[tuple[int, int], Decimal] = defaultdict(Decimal)
|
||||
for _, txn_date, amount in contributions:
|
||||
by_month[(txn_date.year, txn_date.month)] += amount
|
||||
|
||||
total_amount = sum((amount for _, _, amount in contributions), Decimal("0"))
|
||||
# Distinct transactions, not rows — a transaction split across two of
|
||||
# these categories (e.g. parent + one of its children) must count once,
|
||||
# the same as a plain transaction filed under just one of them.
|
||||
total_count = len({transaction_id for transaction_id, _, _ in contributions})
|
||||
|
||||
series: list[CategorySpendingPoint] = []
|
||||
year, month = effective_start.year, effective_start.month
|
||||
while (year, month) <= (effective_end.year, effective_end.month):
|
||||
series.append(CategorySpendingPoint(year=year, month=month, amount=by_month.get((year, month), Decimal("0"))))
|
||||
year, month = _next_month(year, month)
|
||||
|
||||
months_count = len(series)
|
||||
average_per_month = (total_amount / months_count).quantize(Decimal("0.01")) if months_count else Decimal("0")
|
||||
summary = _summarize_by_month(contributions, start_date, end_date)
|
||||
|
||||
return CategorySpendingReport(
|
||||
category_id=category.id,
|
||||
category_name=category.name,
|
||||
category_color=category.color,
|
||||
category_icon=category.icon,
|
||||
start_date=effective_start,
|
||||
end_date=effective_end,
|
||||
total_amount=total_amount,
|
||||
transaction_count=total_count,
|
||||
average_per_month=average_per_month,
|
||||
series=series,
|
||||
start_date=summary.start_date,
|
||||
end_date=summary.end_date,
|
||||
total_amount=summary.total_amount,
|
||||
transaction_count=summary.transaction_count,
|
||||
average_per_month=summary.average_per_month,
|
||||
series=summary.series,
|
||||
)
|
||||
|
||||
|
||||
@@ -168,3 +215,133 @@ async def get_category_ranking_report(
|
||||
]
|
||||
|
||||
return CategoryRankingReport(start_date=start_date, end_date=end_date, total_amount=total_amount, items=items)
|
||||
|
||||
|
||||
async def _period_total(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
transaction_type: TransactionType,
|
||||
start_date: date_ | None,
|
||||
end_date: date_ | None,
|
||||
tagged_only: bool = False,
|
||||
) -> Decimal:
|
||||
"""Everything spent/earned in the period — or only the part carrying at
|
||||
least one tag. `Transaction.tags.any()` is an EXISTS, so a transaction
|
||||
with three tags is still counted once; summing the ranking's items
|
||||
instead would count it three times."""
|
||||
stmt = select(func.coalesce(func.sum(Transaction.amount), 0)).where(Transaction.type == transaction_type)
|
||||
if tagged_only:
|
||||
stmt = stmt.where(Transaction.tags.any())
|
||||
if start_date is not None:
|
||||
stmt = stmt.where(Transaction.date >= start_date)
|
||||
if end_date is not None:
|
||||
stmt = stmt.where(Transaction.date <= end_date)
|
||||
return Decimal(str((await session.execute(stmt)).scalar_one()))
|
||||
|
||||
|
||||
async def get_tag_ranking_report(
|
||||
session: AsyncSession, kind: CategoryKind, start_date: date_ | None, end_date: date_ | None
|
||||
) -> TagRankingReport:
|
||||
"""Every tag ranked by total spent/earned over an arbitrary period —
|
||||
"which trip/project/person cost the most", the question the category
|
||||
ranking above can't answer because one such answer cuts across several
|
||||
categories at once.
|
||||
|
||||
Each tag is measured against the period's *whole* spending rather than
|
||||
against the other tags: tags overlap, so a denominator built from the
|
||||
items themselves would double-count every multi-tagged transaction and
|
||||
quietly shrink each percentage.
|
||||
"""
|
||||
transaction_type = _KIND_TO_TRANSACTION_TYPE[kind]
|
||||
rows = await rollup_spending_by_tag(
|
||||
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date
|
||||
)
|
||||
total_amount = await _period_total(
|
||||
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date
|
||||
)
|
||||
tagged_amount = await _period_total(
|
||||
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date, tagged_only=True
|
||||
)
|
||||
|
||||
def _percent(amount: Decimal) -> float:
|
||||
return float(amount / total_amount * 100) if total_amount else 0.0
|
||||
|
||||
items = [
|
||||
TagRankingItem(
|
||||
tag_id=row.tag_id,
|
||||
name=row.name,
|
||||
color=row.color,
|
||||
amount=row.amount,
|
||||
percent=_percent(row.amount),
|
||||
transaction_count=row.transaction_count,
|
||||
categories=[
|
||||
TagRankingCategoryItem(
|
||||
category_id=category.category_id, name=category.name, color=category.color,
|
||||
icon=category.icon, amount=category.amount,
|
||||
)
|
||||
for category in row.categories
|
||||
],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
return TagRankingReport(
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
total_amount=total_amount,
|
||||
tagged_amount=tagged_amount,
|
||||
items=items,
|
||||
)
|
||||
|
||||
|
||||
async def get_tag_spending_report(
|
||||
session: AsyncSession, tag_id: int, kind: CategoryKind, start_date: date_ | None, end_date: date_ | None
|
||||
) -> TagSpendingReport:
|
||||
"""One tag's spend over time. Unlike its category twin this needs no
|
||||
split-line union: a tag sits on the transaction itself, so the
|
||||
transaction's own amount is the whole of its contribution however many
|
||||
categories it was split across.
|
||||
|
||||
`kind` is a parameter here rather than a property of the subject — a
|
||||
category is either an expense or an income one, but a tag is neither and
|
||||
can legitimately sit on both sides ("trip:georgia" on the flights and on
|
||||
the refund), so the caller picks which side it's looking at.
|
||||
"""
|
||||
tag = await session.get(Tag, tag_id)
|
||||
if tag is None:
|
||||
raise HTTPException(status_code=404, detail="Tag not found")
|
||||
|
||||
stmt = (
|
||||
select(Transaction.id, Transaction.date, Transaction.amount)
|
||||
.join(transaction_tags, transaction_tags.c.transaction_id == Transaction.id)
|
||||
.where(transaction_tags.c.tag_id == tag_id, Transaction.type == _KIND_TO_TRANSACTION_TYPE[kind])
|
||||
)
|
||||
if start_date is not None:
|
||||
stmt = stmt.where(Transaction.date >= start_date)
|
||||
if end_date is not None:
|
||||
stmt = stmt.where(Transaction.date <= end_date)
|
||||
|
||||
contributions = [(r[0], r[1], r[2]) for r in (await session.execute(stmt)).all()]
|
||||
if not contributions:
|
||||
return TagSpendingReport(
|
||||
tag_id=tag.id,
|
||||
tag_name=tag.name,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
total_amount=Decimal("0"),
|
||||
transaction_count=0,
|
||||
average_per_month=Decimal("0"),
|
||||
series=[],
|
||||
)
|
||||
|
||||
summary = _summarize_by_month(contributions, start_date, end_date)
|
||||
return TagSpendingReport(
|
||||
tag_id=tag.id,
|
||||
tag_name=tag.name,
|
||||
start_date=summary.start_date,
|
||||
end_date=summary.end_date,
|
||||
total_amount=summary.total_amount,
|
||||
transaction_count=summary.transaction_count,
|
||||
average_per_month=summary.average_per_month,
|
||||
series=summary.series,
|
||||
)
|
||||
|
||||
163
backend/app/services/tag_rollup.py
Normal file
163
backend/app/services/tag_rollup.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""Spend/income per tag over a period, with each tag's total broken down by
|
||||
top-level category — the tag-side mirror of category_rollup.py, and the data
|
||||
behind the Reports page's tag ranking.
|
||||
|
||||
Two things follow from where a tag actually lives (models/tag.py: a label on
|
||||
the *transaction*, not on a category or a split line) and make this rollup
|
||||
behave differently from the category one:
|
||||
|
||||
* A tagged transaction contributes its **whole** amount to the tag, even when
|
||||
its categories are split several ways — the split only decides how that
|
||||
amount is attributed *inside* the tag's breakdown, never how much the tag
|
||||
itself is worth.
|
||||
* Tags overlap freely: one transaction can carry any number of them, so tag
|
||||
totals can legitimately sum to more than the period actually saw. Callers
|
||||
must not treat the sum of these items as a period total — see
|
||||
reports_service.get_tag_ranking_report, which measures each tag against the
|
||||
period's real spending instead.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date as date_
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.category import Category
|
||||
from app.models.enums import TransactionType
|
||||
from app.models.tag import Tag, transaction_tags
|
||||
from app.models.transaction import Transaction
|
||||
from app.services.category_rollup import raw_category_contributions
|
||||
|
||||
# Same neutral the category rollup falls back to for a category that no
|
||||
# longer exists — reused here for the "no category at all" bucket.
|
||||
NEUTRAL_COLOR = "#898781"
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagRollupCategoryItem:
|
||||
"""One top-level category's share of a tag's total. category_id is None
|
||||
for the amount that had no category to attribute at all (a transaction
|
||||
saved without one) — kept as an explicit bucket so the breakdown still
|
||||
adds up to the tag's total instead of silently losing money."""
|
||||
|
||||
category_id: int | None
|
||||
name: str
|
||||
color: str
|
||||
icon: str | None
|
||||
amount: Decimal
|
||||
|
||||
|
||||
@dataclass
|
||||
class TagRollupItem:
|
||||
tag_id: int
|
||||
name: str
|
||||
amount: Decimal
|
||||
# Distinct transactions carrying this tag — a transaction_tags row is
|
||||
# unique per (transaction, tag) pair, so every joined row is already one
|
||||
# distinct transaction and no de-duplication is needed here.
|
||||
transaction_count: int
|
||||
# A tag has no color of its own (models/tag.py) — it borrows the color of
|
||||
# the category it spent the most on, so the ranking bar still reads as
|
||||
# "this is mostly restaurants" at a glance. NEUTRAL_COLOR when there's
|
||||
# nothing to borrow from.
|
||||
color: str
|
||||
categories: list[TagRollupCategoryItem] = field(default_factory=list)
|
||||
|
||||
|
||||
async def rollup_spending_by_tag(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
transaction_type: TransactionType,
|
||||
start_date: date_ | None = None,
|
||||
end_date: date_ | None = None,
|
||||
) -> list[TagRollupItem]:
|
||||
"""Every tag's total for the period, sorted by amount desc (tag name as
|
||||
tiebreak so equal-amount tags keep a stable, readable order)."""
|
||||
tag_stmt = (
|
||||
select(Tag.id, Tag.name, Transaction.id, Transaction.amount)
|
||||
.join(transaction_tags, transaction_tags.c.tag_id == Tag.id)
|
||||
.join(Transaction, Transaction.id == transaction_tags.c.transaction_id)
|
||||
.where(Transaction.type == transaction_type)
|
||||
)
|
||||
if start_date is not None:
|
||||
tag_stmt = tag_stmt.where(Transaction.date >= start_date)
|
||||
if end_date is not None:
|
||||
tag_stmt = tag_stmt.where(Transaction.date <= end_date)
|
||||
|
||||
tagged_rows = (await session.execute(tag_stmt)).all()
|
||||
if not tagged_rows:
|
||||
return []
|
||||
|
||||
# The same (transaction_id, category_id, amount) contributions the
|
||||
# category ranking rolls up — reused here to answer "what was this tag
|
||||
# spent on", so a split transaction's share lands under each category it
|
||||
# genuinely touched rather than all under one.
|
||||
contributions = await raw_category_contributions(
|
||||
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date
|
||||
)
|
||||
categories_by_id = {c.id: c for c in (await session.execute(select(Category))).scalars().all()}
|
||||
|
||||
# transaction_id -> {top-level category id: that category's share of it}
|
||||
shares_by_transaction: dict[int, dict[int, Decimal]] = defaultdict(lambda: defaultdict(Decimal))
|
||||
for transaction_id, category_id, amount in contributions:
|
||||
category = categories_by_id.get(category_id)
|
||||
effective_id = category.parent_id if category and category.parent_id is not None else category_id
|
||||
shares_by_transaction[transaction_id][effective_id] += amount
|
||||
|
||||
names: dict[int, str] = {}
|
||||
amount_by_tag: dict[int, Decimal] = defaultdict(Decimal)
|
||||
count_by_tag: dict[int, int] = defaultdict(int)
|
||||
category_amounts: dict[int, dict[int | None, Decimal]] = defaultdict(lambda: defaultdict(Decimal))
|
||||
|
||||
for tag_id, tag_name, transaction_id, amount in tagged_rows:
|
||||
names[tag_id] = tag_name
|
||||
amount_by_tag[tag_id] += amount
|
||||
count_by_tag[tag_id] += 1
|
||||
shares = shares_by_transaction.get(transaction_id)
|
||||
if shares:
|
||||
for effective_id, share in shares.items():
|
||||
category_amounts[tag_id][effective_id] += share
|
||||
else:
|
||||
# Neither a category of its own nor split lines — still real
|
||||
# money the tag is responsible for, so it gets its own bucket.
|
||||
category_amounts[tag_id][None] += amount
|
||||
|
||||
items: list[TagRollupItem] = []
|
||||
for tag_id, amount in amount_by_tag.items():
|
||||
breakdown = [
|
||||
TagRollupCategoryItem(
|
||||
category_id=category_id,
|
||||
name=_category_name(categories_by_id.get(category_id) if category_id is not None else None),
|
||||
color=_category_color(categories_by_id.get(category_id) if category_id is not None else None),
|
||||
icon=categories_by_id[category_id].icon if category_id in categories_by_id else None,
|
||||
amount=category_amount,
|
||||
)
|
||||
for category_id, category_amount in sorted(
|
||||
category_amounts[tag_id].items(), key=lambda pair: -pair[1]
|
||||
)
|
||||
]
|
||||
items.append(
|
||||
TagRollupItem(
|
||||
tag_id=tag_id,
|
||||
name=names[tag_id],
|
||||
amount=amount,
|
||||
transaction_count=count_by_tag[tag_id],
|
||||
color=breakdown[0].color if breakdown else NEUTRAL_COLOR,
|
||||
categories=breakdown,
|
||||
)
|
||||
)
|
||||
items.sort(key=lambda item: (-item.amount, item.name))
|
||||
return items
|
||||
|
||||
|
||||
def _category_name(category: Category | None) -> str:
|
||||
"""An empty name marks the no-category bucket, which the frontend labels
|
||||
from its own translations rather than from a raw backend string (the
|
||||
breakdown is bilingual like every other category label)."""
|
||||
return category.name if category is not None else ""
|
||||
|
||||
|
||||
def _category_color(category: Category | None) -> str:
|
||||
return category.color if category is not None else NEUTRAL_COLOR
|
||||
Reference in New Issue
Block a user