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:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aurum-frontend",
|
||||
"private": true,
|
||||
"version": "1.1.8",
|
||||
"version": "1.1.9",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
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) {
|
||||
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);
|
||||
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";
|
||||
|
||||
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;
|
||||
color: string;
|
||||
icon: string | null;
|
||||
@@ -15,23 +17,32 @@ interface CategoryBreakdownChild {
|
||||
interface CategoryBreakdownModalProps {
|
||||
open: boolean;
|
||||
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;
|
||||
totalAmount: string;
|
||||
children: CategoryBreakdownChild[];
|
||||
}
|
||||
|
||||
/** Shows how a parent category's total splits across its subcategories — a
|
||||
* modal rather than an inline expansion, since a category with many
|
||||
* subcategories (or many split-across purchases) would otherwise push the
|
||||
* Dashboard's donut/list layout out of alignment as rows grow taller. Shared
|
||||
* between the Dashboard breakdown and the Reports category ranking, which
|
||||
* expose the same shape (see services/category_rollup.py's
|
||||
* CategoryRollupChildItem). */
|
||||
/** Shows how a total splits across the categories that fed it — a modal
|
||||
* rather than an inline expansion, since a subject with many parts (or many
|
||||
* split-across purchases) would otherwise push the Dashboard's donut/list
|
||||
* layout out of alignment as rows grow taller. Shared by the Dashboard
|
||||
* breakdown and the Reports category ranking, which expose the same shape
|
||||
* (see services/category_rollup.py's CategoryRollupChildItem), and by the
|
||||
* Reports tag ranking, whose rows are that tag's categories instead
|
||||
* (services/tag_rollup.py's TagRollupCategoryItem). */
|
||||
export function CategoryBreakdownModal({
|
||||
open,
|
||||
onClose,
|
||||
categoryId,
|
||||
title,
|
||||
categoryName,
|
||||
totalAmount,
|
||||
children,
|
||||
@@ -40,7 +51,7 @@ export function CategoryBreakdownModal({
|
||||
const total = Number(totalAmount);
|
||||
|
||||
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">
|
||||
<span className="text-text-muted">{t("reports.categoryBreakdownTotalLabel")}</span>
|
||||
<span className="font-semibold tabular-nums text-text-primary">{formatCurrency(totalAmount)}</span>
|
||||
@@ -49,9 +60,14 @@ export function CategoryBreakdownModal({
|
||||
{children.map((child) => {
|
||||
const Icon = getCategoryIcon(child.icon);
|
||||
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 (
|
||||
<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
|
||||
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"
|
||||
style={{ backgroundColor: `${child.color}26` }}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
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 { SpendingTrendChart } from "@/components/reports/SpendingTrendChart";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { CategorySpendingReport } from "@/types";
|
||||
|
||||
@@ -10,105 +7,20 @@ interface CategorySpendingChartProps {
|
||||
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 category's spend month by month. The drawing itself lives in
|
||||
* SpendingTrendChart, shared with the tag side — this only maps the report
|
||||
* onto it and resolves the category's name through the default-category
|
||||
* translations. */
|
||||
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 (
|
||||
<Card>
|
||||
<CardHeader className="items-start">
|
||||
<div>
|
||||
<CardTitle>{report ? translateCategoryName(report.category_name) : t("reports.defaultChartTitle")}</CardTitle>
|
||||
<p className="mt-1.5 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
||||
{isLoading || !report ? "…" : formatCurrency(report.total_amount)}
|
||||
</p>
|
||||
{report && (
|
||||
<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>
|
||||
<SpendingTrendChart
|
||||
title={report ? translateCategoryName(report.category_name) : undefined}
|
||||
color={report?.category_color ?? "#898781"}
|
||||
totalAmount={report?.total_amount}
|
||||
averagePerMonth={report?.average_per_month}
|
||||
transactionCount={report?.transaction_count}
|
||||
series={report?.series}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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 { fetchCategoryRanking, fetchCategorySpendingReport } from "@/api/reports";
|
||||
import {
|
||||
fetchCategoryRanking,
|
||||
fetchCategorySpendingReport,
|
||||
fetchTagRanking,
|
||||
fetchTagSpendingReport,
|
||||
} from "@/api/reports";
|
||||
import type { CategoryKind } from "@/types";
|
||||
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
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: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["tags"] });
|
||||
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: ["category-spending-report"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["category-ranking"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["tag-spending-report"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["tag-ranking"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["budget-status"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["financial-alerts"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["advice"] });
|
||||
|
||||
@@ -347,6 +347,14 @@ const ru = {
|
||||
"reports.noDataForPeriod": "Нет данных за выбранный период.",
|
||||
"reports.categoryRankingTitle": "Топ категорий за период",
|
||||
"reports.noRankingData": "Нет расходов за выбранный период.",
|
||||
"reports.modeCategory": "По категориям",
|
||||
"reports.modeTag": "По тегам",
|
||||
"reports.tagLabel": "Тег",
|
||||
"reports.noTagsYet": "Тегов пока нет",
|
||||
"reports.tagRankingTitle": "Топ тегов за период",
|
||||
"reports.noTagRankingData": "За выбранный период нет расходов с тегами.",
|
||||
"reports.tagCoverage": "С тегами: {{tagged}} из {{total}}",
|
||||
"reports.noCategoryLabel": "Без категории",
|
||||
|
||||
"settings.language": "Язык",
|
||||
"settings.languageRussian": "Русский",
|
||||
@@ -872,6 +880,14 @@ const en: Record<keyof typeof ru, string> = {
|
||||
"reports.noDataForPeriod": "No data for the selected period.",
|
||||
"reports.categoryRankingTitle": "Top categories for 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.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 { CategoryRankingCard } from "@/components/reports/CategoryRankingCard";
|
||||
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 { TransactionFormModal } from "@/components/transactions/TransactionFormModal";
|
||||
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 type { TransactionSort } from "@/api/transactions";
|
||||
import { computeRange, type CustomYearRange, type RangePreset } from "@/lib/dateRange";
|
||||
@@ -19,6 +22,13 @@ import type { Transaction } from "@/types";
|
||||
|
||||
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() {
|
||||
const { t, language } = useTranslation();
|
||||
const now = new Date();
|
||||
@@ -28,9 +38,16 @@ export function ReportsPage() {
|
||||
{ value: "5y", label: t("reports.range5y") },
|
||||
{ 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: tags } = useTags();
|
||||
const { data: years } = useTransactionYears();
|
||||
const [mode, setMode] = useState<ReportMode>("category");
|
||||
const [categoryId, setCategoryId] = useState<number | null>(null);
|
||||
const [tagId, setTagId] = useState<number | null>(null);
|
||||
const [range, setRange] = useState<RangePreset>("all");
|
||||
const [customRange, setCustomRange] = useState<CustomYearRange>({
|
||||
fromYear: now.getFullYear(),
|
||||
@@ -48,11 +65,26 @@ export function ReportsPage() {
|
||||
}
|
||||
}, [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 isTagMode = mode === "tag";
|
||||
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: tagReport, isLoading: isTagReportLoading } = useTagSpendingReport(
|
||||
isTagMode ? tagId : null,
|
||||
"expense",
|
||||
startDate,
|
||||
endDate
|
||||
);
|
||||
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,
|
||||
end_date: endDate,
|
||||
sort,
|
||||
@@ -61,6 +93,15 @@ export function ReportsPage() {
|
||||
});
|
||||
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
|
||||
// parent, indented) — a bare "Sweets" option next to top-level categories
|
||||
// reads as if it were one itself.
|
||||
@@ -73,6 +114,12 @@ export function ReportsPage() {
|
||||
language
|
||||
);
|
||||
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) {
|
||||
setEditingTransaction(transaction);
|
||||
@@ -89,38 +136,63 @@ export function ReportsPage() {
|
||||
<div className="space-y-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div className="max-w-xs flex-1">
|
||||
<Label htmlFor="report-category">{t("reports.categoryLabel")}</Label>
|
||||
<Select
|
||||
id="report-category"
|
||||
value={categoryId ?? ""}
|
||||
onChange={(event) => {
|
||||
setCategoryId(Number(event.target.value));
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
{expenseCategories.length > 0 && (
|
||||
<optgroup label={t("reports.expenseGroup")}>
|
||||
{expenseCategories.map((category) => (
|
||||
<option key={category.id} value={category.id}>
|
||||
{category.indented ? ` ↳ ` : ""}
|
||||
{translateCategoryName(category.name)}
|
||||
{isTagMode ? (
|
||||
<>
|
||||
<Label htmlFor="report-tag">{t("reports.tagLabel")}</Label>
|
||||
<Select
|
||||
id="report-tag"
|
||||
value={tagId ?? ""}
|
||||
disabled={!tags || tags.length === 0}
|
||||
onChange={(event) => {
|
||||
setTagId(event.target.value ? Number(event.target.value) : null);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
{(!tags || tags.length === 0) && <option value="">{t("reports.noTagsYet")}</option>}
|
||||
{tags?.map((tag) => (
|
||||
<option key={tag.id} value={tag.id}>
|
||||
{tag.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>
|
||||
</Select>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Label htmlFor="report-category">{t("reports.categoryLabel")}</Label>
|
||||
<Select
|
||||
id="report-category"
|
||||
value={categoryId ?? ""}
|
||||
onChange={(event) => {
|
||||
setCategoryId(Number(event.target.value));
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
{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 className="flex flex-wrap items-center justify-end gap-2">
|
||||
<PillSelector options={MODE_OPTIONS} value={mode} onChange={handleModeChange} />
|
||||
<PillSelector
|
||||
options={RANGE_OPTIONS}
|
||||
value={range}
|
||||
@@ -143,17 +215,35 @@ export function ReportsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CategorySpendingChart report={report} isLoading={isReportLoading} />
|
||||
|
||||
<CategoryRankingCard
|
||||
items={ranking?.items ?? []}
|
||||
isLoading={isRankingLoading}
|
||||
selectedCategoryId={categoryId}
|
||||
onSelectCategory={(id) => {
|
||||
setCategoryId(id);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
{isTagMode ? (
|
||||
<>
|
||||
<TagSpendingChart report={tagReport} color={selectedTagColor} isLoading={isTagReportLoading} />
|
||||
<TagRankingCard
|
||||
items={tagRanking?.items ?? []}
|
||||
isLoading={isTagRankingLoading}
|
||||
totalAmount={tagRanking?.total_amount}
|
||||
taggedAmount={tagRanking?.tagged_amount}
|
||||
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>
|
||||
<CardHeader>
|
||||
|
||||
@@ -349,6 +349,54 @@ export interface CategoryRankingReport {
|
||||
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 {
|
||||
id: number;
|
||||
name: string;
|
||||
|
||||
Reference in New Issue
Block a user