feat: отчёт по тегам в Отчётах, версия 1.1.9

This commit is contained in:
justl
2026-09-18 16:57:11 +03:00
parent 848ff21665
commit 075906ffc6
23 changed files with 1325 additions and 194 deletions

View File

@@ -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` }}

View File

@@ -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}
/>
);
}

View 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>
);
}

View 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>
);
}

View 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}
/>
);
}