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:
21
DOCS.md
21
DOCS.md
@@ -362,6 +362,23 @@ touches (rolled up to the shared parent), not just once under a single category
|
|||||||
$60/$24.20 between Sweets and Alcohol above contributes exactly those amounts to each subcategory's
|
$60/$24.20 between Sweets and Alcohol above contributes exactly those amounts to each subcategory's
|
||||||
total under Groceries.
|
total under Groceries.
|
||||||
|
|
||||||
|
The tag reports read the same split differently, and deliberately so: a tag sits on the
|
||||||
|
*transaction*, not on a category or a split line, so `/reports/tag-ranking` counts that receipt's
|
||||||
|
full $84.20 toward each tag it carries and uses the split only to say *what the money went on*
|
||||||
|
inside that tag's breakdown. Two consequences worth knowing before building on these numbers:
|
||||||
|
|
||||||
|
- **Tag totals overlap.** One transaction can carry any number of tags and each owns it whole, so
|
||||||
|
summing the ranking's `items` can exceed what the period actually saw. Each item's `percent` is
|
||||||
|
therefore measured against `total_amount` — everything spent in the period, tagged or not — and
|
||||||
|
the percentages are each meaningful on their own but do not add up to 100.
|
||||||
|
- **`tagged_amount` counts each transaction once**, however many tags it has, so
|
||||||
|
`total_amount - tagged_amount` is exactly the untagged remainder — i.e. how much of the period
|
||||||
|
these tags actually account for.
|
||||||
|
|
||||||
|
A tag has no `kind` of its own (a category is either an expense or an income one, but the same tag
|
||||||
|
can sit on both sides of the ledger), which is why `kind` is a query parameter on both tag
|
||||||
|
endpoints rather than a property of the subject.
|
||||||
|
|
||||||
### Bulk create (`POST /transactions/bulk`)
|
### Bulk create (`POST /transactions/bulk`)
|
||||||
|
|
||||||
Used by the CSV import wizard, but callable directly for any bulk load (e.g. syncing from a bank
|
Used by the CSV import wizard, but callable directly for any bulk load (e.g. syncing from a bank
|
||||||
@@ -715,6 +732,8 @@ into an external dashboard without recomputing it yourself.
|
|||||||
| `GET` | `/cash-flow` | Income vs. expense, month by month. `?start_date=&end_date=` (default: no bound, i.e. all history). |
|
| `GET` | `/cash-flow` | Income vs. expense, month by month. `?start_date=&end_date=` (default: no bound, i.e. all history). |
|
||||||
| `GET` | `/reports/category-spending` | One category's spend over time. `?category_id=` (required) `&start_date=&end_date=`. |
|
| `GET` | `/reports/category-spending` | One category's spend over time. `?category_id=` (required) `&start_date=&end_date=`. |
|
||||||
| `GET` | `/reports/category-ranking` | All categories ranked by total spend over a period. `?kind=expense\|income` (default `expense`) `&start_date=&end_date=`. |
|
| `GET` | `/reports/category-ranking` | All categories ranked by total spend over a period. `?kind=expense\|income` (default `expense`) `&start_date=&end_date=`. |
|
||||||
|
| `GET` | `/reports/tag-ranking` | All tags ranked by total spend over a period, each with a per-category breakdown. `?kind=expense\|income` (default `expense`) `&start_date=&end_date=`. |
|
||||||
|
| `GET` | `/reports/tag-spending` | One tag's spend over time. `?tag_id=` (required) `&kind=expense\|income` (default `expense`) `&start_date=&end_date=`. |
|
||||||
|
|
||||||
**`GET /dashboard/summary` response:**
|
**`GET /dashboard/summary` response:**
|
||||||
|
|
||||||
@@ -778,7 +797,7 @@ Single row, created automatically on first run — there's nothing to create, on
|
|||||||
"risky_allocation_threshold_percent": 20,
|
"risky_allocation_threshold_percent": 20,
|
||||||
"idle_cash_threshold_amount": "1000.00",
|
"idle_cash_threshold_amount": "1000.00",
|
||||||
"idle_cash_threshold_days": 60,
|
"idle_cash_threshold_days": 60,
|
||||||
"app_version": "1.1.8"
|
"app_version": "1.1.9"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ A CoinMarketCap-style portfolio tab for the coins you actually hold: live price
|
|||||||
Set a monthly limit per category and watch progress bars fill up. Track savings goals with a running contribution log. Register recurring bills and post them with one click when they're due — nothing runs automatically in the background.
|
Set a monthly limit per category and watch progress bars fill up. Track savings goals with a running contribution log. Register recurring bills and post them with one click when they're due — nothing runs automatically in the background.
|
||||||
|
|
||||||
### 📊 Reports & Advice
|
### 📊 Reports & Advice
|
||||||
Rank every category by total spend over any custom period to find what's actually eating your budget. A rules-based Advice tab surfaces rising spending categories, unbudgeted top expenses, and month-over-month savings rate trends in plain language.
|
Rank every category by total spend over any custom period to find what's actually eating your budget — or switch the same report to rank **tags** instead, to total up a trip, an occasion or a person across every category at once (each tag broken down by what the money went on, and measured against the whole period so you can see how much of it your tags actually cover). A rules-based Advice tab surfaces rising spending categories, unbudgeted top expenses, and month-over-month savings rate trends in plain language.
|
||||||
|
|
||||||
### 🧮 Returns Calculator
|
### 🧮 Returns Calculator
|
||||||
A standalone ROI calculator: enter what you'd invest and what it would pay you monthly, and see the annual return, payback period, and a compound-interest projection — with a year-by-year comparison chart of compounding vs. just banking the cash — before you commit to a purchase.
|
A standalone ROI calculator: enter what you'd invest and what it would pay you monthly, and see the annual return, payback period, and a compound-interest projection — with a year-by-year comparison chart of compounding vs. just banking the cash — before you commit to a purchase.
|
||||||
|
|||||||
@@ -5,8 +5,18 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.api.deps import get_session
|
from app.api.deps import get_session
|
||||||
from app.models.enums import CategoryKind
|
from app.models.enums import CategoryKind
|
||||||
from app.schemas.reports import CategoryRankingReport, CategorySpendingReport
|
from app.schemas.reports import (
|
||||||
from app.services.reports_service import get_category_ranking_report, get_category_spending_report
|
CategoryRankingReport,
|
||||||
|
CategorySpendingReport,
|
||||||
|
TagRankingReport,
|
||||||
|
TagSpendingReport,
|
||||||
|
)
|
||||||
|
from app.services.reports_service import (
|
||||||
|
get_category_ranking_report,
|
||||||
|
get_category_spending_report,
|
||||||
|
get_tag_ranking_report,
|
||||||
|
get_tag_spending_report,
|
||||||
|
)
|
||||||
|
|
||||||
router = APIRouter(prefix="/reports", tags=["reports"])
|
router = APIRouter(prefix="/reports", tags=["reports"])
|
||||||
|
|
||||||
@@ -29,3 +39,24 @@ async def read_category_ranking_report(
|
|||||||
session: AsyncSession = Depends(get_session),
|
session: AsyncSession = Depends(get_session),
|
||||||
) -> CategoryRankingReport:
|
) -> CategoryRankingReport:
|
||||||
return await get_category_ranking_report(session, kind, start_date, end_date)
|
return await get_category_ranking_report(session, kind, start_date, end_date)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tag-ranking", response_model=TagRankingReport)
|
||||||
|
async def read_tag_ranking_report(
|
||||||
|
kind: CategoryKind = CategoryKind.EXPENSE,
|
||||||
|
start_date: date_ | None = Query(default=None),
|
||||||
|
end_date: date_ | None = Query(default=None),
|
||||||
|
session: AsyncSession = Depends(get_session),
|
||||||
|
) -> TagRankingReport:
|
||||||
|
return await get_tag_ranking_report(session, kind, start_date, end_date)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tag-spending", response_model=TagSpendingReport)
|
||||||
|
async def read_tag_spending_report(
|
||||||
|
tag_id: int,
|
||||||
|
kind: CategoryKind = CategoryKind.EXPENSE,
|
||||||
|
start_date: date_ | None = Query(default=None),
|
||||||
|
end_date: date_ | None = Query(default=None),
|
||||||
|
session: AsyncSession = Depends(get_session),
|
||||||
|
) -> TagSpendingReport:
|
||||||
|
return await get_tag_spending_report(session, tag_id, kind, start_date, end_date)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||||||
# it in Settings; it deliberately does NOT ride on the unauthenticated
|
# it in Settings; it deliberately does NOT ride on the unauthenticated
|
||||||
# /api/health), and embedded in exported backups so an old file can be told
|
# /api/health), and embedded in exported backups so an old file can be told
|
||||||
# apart from a current one.
|
# apart from a current one.
|
||||||
APP_VERSION = "1.1.8"
|
APP_VERSION = "1.1.9"
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
|
|||||||
@@ -54,3 +54,57 @@ class CategoryRankingReport(BaseModel):
|
|||||||
end_date: date_ | None
|
end_date: date_ | None
|
||||||
total_amount: Decimal
|
total_amount: Decimal
|
||||||
items: list[CategoryRankingItem]
|
items: list[CategoryRankingItem]
|
||||||
|
|
||||||
|
|
||||||
|
class TagRankingCategoryItem(BaseModel):
|
||||||
|
"""One top-level category's share of a tag's total — see
|
||||||
|
services/tag_rollup.py's TagRollupCategoryItem. category_id is null (and
|
||||||
|
name empty) for the share that had no category at all."""
|
||||||
|
|
||||||
|
category_id: int | None
|
||||||
|
name: str
|
||||||
|
color: str
|
||||||
|
icon: str | None
|
||||||
|
amount: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
class TagRankingItem(BaseModel):
|
||||||
|
tag_id: int
|
||||||
|
name: str
|
||||||
|
color: str
|
||||||
|
amount: Decimal
|
||||||
|
# Share of the period's *total* spending of this kind, not of the tagged
|
||||||
|
# part of it — tags overlap, so these percentages are each meaningful on
|
||||||
|
# their own but deliberately don't add up to 100.
|
||||||
|
percent: float
|
||||||
|
transaction_count: int
|
||||||
|
categories: list[TagRankingCategoryItem] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class TagRankingReport(BaseModel):
|
||||||
|
start_date: date_ | None
|
||||||
|
end_date: date_ | None
|
||||||
|
# Everything spent/earned in the period, tagged or not — the denominator
|
||||||
|
# behind each item's percent.
|
||||||
|
total_amount: Decimal
|
||||||
|
# The part of total_amount carrying at least one tag, counted once per
|
||||||
|
# transaction however many tags it has. total_amount - tagged_amount is
|
||||||
|
# what's still untagged, so the two together say how much of the period
|
||||||
|
# this report actually covers.
|
||||||
|
tagged_amount: Decimal
|
||||||
|
items: list[TagRankingItem]
|
||||||
|
|
||||||
|
|
||||||
|
class TagSpendingReport(BaseModel):
|
||||||
|
"""One tag's month-by-month total — the tag-side twin of
|
||||||
|
CategorySpendingReport, reusing its CategorySpendingPoint since a point
|
||||||
|
is just (year, month, amount) either way."""
|
||||||
|
|
||||||
|
tag_id: int
|
||||||
|
tag_name: str
|
||||||
|
start_date: date_ | None
|
||||||
|
end_date: date_ | None
|
||||||
|
total_amount: Decimal
|
||||||
|
transaction_count: int
|
||||||
|
average_per_month: Decimal
|
||||||
|
series: list[CategorySpendingPoint]
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ class CategoryRollupItem:
|
|||||||
children: list[CategoryRollupChildItem] = field(default_factory=list)
|
children: list[CategoryRollupChildItem] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
async def _raw_category_contributions(
|
async def raw_category_contributions(
|
||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
*,
|
*,
|
||||||
transaction_type: TransactionType,
|
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
|
"""Every top-level category's total for the period, sorted by amount
|
||||||
desc (category sort_order as tiebreak — same order the SQL-only version
|
desc (category sort_order as tiebreak — same order the SQL-only version
|
||||||
used to produce)."""
|
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
|
session, transaction_type=transaction_type, start_date=start_date, end_date=end_date
|
||||||
)
|
)
|
||||||
if not contributions:
|
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
|
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 cost the most over this whole period" (ranking, across all
|
||||||
categories of one kind at once, not just the current month).
|
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 collections import defaultdict
|
||||||
from datetime import date as date_
|
from datetime import date as date_
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
from typing import NamedTuple
|
||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from sqlalchemy import select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.models.category import Category
|
from app.models.category import Category
|
||||||
from app.models.enums import CategoryKind, TransactionType
|
from app.models.enums import CategoryKind, TransactionType
|
||||||
|
from app.models.tag import Tag, transaction_tags
|
||||||
from app.models.transaction import Transaction, TransactionSplit
|
from app.models.transaction import Transaction, TransactionSplit
|
||||||
from app.schemas.reports import (
|
from app.schemas.reports import (
|
||||||
CategoryRankingChildItem,
|
CategoryRankingChildItem,
|
||||||
@@ -21,14 +29,74 @@ from app.schemas.reports import (
|
|||||||
CategoryRankingReport,
|
CategoryRankingReport,
|
||||||
CategorySpendingPoint,
|
CategorySpendingPoint,
|
||||||
CategorySpendingReport,
|
CategorySpendingReport,
|
||||||
|
TagRankingCategoryItem,
|
||||||
|
TagRankingItem,
|
||||||
|
TagRankingReport,
|
||||||
|
TagSpendingReport,
|
||||||
)
|
)
|
||||||
from app.services.category_rollup import rollup_spending_by_top_level_category
|
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]:
|
def _next_month(year: int, month: int) -> tuple[int, int]:
|
||||||
return (year + 1, 1) if month == 12 else (year, month + 1)
|
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(
|
async def get_category_spending_report(
|
||||||
session: AsyncSession, category_id: int, start_date: date_ | None, end_date: date_ | None
|
session: AsyncSession, category_id: int, start_date: date_ | None, end_date: date_ | None
|
||||||
) -> CategorySpendingReport:
|
) -> CategorySpendingReport:
|
||||||
@@ -83,40 +151,19 @@ async def get_category_spending_report(
|
|||||||
if not contributions:
|
if not contributions:
|
||||||
return empty
|
return empty
|
||||||
|
|
||||||
dates = [txn_date for _, txn_date, _ in contributions]
|
summary = _summarize_by_month(contributions, start_date, end_date)
|
||||||
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")
|
|
||||||
|
|
||||||
return CategorySpendingReport(
|
return CategorySpendingReport(
|
||||||
category_id=category.id,
|
category_id=category.id,
|
||||||
category_name=category.name,
|
category_name=category.name,
|
||||||
category_color=category.color,
|
category_color=category.color,
|
||||||
category_icon=category.icon,
|
category_icon=category.icon,
|
||||||
start_date=effective_start,
|
start_date=summary.start_date,
|
||||||
end_date=effective_end,
|
end_date=summary.end_date,
|
||||||
total_amount=total_amount,
|
total_amount=summary.total_amount,
|
||||||
transaction_count=total_count,
|
transaction_count=summary.transaction_count,
|
||||||
average_per_month=average_per_month,
|
average_per_month=summary.average_per_month,
|
||||||
series=series,
|
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)
|
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
|
||||||
235
backend/tests/test_tag_reports.py
Normal file
235
backend/tests/test_tag_reports.py
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
"""Tag reports: the ranking (which tag cost the most over a period, and on
|
||||||
|
what) and the single-tag spending detail.
|
||||||
|
|
||||||
|
What separates these from the category reports in test_reports.py is that a
|
||||||
|
tag lives on the transaction, not on a category or a split line
|
||||||
|
(models/tag.py) — so a tagged transaction counts in full toward its tag
|
||||||
|
however its categories are split, and two tags on one transaction each
|
||||||
|
count it whole.
|
||||||
|
"""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from tests.helpers import money, txn_payload as _txn
|
||||||
|
|
||||||
|
|
||||||
|
async def _tag(client: AsyncClient, name: str) -> int:
|
||||||
|
return (await client.post("/tags", json={"name": name})).json()["id"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ranking_sums_a_tag_across_categories(client: AsyncClient, account_id, categories):
|
||||||
|
"""The point of the report: one tag's total cutting across the
|
||||||
|
categories the category ranking would have scattered it over."""
|
||||||
|
together = await _tag(client, "together")
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(account_id, amount="60.00", category_id=categories["Dining Out"]["id"], tag_ids=[together]),
|
||||||
|
)
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(account_id, amount="40.00", category_id=categories["Shopping"]["id"], tag_ids=[together]),
|
||||||
|
)
|
||||||
|
|
||||||
|
resp = await client.get("/reports/tag-ranking", params={"kind": "expense"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
item = resp.json()["items"][0]
|
||||||
|
|
||||||
|
assert item["name"] == "together"
|
||||||
|
assert money(item["amount"]) == Decimal("100.00")
|
||||||
|
assert item["transaction_count"] == 2
|
||||||
|
breakdown = {c["name"]: money(c["amount"]) for c in item["categories"]}
|
||||||
|
assert breakdown == {"Dining Out": Decimal("60.00"), "Shopping": Decimal("40.00")}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ranking_counts_a_split_transaction_whole_but_breaks_it_down(client: AsyncClient, account_id, categories):
|
||||||
|
"""A split decides how the tag's total is attributed inside the
|
||||||
|
breakdown, never how much the tag itself is worth."""
|
||||||
|
groceries = categories["Groceries"]["id"]
|
||||||
|
sweets = (
|
||||||
|
await client.post(
|
||||||
|
"/categories", json={"name": "Sweets", "kind": "expense", "color": "#7a869a", "parent_id": groceries}
|
||||||
|
)
|
||||||
|
).json()["id"]
|
||||||
|
gifts = await _tag(client, "gifts")
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(
|
||||||
|
account_id,
|
||||||
|
amount="100.00",
|
||||||
|
category_id=None,
|
||||||
|
tag_ids=[gifts],
|
||||||
|
splits=[
|
||||||
|
{"category_id": groceries, "amount": "70.00"},
|
||||||
|
{"category_id": sweets, "amount": "30.00"},
|
||||||
|
],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
item = (await client.get("/reports/tag-ranking", params={"kind": "expense"})).json()["items"][0]
|
||||||
|
|
||||||
|
assert money(item["amount"]) == Decimal("100.00")
|
||||||
|
assert item["transaction_count"] == 1
|
||||||
|
# Rolled up to the top-level category, same as everywhere else in the app.
|
||||||
|
assert [(c["name"], money(c["amount"])) for c in item["categories"]] == [("Groceries", Decimal("100.00"))]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_two_tags_on_one_transaction_each_count_it_whole(client: AsyncClient, account_id, categories):
|
||||||
|
date_night = await _tag(client, "date-night")
|
||||||
|
anniversary = await _tag(client, "anniversary")
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(
|
||||||
|
account_id,
|
||||||
|
amount="80.00",
|
||||||
|
category_id=categories["Dining Out"]["id"],
|
||||||
|
tag_ids=[date_night, anniversary],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-ranking", params={"kind": "expense"})).json()
|
||||||
|
amounts = {item["name"]: money(item["amount"]) for item in body["items"]}
|
||||||
|
|
||||||
|
assert amounts == {"date-night": Decimal("80.00"), "anniversary": Decimal("80.00")}
|
||||||
|
# Overlapping tags must not inflate the period's own totals: the
|
||||||
|
# transaction is one 80.00 expense, counted once on both lines.
|
||||||
|
assert money(body["total_amount"]) == Decimal("80.00")
|
||||||
|
assert money(body["tagged_amount"]) == Decimal("80.00")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_percent_is_measured_against_all_spending_not_just_tagged(client: AsyncClient, account_id, categories):
|
||||||
|
gifts = await _tag(client, "gifts")
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(account_id, amount="25.00", category_id=categories["Shopping"]["id"], tag_ids=[gifts]),
|
||||||
|
)
|
||||||
|
await client.post("/transactions", json=_txn(account_id, amount="75.00", category_id=categories["Groceries"]["id"]))
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-ranking", params={"kind": "expense"})).json()
|
||||||
|
|
||||||
|
assert money(body["total_amount"]) == Decimal("100.00")
|
||||||
|
assert money(body["tagged_amount"]) == Decimal("25.00")
|
||||||
|
assert body["items"][0]["percent"] == 25.0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ranking_keeps_an_uncategorized_amount_in_its_own_bucket(client: AsyncClient, account_id):
|
||||||
|
"""A transaction saved without a category is still real money the tag
|
||||||
|
owns — it gets a null-category bucket rather than dropping out of the
|
||||||
|
breakdown and leaving it short of the tag's total."""
|
||||||
|
misc = await _tag(client, "misc")
|
||||||
|
await client.post("/transactions", json=_txn(account_id, amount="15.00", category_id=None, tag_ids=[misc]))
|
||||||
|
|
||||||
|
item = (await client.get("/reports/tag-ranking", params={"kind": "expense"})).json()["items"][0]
|
||||||
|
|
||||||
|
assert money(item["amount"]) == Decimal("15.00")
|
||||||
|
assert [(c["category_id"], money(c["amount"])) for c in item["categories"]] == [(None, Decimal("15.00"))]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ranking_respects_kind_and_date_range(client: AsyncClient, account_id, categories):
|
||||||
|
shared = await _tag(client, "shared")
|
||||||
|
dining = categories["Dining Out"]["id"]
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(account_id, amount="30.00", category_id=dining, tag_ids=[shared], date="2026-03-10"),
|
||||||
|
)
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(account_id, amount="50.00", category_id=dining, tag_ids=[shared], date="2026-07-10"),
|
||||||
|
)
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(
|
||||||
|
account_id,
|
||||||
|
type="income",
|
||||||
|
amount="900.00",
|
||||||
|
category_id=categories["Salary"]["id"],
|
||||||
|
tag_ids=[shared],
|
||||||
|
date="2026-03-05",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
ranged = await client.get(
|
||||||
|
"/reports/tag-ranking",
|
||||||
|
params={"kind": "expense", "start_date": "2026-01-01", "end_date": "2026-06-30"},
|
||||||
|
)
|
||||||
|
assert money(ranged.json()["items"][0]["amount"]) == Decimal("30.00")
|
||||||
|
|
||||||
|
income = await client.get("/reports/tag-ranking", params={"kind": "income"})
|
||||||
|
assert money(income.json()["items"][0]["amount"]) == Decimal("900.00")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tag_spending_report_series_fills_gap_months(client: AsyncClient, account_id, categories):
|
||||||
|
trip = await _tag(client, "trip")
|
||||||
|
dining = categories["Dining Out"]["id"]
|
||||||
|
await client.post(
|
||||||
|
"/transactions", json=_txn(account_id, amount="10.00", category_id=dining, tag_ids=[trip], date="2026-01-15")
|
||||||
|
)
|
||||||
|
await client.post(
|
||||||
|
"/transactions", json=_txn(account_id, amount="20.00", category_id=dining, tag_ids=[trip], date="2026-03-15")
|
||||||
|
)
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-spending", params={"tag_id": trip})).json()
|
||||||
|
|
||||||
|
assert body["tag_name"] == "trip"
|
||||||
|
assert money(body["total_amount"]) == Decimal("30.00")
|
||||||
|
assert body["transaction_count"] == 2
|
||||||
|
assert [(p["month"], money(p["amount"])) for p in body["series"]] == [
|
||||||
|
(1, Decimal("10.00")),
|
||||||
|
(2, Decimal("0")),
|
||||||
|
(3, Decimal("20.00")),
|
||||||
|
]
|
||||||
|
assert money(body["average_per_month"]) == Decimal("10.00")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tag_spending_report_counts_a_split_transaction_once(client: AsyncClient, account_id, categories):
|
||||||
|
"""The category detail report has to de-duplicate split lines; the tag
|
||||||
|
one never sees them, so a split transaction is one row worth its full
|
||||||
|
amount."""
|
||||||
|
groceries = categories["Groceries"]["id"]
|
||||||
|
sweets = (
|
||||||
|
await client.post(
|
||||||
|
"/categories", json={"name": "Sweets", "kind": "expense", "color": "#7a869a", "parent_id": groceries}
|
||||||
|
)
|
||||||
|
).json()["id"]
|
||||||
|
trip = await _tag(client, "trip")
|
||||||
|
await client.post(
|
||||||
|
"/transactions",
|
||||||
|
json=_txn(
|
||||||
|
account_id,
|
||||||
|
amount="100.00",
|
||||||
|
category_id=None,
|
||||||
|
tag_ids=[trip],
|
||||||
|
splits=[
|
||||||
|
{"category_id": groceries, "amount": "60.00"},
|
||||||
|
{"category_id": sweets, "amount": "40.00"},
|
||||||
|
],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-spending", params={"tag_id": trip})).json()
|
||||||
|
|
||||||
|
assert money(body["total_amount"]) == Decimal("100.00")
|
||||||
|
assert body["transaction_count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tag_spending_report_is_empty_for_an_unused_tag(client: AsyncClient):
|
||||||
|
unused = await _tag(client, "unused")
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-spending", params={"tag_id": unused})).json()
|
||||||
|
|
||||||
|
assert money(body["total_amount"]) == Decimal("0")
|
||||||
|
assert body["series"] == []
|
||||||
|
|
||||||
|
|
||||||
|
async def test_tag_spending_report_404s_for_a_missing_tag(client: AsyncClient):
|
||||||
|
assert (await client.get("/reports/tag-spending", params={"tag_id": 9999})).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
async def test_ranking_is_empty_when_nothing_is_tagged(client: AsyncClient, account_id, categories):
|
||||||
|
await client.post("/transactions", json=_txn(account_id, amount="10.00", category_id=categories["Groceries"]["id"]))
|
||||||
|
|
||||||
|
body = (await client.get("/reports/tag-ranking", params={"kind": "expense"})).json()
|
||||||
|
|
||||||
|
assert body["items"] == []
|
||||||
|
assert money(body["tagged_amount"]) == Decimal("0")
|
||||||
|
assert money(body["total_amount"]) == Decimal("10.00")
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "aurum-frontend",
|
"name": "aurum-frontend",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.1.8",
|
"version": "1.1.9",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import { api } from "@/api/client";
|
import { api } from "@/api/client";
|
||||||
import type { CategoryKind, CategoryRankingReport, CategorySpendingReport } from "@/types";
|
import type {
|
||||||
|
CategoryKind,
|
||||||
|
CategoryRankingReport,
|
||||||
|
CategorySpendingReport,
|
||||||
|
TagRankingReport,
|
||||||
|
TagSpendingReport,
|
||||||
|
} from "@/types";
|
||||||
|
|
||||||
export function fetchCategorySpendingReport(categoryId: number, startDate?: string, endDate?: string) {
|
export function fetchCategorySpendingReport(categoryId: number, startDate?: string, endDate?: string) {
|
||||||
const params = new URLSearchParams({ category_id: String(categoryId) });
|
const params = new URLSearchParams({ category_id: String(categoryId) });
|
||||||
@@ -14,3 +20,21 @@ export function fetchCategoryRanking(kind: CategoryKind, startDate?: string, end
|
|||||||
if (endDate) params.set("end_date", endDate);
|
if (endDate) params.set("end_date", endDate);
|
||||||
return api.get<CategoryRankingReport>(`/reports/category-ranking?${params.toString()}`);
|
return api.get<CategoryRankingReport>(`/reports/category-ranking?${params.toString()}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `kind` is a parameter on both tag endpoints rather than a property of the
|
||||||
|
// tag: a category is either an expense or an income one, but a tag can sit
|
||||||
|
// on both sides of the ledger, so the caller picks which side it's asking
|
||||||
|
// about (see backend/app/services/reports_service.py).
|
||||||
|
export function fetchTagRanking(kind: CategoryKind, startDate?: string, endDate?: string) {
|
||||||
|
const params = new URLSearchParams({ kind });
|
||||||
|
if (startDate) params.set("start_date", startDate);
|
||||||
|
if (endDate) params.set("end_date", endDate);
|
||||||
|
return api.get<TagRankingReport>(`/reports/tag-ranking?${params.toString()}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchTagSpendingReport(tagId: number, kind: CategoryKind, startDate?: string, endDate?: string) {
|
||||||
|
const params = new URLSearchParams({ tag_id: String(tagId), kind });
|
||||||
|
if (startDate) params.set("start_date", startDate);
|
||||||
|
if (endDate) params.set("end_date", endDate);
|
||||||
|
return api.get<TagSpendingReport>(`/reports/tag-spending?${params.toString()}`);
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import { useTranslation } from "@/lib/i18n";
|
|||||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||||
|
|
||||||
interface CategoryBreakdownChild {
|
interface CategoryBreakdownChild {
|
||||||
category_id: number;
|
// Null only on the tag side: the share of a tag's total that had no
|
||||||
|
// category at all (a transaction saved without one).
|
||||||
|
category_id: number | null;
|
||||||
name: string;
|
name: string;
|
||||||
color: string;
|
color: string;
|
||||||
icon: string | null;
|
icon: string | null;
|
||||||
@@ -15,23 +17,32 @@ interface CategoryBreakdownChild {
|
|||||||
interface CategoryBreakdownModalProps {
|
interface CategoryBreakdownModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
categoryId: number;
|
/** The parent category being broken down — the child row matching it is
|
||||||
|
* the "no subcategory" share. Omitted by the tag ranking, where the rows
|
||||||
|
* are categories and no one of them is the subject itself. */
|
||||||
|
categoryId?: number;
|
||||||
|
/** Shown as-is instead of `categoryName` run through the default-category
|
||||||
|
* translations — used by the tag ranking, whose subject is a user-typed
|
||||||
|
* tag name that must never be translated. */
|
||||||
|
title?: string;
|
||||||
categoryName: string;
|
categoryName: string;
|
||||||
totalAmount: string;
|
totalAmount: string;
|
||||||
children: CategoryBreakdownChild[];
|
children: CategoryBreakdownChild[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Shows how a parent category's total splits across its subcategories — a
|
/** Shows how a total splits across the categories that fed it — a modal
|
||||||
* modal rather than an inline expansion, since a category with many
|
* rather than an inline expansion, since a subject with many parts (or many
|
||||||
* subcategories (or many split-across purchases) would otherwise push the
|
* split-across purchases) would otherwise push the Dashboard's donut/list
|
||||||
* Dashboard's donut/list layout out of alignment as rows grow taller. Shared
|
* layout out of alignment as rows grow taller. Shared by the Dashboard
|
||||||
* between the Dashboard breakdown and the Reports category ranking, which
|
* breakdown and the Reports category ranking, which expose the same shape
|
||||||
* expose the same shape (see services/category_rollup.py's
|
* (see services/category_rollup.py's CategoryRollupChildItem), and by the
|
||||||
* CategoryRollupChildItem). */
|
* Reports tag ranking, whose rows are that tag's categories instead
|
||||||
|
* (services/tag_rollup.py's TagRollupCategoryItem). */
|
||||||
export function CategoryBreakdownModal({
|
export function CategoryBreakdownModal({
|
||||||
open,
|
open,
|
||||||
onClose,
|
onClose,
|
||||||
categoryId,
|
categoryId,
|
||||||
|
title,
|
||||||
categoryName,
|
categoryName,
|
||||||
totalAmount,
|
totalAmount,
|
||||||
children,
|
children,
|
||||||
@@ -40,7 +51,7 @@ export function CategoryBreakdownModal({
|
|||||||
const total = Number(totalAmount);
|
const total = Number(totalAmount);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onClose={onClose} title={translateCategoryName(categoryName)}>
|
<Dialog open={open} onClose={onClose} title={title ?? translateCategoryName(categoryName)}>
|
||||||
<div className="mb-3 flex items-center justify-between border-b border-gridline pb-3 text-sm">
|
<div className="mb-3 flex items-center justify-between border-b border-gridline pb-3 text-sm">
|
||||||
<span className="text-text-muted">{t("reports.categoryBreakdownTotalLabel")}</span>
|
<span className="text-text-muted">{t("reports.categoryBreakdownTotalLabel")}</span>
|
||||||
<span className="font-semibold tabular-nums text-text-primary">{formatCurrency(totalAmount)}</span>
|
<span className="font-semibold tabular-nums text-text-primary">{formatCurrency(totalAmount)}</span>
|
||||||
@@ -49,9 +60,14 @@ export function CategoryBreakdownModal({
|
|||||||
{children.map((child) => {
|
{children.map((child) => {
|
||||||
const Icon = getCategoryIcon(child.icon);
|
const Icon = getCategoryIcon(child.icon);
|
||||||
const percent = total ? (Number(child.amount) / total) * 100 : 0;
|
const percent = total ? (Number(child.amount) / total) * 100 : 0;
|
||||||
const label = child.category_id === categoryId ? t("reports.directSpendLabel") : translateCategoryName(child.name);
|
const label =
|
||||||
|
child.category_id === null
|
||||||
|
? t("reports.noCategoryLabel")
|
||||||
|
: child.category_id === categoryId
|
||||||
|
? t("reports.directSpendLabel")
|
||||||
|
: translateCategoryName(child.name);
|
||||||
return (
|
return (
|
||||||
<li key={child.category_id} className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0">
|
<li key={child.category_id ?? "uncategorized"} className="flex items-center gap-3 py-2.5 first:pt-0 last:pb-0">
|
||||||
<span
|
<span
|
||||||
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
|
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
|
||||||
style={{ backgroundColor: `${child.color}26` }}
|
style={{ backgroundColor: `${child.color}26` }}
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis } from "recharts";
|
import { SpendingTrendChart } from "@/components/reports/SpendingTrendChart";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
|
||||||
import { formatCurrency, getIntlLocale, pluralizeRu } from "@/lib/format";
|
|
||||||
import { useTranslation, type Language } from "@/lib/i18n";
|
|
||||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||||
import type { CategorySpendingReport } from "@/types";
|
import type { CategorySpendingReport } from "@/types";
|
||||||
|
|
||||||
@@ -10,105 +7,20 @@ interface CategorySpendingChartProps {
|
|||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function monthKey(year: number, month: number): string {
|
/** One category's spend month by month. The drawing itself lives in
|
||||||
return `${year}-${String(month).padStart(2, "0")}-01`;
|
* SpendingTrendChart, shared with the tag side — this only maps the report
|
||||||
}
|
* onto it and resolves the category's name through the default-category
|
||||||
|
* translations. */
|
||||||
function formatMonthLabel(key: string): string {
|
|
||||||
return new Intl.DateTimeFormat(getIntlLocale(), { month: "short", year: "numeric" }).format(
|
|
||||||
new Date(`${key}T00:00:00`)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function transactionsCountLabel(count: number, language: Language): string {
|
|
||||||
if (language === "ru") return pluralizeRu(count, "транзакция", "транзакции", "транзакций");
|
|
||||||
return count === 1 ? "transaction" : "transactions";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Same landmark idea as the Net Worth chart: year ticks only when the bars
|
|
||||||
* span more than one calendar year, so a 5-year report reads at a glance. */
|
|
||||||
function computeYearTicks(keys: string[]): string[] {
|
|
||||||
if (keys.length < 2) return [];
|
|
||||||
const startYear = Number(keys[0].slice(0, 4));
|
|
||||||
const endYear = Number(keys[keys.length - 1].slice(0, 4));
|
|
||||||
if (startYear === endYear) return [];
|
|
||||||
const ticks: string[] = [];
|
|
||||||
for (let year = startYear + 1; year <= endYear; year++) {
|
|
||||||
const jan = `${year}-01-01`;
|
|
||||||
if (keys.includes(jan)) ticks.push(jan);
|
|
||||||
}
|
|
||||||
return ticks;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ChartTooltip({ active, payload }: { active?: boolean; payload?: Array<{ payload: { key: string; amount: number } }> }) {
|
|
||||||
if (!active || !payload?.length) return null;
|
|
||||||
const point = payload[0].payload;
|
|
||||||
return (
|
|
||||||
<div className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm shadow-md">
|
|
||||||
<p className="text-text-muted">{formatMonthLabel(point.key)}</p>
|
|
||||||
<p className="font-medium text-text-primary">{formatCurrency(point.amount)}</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CategorySpendingChart({ report, isLoading }: CategorySpendingChartProps) {
|
export function CategorySpendingChart({ report, isLoading }: CategorySpendingChartProps) {
|
||||||
const { t, language } = useTranslation();
|
|
||||||
const chartData = report?.series.map((point) => ({
|
|
||||||
key: monthKey(point.year, point.month),
|
|
||||||
amount: Number(point.amount),
|
|
||||||
})) ?? [];
|
|
||||||
const yearTicks = computeYearTicks(chartData.map((point) => point.key));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<SpendingTrendChart
|
||||||
<CardHeader className="items-start">
|
title={report ? translateCategoryName(report.category_name) : undefined}
|
||||||
<div>
|
color={report?.category_color ?? "#898781"}
|
||||||
<CardTitle>{report ? translateCategoryName(report.category_name) : t("reports.defaultChartTitle")}</CardTitle>
|
totalAmount={report?.total_amount}
|
||||||
<p className="mt-1.5 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
averagePerMonth={report?.average_per_month}
|
||||||
{isLoading || !report ? "…" : formatCurrency(report.total_amount)}
|
transactionCount={report?.transaction_count}
|
||||||
</p>
|
series={report?.series}
|
||||||
{report && (
|
isLoading={isLoading}
|
||||||
<p className="mt-1 text-sm text-text-muted">
|
/>
|
||||||
{t("reports.averagePerMonth", { amount: formatCurrency(report.average_per_month) })} ·{" "}
|
|
||||||
{report.transaction_count} {transactionsCountLabel(report.transaction_count, language)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="h-56 w-full sm:h-64">
|
|
||||||
{isLoading || !report || chartData.length === 0 ? (
|
|
||||||
<div className="flex h-full items-center justify-center text-sm text-text-muted">
|
|
||||||
{isLoading ? t("common.loading") : t("reports.noDataForPeriod")}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<BarChart data={chartData} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
|
|
||||||
{yearTicks.length > 0 && (
|
|
||||||
<XAxis
|
|
||||||
dataKey="key"
|
|
||||||
type="category"
|
|
||||||
ticks={yearTicks}
|
|
||||||
tickFormatter={(value: string) => value.slice(0, 4)}
|
|
||||||
axisLine={false}
|
|
||||||
tickLine={false}
|
|
||||||
tick={{ fill: "var(--text-muted)", fontSize: 11 }}
|
|
||||||
interval="preserveStartEnd"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<Tooltip content={<ChartTooltip />} cursor={{ fill: "var(--surface-2)" }} />
|
|
||||||
<Bar dataKey="amount" fill={report.category_color} radius={[2, 2, 0, 0]} isAnimationActive={false} />
|
|
||||||
</BarChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{chartData.length > 1 && (
|
|
||||||
<div className="mt-2 flex justify-between text-xs text-text-muted">
|
|
||||||
<span>{formatMonthLabel(chartData[0].key)}</span>
|
|
||||||
<span>{formatMonthLabel(chartData[chartData.length - 1].key)}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
136
frontend/src/components/reports/SpendingTrendChart.tsx
Normal file
136
frontend/src/components/reports/SpendingTrendChart.tsx
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis } from "recharts";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { formatCurrency, getIntlLocale, pluralizeRu } from "@/lib/format";
|
||||||
|
import { useTranslation, type Language } from "@/lib/i18n";
|
||||||
|
import type { CategorySpendingPoint } from "@/types";
|
||||||
|
|
||||||
|
interface SpendingTrendChartProps {
|
||||||
|
/** Already resolved for display — a category name goes through
|
||||||
|
* translateCategoryName before it gets here, a tag name is shown as the
|
||||||
|
* user typed it. Undefined while the report is still loading. */
|
||||||
|
title: string | undefined;
|
||||||
|
color: string;
|
||||||
|
totalAmount: string | undefined;
|
||||||
|
averagePerMonth: string | undefined;
|
||||||
|
transactionCount: number | undefined;
|
||||||
|
series: CategorySpendingPoint[] | undefined;
|
||||||
|
isLoading: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function monthKey(year: number, month: number): string {
|
||||||
|
return `${year}-${String(month).padStart(2, "0")}-01`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMonthLabel(key: string): string {
|
||||||
|
return new Intl.DateTimeFormat(getIntlLocale(), { month: "short", year: "numeric" }).format(
|
||||||
|
new Date(`${key}T00:00:00`)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function transactionsCountLabel(count: number, language: Language): string {
|
||||||
|
if (language === "ru") return pluralizeRu(count, "транзакция", "транзакции", "транзакций");
|
||||||
|
return count === 1 ? "transaction" : "transactions";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same landmark idea as the Net Worth chart: year ticks only when the bars
|
||||||
|
* span more than one calendar year, so a 5-year report reads at a glance. */
|
||||||
|
function computeYearTicks(keys: string[]): string[] {
|
||||||
|
if (keys.length < 2) return [];
|
||||||
|
const startYear = Number(keys[0].slice(0, 4));
|
||||||
|
const endYear = Number(keys[keys.length - 1].slice(0, 4));
|
||||||
|
if (startYear === endYear) return [];
|
||||||
|
const ticks: string[] = [];
|
||||||
|
for (let year = startYear + 1; year <= endYear; year++) {
|
||||||
|
const jan = `${year}-01-01`;
|
||||||
|
if (keys.includes(jan)) ticks.push(jan);
|
||||||
|
}
|
||||||
|
return ticks;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartTooltip({ active, payload }: { active?: boolean; payload?: Array<{ payload: { key: string; amount: number } }> }) {
|
||||||
|
if (!active || !payload?.length) return null;
|
||||||
|
const point = payload[0].payload;
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm shadow-md">
|
||||||
|
<p className="text-text-muted">{formatMonthLabel(point.key)}</p>
|
||||||
|
<p className="font-medium text-text-primary">{formatCurrency(point.amount)}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One subject's month-by-month spending, as bars with a headline total —
|
||||||
|
* the presentational half of the Reports detail chart, taking a plain
|
||||||
|
* already-resolved shape rather than a report object so the category
|
||||||
|
* (CategorySpendingChart) and tag (TagSpendingChart) sides render
|
||||||
|
* identically instead of growing two drifting copies of this. */
|
||||||
|
export function SpendingTrendChart({
|
||||||
|
title,
|
||||||
|
color,
|
||||||
|
totalAmount,
|
||||||
|
averagePerMonth,
|
||||||
|
transactionCount,
|
||||||
|
series,
|
||||||
|
isLoading,
|
||||||
|
}: SpendingTrendChartProps) {
|
||||||
|
const { t, language } = useTranslation();
|
||||||
|
const chartData =
|
||||||
|
series?.map((point) => ({
|
||||||
|
key: monthKey(point.year, point.month),
|
||||||
|
amount: Number(point.amount),
|
||||||
|
})) ?? [];
|
||||||
|
const yearTicks = computeYearTicks(chartData.map((point) => point.key));
|
||||||
|
const hasReport = totalAmount !== undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="items-start">
|
||||||
|
<div>
|
||||||
|
<CardTitle>{title ?? t("reports.defaultChartTitle")}</CardTitle>
|
||||||
|
<p className="mt-1.5 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
||||||
|
{isLoading || !hasReport ? "…" : formatCurrency(totalAmount)}
|
||||||
|
</p>
|
||||||
|
{hasReport && averagePerMonth !== undefined && transactionCount !== undefined && (
|
||||||
|
<p className="mt-1 text-sm text-text-muted">
|
||||||
|
{t("reports.averagePerMonth", { amount: formatCurrency(averagePerMonth) })} ·{" "}
|
||||||
|
{transactionCount} {transactionsCountLabel(transactionCount, language)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="h-56 w-full sm:h-64">
|
||||||
|
{isLoading || !hasReport || chartData.length === 0 ? (
|
||||||
|
<div className="flex h-full items-center justify-center text-sm text-text-muted">
|
||||||
|
{isLoading ? t("common.loading") : t("reports.noDataForPeriod")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<BarChart data={chartData} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
|
||||||
|
{yearTicks.length > 0 && (
|
||||||
|
<XAxis
|
||||||
|
dataKey="key"
|
||||||
|
type="category"
|
||||||
|
ticks={yearTicks}
|
||||||
|
tickFormatter={(value: string) => value.slice(0, 4)}
|
||||||
|
axisLine={false}
|
||||||
|
tickLine={false}
|
||||||
|
tick={{ fill: "var(--text-muted)", fontSize: 11 }}
|
||||||
|
interval="preserveStartEnd"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Tooltip content={<ChartTooltip />} cursor={{ fill: "var(--surface-2)" }} />
|
||||||
|
<Bar dataKey="amount" fill={color} radius={[2, 2, 0, 0]} isAnimationActive={false} />
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{chartData.length > 1 && (
|
||||||
|
<div className="mt-2 flex justify-between text-xs text-text-muted">
|
||||||
|
<span>{formatMonthLabel(chartData[0].key)}</span>
|
||||||
|
<span>{formatMonthLabel(chartData[chartData.length - 1].key)}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
144
frontend/src/components/reports/TagRankingCard.tsx
Normal file
144
frontend/src/components/reports/TagRankingCard.tsx
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { SquareDivide, Tag as TagIcon } from "lucide-react";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||||
|
import { CategoryBreakdownModal } from "@/components/categories/CategoryBreakdownModal";
|
||||||
|
import { formatCurrency } from "@/lib/format";
|
||||||
|
import { useTranslation } from "@/lib/i18n";
|
||||||
|
import type { TagRankingItem } from "@/types";
|
||||||
|
|
||||||
|
interface TagRankingCardProps {
|
||||||
|
items: TagRankingItem[];
|
||||||
|
isLoading: boolean;
|
||||||
|
/** Everything spent in the period, tagged or not — the denominator behind
|
||||||
|
* each row's percent, shown so the percentages are interpretable. */
|
||||||
|
totalAmount: string | undefined;
|
||||||
|
taggedAmount: string | undefined;
|
||||||
|
selectedTagId: number | null;
|
||||||
|
onSelectTag: (tagId: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ranks every tag by total spent over the selected period — "which trip,
|
||||||
|
* which occasion, which person cost the most", the question the category
|
||||||
|
* ranking can't answer because one such answer is spread across several
|
||||||
|
* categories at once. Clicking a row drills into that tag in the chart and
|
||||||
|
* transaction list.
|
||||||
|
*
|
||||||
|
* Deliberately unlike the category ranking in one way: the percentages
|
||||||
|
* needn't sum to 100 and the rows may overlap, because one transaction can
|
||||||
|
* carry several tags and each tag owns it whole. The coverage line in the
|
||||||
|
* header is what keeps that honest — it says how much of the period carries
|
||||||
|
* any tag at all. */
|
||||||
|
export function TagRankingCard({
|
||||||
|
items,
|
||||||
|
isLoading,
|
||||||
|
totalAmount,
|
||||||
|
taggedAmount,
|
||||||
|
selectedTagId,
|
||||||
|
onSelectTag,
|
||||||
|
}: TagRankingCardProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [breakdownItem, setBreakdownItem] = useState<TagRankingItem | null>(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="items-start">
|
||||||
|
<div>
|
||||||
|
<CardTitle>{t("reports.tagRankingTitle")}</CardTitle>
|
||||||
|
{taggedAmount !== undefined && totalAmount !== undefined && (
|
||||||
|
<p className="mt-1 text-xs text-text-muted">
|
||||||
|
{t("reports.tagCoverage", {
|
||||||
|
tagged: formatCurrency(taggedAmount),
|
||||||
|
total: formatCurrency(totalAmount),
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{isLoading ? (
|
||||||
|
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<p className="py-10 text-center text-sm text-text-muted">{t("reports.noTagRankingData")}</p>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y divide-gridline">
|
||||||
|
{items.map((item, index) => {
|
||||||
|
const isSelected = item.tag_id === selectedTagId;
|
||||||
|
// Shown even for a single-category tag, unlike the category
|
||||||
|
// ranking's: a tag row names no category at all, so even a
|
||||||
|
// one-row breakdown says something the row itself doesn't.
|
||||||
|
const hasBreakdown = item.categories.length > 0;
|
||||||
|
return (
|
||||||
|
<li key={item.tag_id}>
|
||||||
|
<div
|
||||||
|
className={`flex items-center gap-1 rounded-lg transition-colors hover:bg-surface-2 ${
|
||||||
|
isSelected ? "bg-surface-2" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{/* Fixed-width slot on every row, populated or not — the
|
||||||
|
amount column at the row's end must stay flush right
|
||||||
|
the same way whether or not this row has a
|
||||||
|
breakdown to open. */}
|
||||||
|
<span className="ml-1 flex h-8 w-7 shrink-0 items-center justify-center">
|
||||||
|
{hasBreakdown && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t("common.expand")}
|
||||||
|
onClick={() => setBreakdownItem(item)}
|
||||||
|
className="rounded-md p-1.5 text-text-muted hover:text-text-primary"
|
||||||
|
>
|
||||||
|
<SquareDivide size={14} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSelectTag(item.tag_id)}
|
||||||
|
className="flex flex-1 items-center gap-3 py-2.5 text-left"
|
||||||
|
>
|
||||||
|
<span className="w-4 shrink-0 text-right text-xs tabular-nums text-text-muted">{index + 1}</span>
|
||||||
|
<span
|
||||||
|
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
|
||||||
|
style={{ backgroundColor: `${item.color}26` }}
|
||||||
|
>
|
||||||
|
<TagIcon size={15} style={{ color: item.color }} />
|
||||||
|
</span>
|
||||||
|
{/* A tag name is whatever the user typed — shown
|
||||||
|
verbatim, never run through the default-category
|
||||||
|
translations. */}
|
||||||
|
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">{item.name}</span>
|
||||||
|
<span className="hidden w-24 shrink-0 items-center gap-2 sm:flex">
|
||||||
|
<span className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||||
|
<span
|
||||||
|
className="block h-full rounded-full"
|
||||||
|
style={{ width: `${Math.min(item.percent, 100)}%`, backgroundColor: item.color }}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
<span className="w-9 shrink-0 text-right text-xs text-text-muted tabular-nums">
|
||||||
|
{item.percent.toFixed(0)}%
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span className="shrink-0 text-sm font-medium tabular-nums text-text-primary">
|
||||||
|
{formatCurrency(item.amount)}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
{breakdownItem && (
|
||||||
|
<CategoryBreakdownModal
|
||||||
|
open
|
||||||
|
onClose={() => setBreakdownItem(null)}
|
||||||
|
title={breakdownItem.name}
|
||||||
|
categoryName={breakdownItem.name}
|
||||||
|
totalAmount={breakdownItem.amount}
|
||||||
|
children={breakdownItem.categories}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
frontend/src/components/reports/TagSpendingChart.tsx
Normal file
31
frontend/src/components/reports/TagSpendingChart.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { SpendingTrendChart } from "@/components/reports/SpendingTrendChart";
|
||||||
|
import { NEUTRAL_TAG_COLOR } from "@/lib/tagColors";
|
||||||
|
import type { TagSpendingReport } from "@/types";
|
||||||
|
|
||||||
|
interface TagSpendingChartProps {
|
||||||
|
report: TagSpendingReport | undefined;
|
||||||
|
/** Borrowed from the tag's own ranking row (the color of the category it
|
||||||
|
* spends the most on) so the chart and the ranking bar agree — a tag has
|
||||||
|
* no color of its own. */
|
||||||
|
color: string | undefined;
|
||||||
|
isLoading: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One tag's spend month by month — "what has this trip / these gifts cost
|
||||||
|
* me over time", the question the category chart can't answer because one
|
||||||
|
* such answer cuts across several categories. A tag name is shown exactly
|
||||||
|
* as the user typed it, so unlike the category chart it never goes through
|
||||||
|
* the default-name translations. */
|
||||||
|
export function TagSpendingChart({ report, color, isLoading }: TagSpendingChartProps) {
|
||||||
|
return (
|
||||||
|
<SpendingTrendChart
|
||||||
|
title={report?.tag_name}
|
||||||
|
color={color ?? NEUTRAL_TAG_COLOR}
|
||||||
|
totalAmount={report?.total_amount}
|
||||||
|
averagePerMonth={report?.average_per_month}
|
||||||
|
transactionCount={report?.transaction_count}
|
||||||
|
series={report?.series}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { fetchCategoryRanking, fetchCategorySpendingReport } from "@/api/reports";
|
import {
|
||||||
|
fetchCategoryRanking,
|
||||||
|
fetchCategorySpendingReport,
|
||||||
|
fetchTagRanking,
|
||||||
|
fetchTagSpendingReport,
|
||||||
|
} from "@/api/reports";
|
||||||
import type { CategoryKind } from "@/types";
|
import type { CategoryKind } from "@/types";
|
||||||
|
|
||||||
export function useCategorySpendingReport(categoryId: number | null, startDate?: string, endDate?: string) {
|
export function useCategorySpendingReport(categoryId: number | null, startDate?: string, endDate?: string) {
|
||||||
@@ -16,3 +21,23 @@ export function useCategoryRanking(kind: CategoryKind, startDate?: string, endDa
|
|||||||
queryFn: () => fetchCategoryRanking(kind, startDate, endDate),
|
queryFn: () => fetchCategoryRanking(kind, startDate, endDate),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useTagRanking(kind: CategoryKind, startDate?: string, endDate?: string) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["tag-ranking", kind, startDate, endDate],
|
||||||
|
queryFn: () => fetchTagRanking(kind, startDate, endDate),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTagSpendingReport(
|
||||||
|
tagId: number | null,
|
||||||
|
kind: CategoryKind,
|
||||||
|
startDate?: string,
|
||||||
|
endDate?: string
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["tag-spending-report", tagId, kind, startDate, endDate],
|
||||||
|
queryFn: () => fetchTagSpendingReport(tagId as number, kind, startDate, endDate),
|
||||||
|
enabled: tagId !== null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ export function useDeleteTag() {
|
|||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["transactions"] });
|
queryClient.invalidateQueries({ queryKey: ["transactions"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tag-ranking"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tag-spending-report"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ function useInvalidateAfterTransactionChange() {
|
|||||||
queryClient.invalidateQueries({ queryKey: ["net-worth-summary"] });
|
queryClient.invalidateQueries({ queryKey: ["net-worth-summary"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["category-spending-report"] });
|
queryClient.invalidateQueries({ queryKey: ["category-spending-report"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["category-ranking"] });
|
queryClient.invalidateQueries({ queryKey: ["category-ranking"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tag-spending-report"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tag-ranking"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["budget-status"] });
|
queryClient.invalidateQueries({ queryKey: ["budget-status"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["financial-alerts"] });
|
queryClient.invalidateQueries({ queryKey: ["financial-alerts"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["advice"] });
|
queryClient.invalidateQueries({ queryKey: ["advice"] });
|
||||||
|
|||||||
@@ -347,6 +347,14 @@ const ru = {
|
|||||||
"reports.noDataForPeriod": "Нет данных за выбранный период.",
|
"reports.noDataForPeriod": "Нет данных за выбранный период.",
|
||||||
"reports.categoryRankingTitle": "Топ категорий за период",
|
"reports.categoryRankingTitle": "Топ категорий за период",
|
||||||
"reports.noRankingData": "Нет расходов за выбранный период.",
|
"reports.noRankingData": "Нет расходов за выбранный период.",
|
||||||
|
"reports.modeCategory": "По категориям",
|
||||||
|
"reports.modeTag": "По тегам",
|
||||||
|
"reports.tagLabel": "Тег",
|
||||||
|
"reports.noTagsYet": "Тегов пока нет",
|
||||||
|
"reports.tagRankingTitle": "Топ тегов за период",
|
||||||
|
"reports.noTagRankingData": "За выбранный период нет расходов с тегами.",
|
||||||
|
"reports.tagCoverage": "С тегами: {{tagged}} из {{total}}",
|
||||||
|
"reports.noCategoryLabel": "Без категории",
|
||||||
|
|
||||||
"settings.language": "Язык",
|
"settings.language": "Язык",
|
||||||
"settings.languageRussian": "Русский",
|
"settings.languageRussian": "Русский",
|
||||||
@@ -872,6 +880,14 @@ const en: Record<keyof typeof ru, string> = {
|
|||||||
"reports.noDataForPeriod": "No data for the selected period.",
|
"reports.noDataForPeriod": "No data for the selected period.",
|
||||||
"reports.categoryRankingTitle": "Top categories for period",
|
"reports.categoryRankingTitle": "Top categories for period",
|
||||||
"reports.noRankingData": "No expenses for the selected period.",
|
"reports.noRankingData": "No expenses for the selected period.",
|
||||||
|
"reports.modeCategory": "By category",
|
||||||
|
"reports.modeTag": "By tag",
|
||||||
|
"reports.tagLabel": "Tag",
|
||||||
|
"reports.noTagsYet": "No tags yet",
|
||||||
|
"reports.tagRankingTitle": "Top tags for period",
|
||||||
|
"reports.noTagRankingData": "No tagged expenses for the selected period.",
|
||||||
|
"reports.tagCoverage": "Tagged: {{tagged}} of {{total}}",
|
||||||
|
"reports.noCategoryLabel": "No category",
|
||||||
|
|
||||||
"settings.language": "Language",
|
"settings.language": "Language",
|
||||||
"settings.languageRussian": "Русский",
|
"settings.languageRussian": "Русский",
|
||||||
|
|||||||
6
frontend/src/lib/tagColors.ts
Normal file
6
frontend/src/lib/tagColors.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
/** A tag carries no color of its own (backend/app/models/tag.py) — the tag
|
||||||
|
* ranking borrows the color of the category the tag spent the most on, and
|
||||||
|
* falls back to this neutral when there's nothing to borrow from. Kept in
|
||||||
|
* step with tag_rollup.py's NEUTRAL_COLOR, which is the same grey the
|
||||||
|
* category rollup already uses for a category it can't resolve. */
|
||||||
|
export const NEUTRAL_TAG_COLOR = "#898781";
|
||||||
@@ -6,10 +6,13 @@ import { PillSelector } from "@/components/layout/PillSelector";
|
|||||||
import { YearRangeSelector } from "@/components/layout/YearSelector";
|
import { YearRangeSelector } from "@/components/layout/YearSelector";
|
||||||
import { CategoryRankingCard } from "@/components/reports/CategoryRankingCard";
|
import { CategoryRankingCard } from "@/components/reports/CategoryRankingCard";
|
||||||
import { CategorySpendingChart } from "@/components/reports/CategorySpendingChart";
|
import { CategorySpendingChart } from "@/components/reports/CategorySpendingChart";
|
||||||
|
import { TagRankingCard } from "@/components/reports/TagRankingCard";
|
||||||
|
import { TagSpendingChart } from "@/components/reports/TagSpendingChart";
|
||||||
import { TransactionsTable } from "@/components/transactions/TransactionsTable";
|
import { TransactionsTable } from "@/components/transactions/TransactionsTable";
|
||||||
import { TransactionFormModal } from "@/components/transactions/TransactionFormModal";
|
import { TransactionFormModal } from "@/components/transactions/TransactionFormModal";
|
||||||
import { useCategories } from "@/hooks/useCategories";
|
import { useCategories } from "@/hooks/useCategories";
|
||||||
import { useCategoryRanking, useCategorySpendingReport } from "@/hooks/useReports";
|
import { useCategoryRanking, useCategorySpendingReport, useTagRanking, useTagSpendingReport } from "@/hooks/useReports";
|
||||||
|
import { useTags } from "@/hooks/useTags";
|
||||||
import { useDeleteTransaction, useTransactions, useTransactionYears } from "@/hooks/useTransactions";
|
import { useDeleteTransaction, useTransactions, useTransactionYears } from "@/hooks/useTransactions";
|
||||||
import type { TransactionSort } from "@/api/transactions";
|
import type { TransactionSort } from "@/api/transactions";
|
||||||
import { computeRange, type CustomYearRange, type RangePreset } from "@/lib/dateRange";
|
import { computeRange, type CustomYearRange, type RangePreset } from "@/lib/dateRange";
|
||||||
@@ -19,6 +22,13 @@ import type { Transaction } from "@/types";
|
|||||||
|
|
||||||
const PAGE_SIZE = 20;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
|
/** Which axis the page is reporting along: down the categories ("what kind
|
||||||
|
* of spend was this") or across the tags ("which event/project was it for").
|
||||||
|
* The two answer genuinely different questions over the same transactions —
|
||||||
|
* see backend/app/models/tag.py — so they're modes of one page rather than
|
||||||
|
* two pages. */
|
||||||
|
type ReportMode = "category" | "tag";
|
||||||
|
|
||||||
export function ReportsPage() {
|
export function ReportsPage() {
|
||||||
const { t, language } = useTranslation();
|
const { t, language } = useTranslation();
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -28,9 +38,16 @@ export function ReportsPage() {
|
|||||||
{ value: "5y", label: t("reports.range5y") },
|
{ value: "5y", label: t("reports.range5y") },
|
||||||
{ value: "custom", label: t("reports.rangeCustom") },
|
{ value: "custom", label: t("reports.rangeCustom") },
|
||||||
];
|
];
|
||||||
|
const MODE_OPTIONS: Array<{ value: ReportMode; label: string }> = [
|
||||||
|
{ value: "category", label: t("reports.modeCategory") },
|
||||||
|
{ value: "tag", label: t("reports.modeTag") },
|
||||||
|
];
|
||||||
const { data: categories } = useCategories();
|
const { data: categories } = useCategories();
|
||||||
|
const { data: tags } = useTags();
|
||||||
const { data: years } = useTransactionYears();
|
const { data: years } = useTransactionYears();
|
||||||
|
const [mode, setMode] = useState<ReportMode>("category");
|
||||||
const [categoryId, setCategoryId] = useState<number | null>(null);
|
const [categoryId, setCategoryId] = useState<number | null>(null);
|
||||||
|
const [tagId, setTagId] = useState<number | null>(null);
|
||||||
const [range, setRange] = useState<RangePreset>("all");
|
const [range, setRange] = useState<RangePreset>("all");
|
||||||
const [customRange, setCustomRange] = useState<CustomYearRange>({
|
const [customRange, setCustomRange] = useState<CustomYearRange>({
|
||||||
fromYear: now.getFullYear(),
|
fromYear: now.getFullYear(),
|
||||||
@@ -48,11 +65,26 @@ export function ReportsPage() {
|
|||||||
}
|
}
|
||||||
}, [categories, categoryId]);
|
}, [categories, categoryId]);
|
||||||
|
|
||||||
|
// A tag deleted elsewhere (Transactions page) would otherwise leave the
|
||||||
|
// detail chart asking the API for an id that no longer resolves.
|
||||||
|
useEffect(() => {
|
||||||
|
if (tagId !== null && tags && !tags.some((tag) => tag.id === tagId)) setTagId(null);
|
||||||
|
}, [tags, tagId]);
|
||||||
|
|
||||||
const { startDate, endDate } = computeRange(range, customRange);
|
const { startDate, endDate } = computeRange(range, customRange);
|
||||||
|
const isTagMode = mode === "tag";
|
||||||
const { data: ranking, isLoading: isRankingLoading } = useCategoryRanking("expense", startDate, endDate);
|
const { data: ranking, isLoading: isRankingLoading } = useCategoryRanking("expense", startDate, endDate);
|
||||||
|
const { data: tagRanking, isLoading: isTagRankingLoading } = useTagRanking("expense", startDate, endDate);
|
||||||
const { data: report, isLoading: isReportLoading } = useCategorySpendingReport(categoryId, startDate, endDate);
|
const { data: report, isLoading: isReportLoading } = useCategorySpendingReport(categoryId, startDate, endDate);
|
||||||
|
const { data: tagReport, isLoading: isTagReportLoading } = useTagSpendingReport(
|
||||||
|
isTagMode ? tagId : null,
|
||||||
|
"expense",
|
||||||
|
startDate,
|
||||||
|
endDate
|
||||||
|
);
|
||||||
const { data: transactions, isLoading: isTransactionsLoading } = useTransactions({
|
const { data: transactions, isLoading: isTransactionsLoading } = useTransactions({
|
||||||
category_id: categoryId ?? undefined,
|
category_id: isTagMode ? undefined : categoryId ?? undefined,
|
||||||
|
tag_id: isTagMode ? tagId ?? undefined : undefined,
|
||||||
start_date: startDate,
|
start_date: startDate,
|
||||||
end_date: endDate,
|
end_date: endDate,
|
||||||
sort,
|
sort,
|
||||||
@@ -61,6 +93,15 @@ export function ReportsPage() {
|
|||||||
});
|
});
|
||||||
const deleteTransaction = useDeleteTransaction();
|
const deleteTransaction = useDeleteTransaction();
|
||||||
|
|
||||||
|
// The ranking is ordered by amount, so its first row is the tag worth
|
||||||
|
// looking at first — a better landing selection than whichever tag
|
||||||
|
// happens to sort first alphabetically in the picker.
|
||||||
|
useEffect(() => {
|
||||||
|
if (isTagMode && tagId === null && tagRanking && tagRanking.items.length > 0) {
|
||||||
|
setTagId(tagRanking.items[0].tag_id);
|
||||||
|
}
|
||||||
|
}, [isTagMode, tagId, tagRanking]);
|
||||||
|
|
||||||
// Hierarchical within each group (a subcategory right under its own
|
// Hierarchical within each group (a subcategory right under its own
|
||||||
// parent, indented) — a bare "Sweets" option next to top-level categories
|
// parent, indented) — a bare "Sweets" option next to top-level categories
|
||||||
// reads as if it were one itself.
|
// reads as if it were one itself.
|
||||||
@@ -73,6 +114,12 @@ export function ReportsPage() {
|
|||||||
language
|
language
|
||||||
);
|
);
|
||||||
const totalPages = transactions ? Math.max(1, Math.ceil(transactions.total / PAGE_SIZE)) : 1;
|
const totalPages = transactions ? Math.max(1, Math.ceil(transactions.total / PAGE_SIZE)) : 1;
|
||||||
|
const selectedTagColor = tagRanking?.items.find((item) => item.tag_id === tagId)?.color;
|
||||||
|
|
||||||
|
function handleModeChange(value: ReportMode) {
|
||||||
|
setMode(value);
|
||||||
|
setPage(1);
|
||||||
|
}
|
||||||
|
|
||||||
function handleEdit(transaction: Transaction) {
|
function handleEdit(transaction: Transaction) {
|
||||||
setEditingTransaction(transaction);
|
setEditingTransaction(transaction);
|
||||||
@@ -89,38 +136,63 @@ export function ReportsPage() {
|
|||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<div className="max-w-xs flex-1">
|
<div className="max-w-xs flex-1">
|
||||||
<Label htmlFor="report-category">{t("reports.categoryLabel")}</Label>
|
{isTagMode ? (
|
||||||
<Select
|
<>
|
||||||
id="report-category"
|
<Label htmlFor="report-tag">{t("reports.tagLabel")}</Label>
|
||||||
value={categoryId ?? ""}
|
<Select
|
||||||
onChange={(event) => {
|
id="report-tag"
|
||||||
setCategoryId(Number(event.target.value));
|
value={tagId ?? ""}
|
||||||
setPage(1);
|
disabled={!tags || tags.length === 0}
|
||||||
}}
|
onChange={(event) => {
|
||||||
>
|
setTagId(event.target.value ? Number(event.target.value) : null);
|
||||||
{expenseCategories.length > 0 && (
|
setPage(1);
|
||||||
<optgroup label={t("reports.expenseGroup")}>
|
}}
|
||||||
{expenseCategories.map((category) => (
|
>
|
||||||
<option key={category.id} value={category.id}>
|
{(!tags || tags.length === 0) && <option value="">{t("reports.noTagsYet")}</option>}
|
||||||
{category.indented ? ` ↳ ` : ""}
|
{tags?.map((tag) => (
|
||||||
{translateCategoryName(category.name)}
|
<option key={tag.id} value={tag.id}>
|
||||||
|
{tag.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</optgroup>
|
</Select>
|
||||||
)}
|
</>
|
||||||
{incomeCategories.length > 0 && (
|
) : (
|
||||||
<optgroup label={t("reports.incomeGroup")}>
|
<>
|
||||||
{incomeCategories.map((category) => (
|
<Label htmlFor="report-category">{t("reports.categoryLabel")}</Label>
|
||||||
<option key={category.id} value={category.id}>
|
<Select
|
||||||
{category.indented ? ` ↳ ` : ""}
|
id="report-category"
|
||||||
{translateCategoryName(category.name)}
|
value={categoryId ?? ""}
|
||||||
</option>
|
onChange={(event) => {
|
||||||
))}
|
setCategoryId(Number(event.target.value));
|
||||||
</optgroup>
|
setPage(1);
|
||||||
)}
|
}}
|
||||||
</Select>
|
>
|
||||||
|
{expenseCategories.length > 0 && (
|
||||||
|
<optgroup label={t("reports.expenseGroup")}>
|
||||||
|
{expenseCategories.map((category) => (
|
||||||
|
<option key={category.id} value={category.id}>
|
||||||
|
{category.indented ? ` ↳ ` : ""}
|
||||||
|
{translateCategoryName(category.name)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</optgroup>
|
||||||
|
)}
|
||||||
|
{incomeCategories.length > 0 && (
|
||||||
|
<optgroup label={t("reports.incomeGroup")}>
|
||||||
|
{incomeCategories.map((category) => (
|
||||||
|
<option key={category.id} value={category.id}>
|
||||||
|
{category.indented ? ` ↳ ` : ""}
|
||||||
|
{translateCategoryName(category.name)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</optgroup>
|
||||||
|
)}
|
||||||
|
</Select>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||||
|
<PillSelector options={MODE_OPTIONS} value={mode} onChange={handleModeChange} />
|
||||||
<PillSelector
|
<PillSelector
|
||||||
options={RANGE_OPTIONS}
|
options={RANGE_OPTIONS}
|
||||||
value={range}
|
value={range}
|
||||||
@@ -143,17 +215,35 @@ export function ReportsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CategorySpendingChart report={report} isLoading={isReportLoading} />
|
{isTagMode ? (
|
||||||
|
<>
|
||||||
<CategoryRankingCard
|
<TagSpendingChart report={tagReport} color={selectedTagColor} isLoading={isTagReportLoading} />
|
||||||
items={ranking?.items ?? []}
|
<TagRankingCard
|
||||||
isLoading={isRankingLoading}
|
items={tagRanking?.items ?? []}
|
||||||
selectedCategoryId={categoryId}
|
isLoading={isTagRankingLoading}
|
||||||
onSelectCategory={(id) => {
|
totalAmount={tagRanking?.total_amount}
|
||||||
setCategoryId(id);
|
taggedAmount={tagRanking?.tagged_amount}
|
||||||
setPage(1);
|
selectedTagId={tagId}
|
||||||
}}
|
onSelectTag={(id) => {
|
||||||
/>
|
setTagId(id);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<CategorySpendingChart report={report} isLoading={isReportLoading} />
|
||||||
|
<CategoryRankingCard
|
||||||
|
items={ranking?.items ?? []}
|
||||||
|
isLoading={isRankingLoading}
|
||||||
|
selectedCategoryId={categoryId}
|
||||||
|
onSelectCategory={(id) => {
|
||||||
|
setCategoryId(id);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
@@ -349,6 +349,54 @@ export interface CategoryRankingReport {
|
|||||||
items: CategoryRankingItem[];
|
items: CategoryRankingItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One top-level category's share of a tag's total. category_id is null (and
|
||||||
|
// name empty) for the share that had no category at all — the frontend
|
||||||
|
// labels that row from its own translations.
|
||||||
|
export interface TagRankingCategoryItem {
|
||||||
|
category_id: number | null;
|
||||||
|
name: string;
|
||||||
|
color: string;
|
||||||
|
icon: string | null;
|
||||||
|
amount: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TagRankingItem {
|
||||||
|
tag_id: number;
|
||||||
|
name: string;
|
||||||
|
// Borrowed from the category this tag spent the most on — a tag has no
|
||||||
|
// color of its own (backend/app/models/tag.py).
|
||||||
|
color: string;
|
||||||
|
amount: string;
|
||||||
|
// Share of the period's total spending of this kind, not of its tagged
|
||||||
|
// part: tags overlap, so these deliberately don't add up to 100.
|
||||||
|
percent: number;
|
||||||
|
transaction_count: number;
|
||||||
|
categories: TagRankingCategoryItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TagRankingReport {
|
||||||
|
start_date: string | null;
|
||||||
|
end_date: string | null;
|
||||||
|
total_amount: string;
|
||||||
|
// The part of total_amount carrying at least one tag, counted once per
|
||||||
|
// transaction however many tags it has.
|
||||||
|
tagged_amount: string;
|
||||||
|
items: TagRankingItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tag-side twin of CategorySpendingReport, reusing its point type since
|
||||||
|
// a point is just (year, month, amount) either way.
|
||||||
|
export interface TagSpendingReport {
|
||||||
|
tag_id: number;
|
||||||
|
tag_name: string;
|
||||||
|
start_date: string | null;
|
||||||
|
end_date: string | null;
|
||||||
|
total_amount: string;
|
||||||
|
transaction_count: number;
|
||||||
|
average_per_month: string;
|
||||||
|
series: CategorySpendingPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface Goal {
|
export interface Goal {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user