import { useEffect, useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card"; import { Button } from "@/components/ui/Button"; import { Label, Select } from "@/components/ui/Input"; 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, 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"; import { useTranslation } from "@/lib/i18n"; import { buildHierarchicalCategories, translateCategoryName } from "@/lib/categoryLabels"; 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"; /** Which side of the ledger the tag report shows. A category carries its own * kind, so in category mode filtering the transaction list by `category_id` * already pins the type implicitly; a tag carries none and can legitimately * sit on both sides of the ledger, so every part of the tag report — chart, * ranking *and* transaction list — has to be pinned to the same side * explicitly. One constant rather than four literals so they can't drift * apart and leave the list showing income the totals above it don't count. */ const TAG_REPORT_KIND = "expense" as const; export function ReportsPage() { const { t, language } = useTranslation(); const now = new Date(); const RANGE_OPTIONS: Array<{ value: RangePreset; label: string }> = [ { value: "all", label: t("reports.rangeAll") }, { value: "this_year", label: t("reports.rangeThisYear") }, { 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("category"); const [categoryId, setCategoryId] = useState(null); const [tagId, setTagId] = useState(null); const [range, setRange] = useState("all"); const [customRange, setCustomRange] = useState({ fromYear: now.getFullYear(), toYear: now.getFullYear(), }); const [sort, setSort] = useState("date_desc"); const [page, setPage] = useState(1); const [editingTransaction, setEditingTransaction] = useState(null); const [modalOpen, setModalOpen] = useState(false); useEffect(() => { if (categoryId === null && categories && categories.length > 0) { const firstExpense = categories.find((category) => category.kind === "expense"); setCategoryId((firstExpense ?? categories[0]).id); } }, [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(TAG_REPORT_KIND, startDate, endDate); const { data: report, isLoading: isReportLoading } = useCategorySpendingReport(categoryId, startDate, endDate); const { data: tagReport, isLoading: isTagReportLoading } = useTagSpendingReport( isTagMode ? tagId : null, TAG_REPORT_KIND, startDate, endDate ); const { data: transactions, isLoading: isTransactionsLoading } = useTransactions({ category_id: isTagMode ? undefined : categoryId ?? undefined, tag_id: isTagMode ? tagId ?? undefined : undefined, // Category mode needs no type filter: the chosen category's own kind // already restricts which transactions can carry it. type: isTagMode ? TAG_REPORT_KIND : undefined, start_date: startDate, end_date: endDate, sort, page, page_size: PAGE_SIZE, }); 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. const expenseCategories = buildHierarchicalCategories( categories?.filter((category) => category.kind === "expense") ?? [], language ); const incomeCategories = buildHierarchicalCategories( categories?.filter((category) => category.kind === "income") ?? [], 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); setModalOpen(true); } function handleDelete(transaction: Transaction) { if (window.confirm(t("transactions.confirmDelete", { description: transaction.description }))) { deleteTransaction.mutate(transaction.id); } } return (
{isTagMode ? ( <> ) : ( <> )}
{ setRange(value); setPage(1); }} /> {range === "custom" && ( { setCustomRange(value); setPage(1); }} /> )}
{isTagMode ? ( <> { setTagId(id); setPage(1); }} /> ) : ( <> { setCategoryId(id); setPage(1); }} /> )} {t("reports.transactionsTitle")} {transactions && ( {t("common.totalCount", { count: transactions.total })} )} {isTransactionsLoading ? (

{t("common.loading")}

) : ( )} {totalPages > 1 && (
{t("common.pageOf", { page, total: totalPages })}
)}
setModalOpen(false)} transaction={editingTransaction} />
); }