fix: restrict transaction splits to one parent category, show subcategory breakdown

Раньше сплит позволял смешивать вообще любые категории. Реальная задача —
разложить одну покупку по подкатегориям ОДНОЙ базовой категории (100 € на
продукты: сколько на сладости, сколько на уход). А раз Dashboard и рейтинг
категорий сворачивают подкатегории в родителя, эта разбивка нигде не была
видна.

- _build_splits() требует, чтобы все категории сплита были одной родительской
  категорией или её прямыми подкатегориями.
- category_rollup.py отдаёт для каждого родительского тотала список
  category-источников, которые в него скинулись (children) — пусто, если
  источник один.
- Dashboard и рейтинг категорий: строка с непустым children раскрывается по
  клику, показывая вклад каждой подкатегории.
- Форма транзакции: выбор категории при сплите — сначала базовая (верхний
  уровень), затем строки сплита выбирают саму базовую или её подкатегорию.
This commit is contained in:
ZProger
2026-08-30 19:06:29 +03:00
parent f778742134
commit 140f58d33f
16 changed files with 580 additions and 130 deletions

View File

@@ -1,10 +1,12 @@
import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { getCategoryIcon } from "@/lib/icons";
import { formatCurrency } from "@/lib/format";
import { useTranslation } from "@/lib/i18n";
import { useTranslation, type TranslationKey } from "@/lib/i18n";
import { translateCategoryName } from "@/lib/categoryLabels";
import type { CategoryBreakdownItem } from "@/types";
import type { CategoryBreakdownChildItem, CategoryBreakdownItem } from "@/types";
interface SpendingByCategoryCardProps {
items: CategoryBreakdownItem[];
@@ -23,13 +25,31 @@ function DonutTooltip({ active, payload }: { active?: boolean; payload?: Array<{
);
}
// A child's category_id equals its parent's own — the enclosing
// CategoryBreakdownItem's — when that slice of spend was filed directly on
// the parent with no more specific subcategory chosen (see
// services/category_rollup.py's CategoryRollupChildItem).
function childLabel(child: CategoryBreakdownChildItem, parentId: number | null, t: (key: TranslationKey) => string) {
return child.category_id === parentId ? t("reports.directSpendLabel") : translateCategoryName(child.name);
}
export function SpendingByCategoryCard({ items }: SpendingByCategoryCardProps) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState<Set<number>>(new Set());
const hasData = items.length > 0;
// Recharts needs a numeric dataKey — API amounts arrive as strings (Decimal
// is serialized as string to avoid float precision loss).
const chartData = items.map((item) => ({ ...item, amount: Number(item.amount) }));
function toggle(categoryId: number) {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(categoryId)) next.delete(categoryId);
else next.add(categoryId);
return next;
});
}
return (
<Card>
<CardHeader>
@@ -66,23 +86,48 @@ export function SpendingByCategoryCard({ items }: SpendingByCategoryCardProps) {
<ul className="w-full min-w-0 flex-1 divide-y divide-gridline">
{items.map((item) => {
const Icon = getCategoryIcon(item.icon);
const hasChildren = item.children.length > 0;
const isExpanded = item.category_id !== null && expanded.has(item.category_id);
return (
<li
key={item.category_id ?? "other"}
className="flex items-center gap-3 py-2 first:pt-0 last:pb-0"
>
<span
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full"
style={{ backgroundColor: `${item.color}26` }}
<li key={item.category_id ?? "other"} className="py-2 first:pt-0 last:pb-0">
<button
type="button"
disabled={!hasChildren}
onClick={() => item.category_id !== null && toggle(item.category_id)}
className="flex w-full items-center gap-3 text-left disabled:cursor-default"
>
<Icon size={14} style={{ color: item.color }} />
</span>
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">
{translateCategoryName(item.name)}
</span>
<span className="shrink-0 text-sm font-medium tabular-nums text-text-primary">
{formatCurrency(item.amount)}
</span>
<span className="flex h-4 w-4 shrink-0 items-center justify-center text-text-muted">
{hasChildren ? isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} /> : null}
</span>
<span
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full"
style={{ backgroundColor: `${item.color}26` }}
>
<Icon size={14} style={{ color: item.color }} />
</span>
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">
{translateCategoryName(item.name)}
</span>
<span className="shrink-0 text-sm font-medium tabular-nums text-text-primary">
{formatCurrency(item.amount)}
</span>
</button>
{hasChildren && isExpanded && (
<ul className="ml-11 mt-1 space-y-1 border-l border-gridline pl-3">
{item.children.map((child) => (
<li key={child.category_id} className="flex items-center gap-2 text-xs">
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: child.color }} />
<span className="min-w-0 flex-1 truncate text-text-secondary">
{childLabel(child, item.category_id, t)}
</span>
<span className="shrink-0 tabular-nums text-text-secondary">
{formatCurrency(child.amount)}
</span>
</li>
))}
</ul>
)}
</li>
);
})}

View File

@@ -1,9 +1,11 @@
import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { getCategoryIcon } from "@/lib/icons";
import { formatCurrency } from "@/lib/format";
import { useTranslation } from "@/lib/i18n";
import { useTranslation, type TranslationKey } from "@/lib/i18n";
import { translateCategoryName } from "@/lib/categoryLabels";
import type { CategoryRankingItem } from "@/types";
import type { CategoryRankingChildItem, CategoryRankingItem } from "@/types";
interface CategoryRankingCardProps {
items: CategoryRankingItem[];
@@ -17,8 +19,26 @@ interface CategoryRankingCardProps {
* detail chart below (locked to one category), this is "which category
* costs the most" across the whole range at once. Clicking a row drills
* into that category in the detail chart/transaction list below. */
// A child's category_id equals its parent's own — the enclosing
// CategoryRankingItem's — when that slice of spend was filed directly on
// the parent with no more specific subcategory chosen (see
// services/category_rollup.py's CategoryRollupChildItem).
function childLabel(child: CategoryRankingChildItem, parentId: number, t: (key: TranslationKey) => string) {
return child.category_id === parentId ? t("reports.directSpendLabel") : translateCategoryName(child.name);
}
export function CategoryRankingCard({ items, isLoading, selectedCategoryId, onSelectCategory }: CategoryRankingCardProps) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState<Set<number>>(new Set());
function toggle(categoryId: number) {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(categoryId)) next.delete(categoryId);
else next.add(categoryId);
return next;
});
}
return (
<Card>
@@ -35,40 +55,72 @@ export function CategoryRankingCard({ items, isLoading, selectedCategoryId, onSe
{items.map((item, index) => {
const Icon = getCategoryIcon(item.icon);
const isSelected = item.category_id === selectedCategoryId;
const hasChildren = item.children.length > 0;
const isExpanded = expanded.has(item.category_id);
return (
<li key={item.category_id}>
<button
type="button"
onClick={() => onSelectCategory(item.category_id)}
className={`flex w-full items-center gap-3 rounded-lg py-2.5 text-left transition-colors hover:bg-surface-2 ${
<div
className={`flex items-center gap-1 rounded-lg transition-colors hover:bg-surface-2 ${
isSelected ? "bg-surface-2" : ""
}`}
>
<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` }}
<button
type="button"
onClick={() => onSelectCategory(item.category_id)}
className="flex flex-1 items-center gap-3 py-2.5 text-left"
>
<Icon size={15} style={{ color: item.color }} />
</span>
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">
{translateCategoryName(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: `${item.percent}%`, backgroundColor: item.color }}
/>
<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` }}
>
<Icon size={15} style={{ color: item.color }} />
</span>
<span className="w-9 shrink-0 text-right text-xs text-text-muted tabular-nums">
{item.percent.toFixed(0)}%
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">
{translateCategoryName(item.name)}
</span>
</span>
<span className="shrink-0 pr-1 text-sm font-medium tabular-nums text-text-primary">
{formatCurrency(item.amount)}
</span>
</button>
<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: `${item.percent}%`, 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>
{hasChildren && (
<button
type="button"
aria-label={isExpanded ? t("common.collapse") : t("common.expand")}
onClick={() => toggle(item.category_id)}
className="mr-1 shrink-0 rounded-md p-1.5 text-text-muted hover:text-text-primary"
>
{isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</button>
)}
</div>
{hasChildren && isExpanded && (
<ul className="ml-11 mb-2 mt-1 space-y-1 border-l border-gridline pl-3">
{item.children.map((child) => (
<li key={child.category_id} className="flex items-center gap-2 text-xs">
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: child.color }} />
<span className="min-w-0 flex-1 truncate text-text-secondary">
{childLabel(child, item.category_id, t)}
</span>
<span className="shrink-0 tabular-nums text-text-secondary">
{formatCurrency(child.amount)}
</span>
</li>
))}
</ul>
)}
</li>
);
})}

View File

@@ -69,10 +69,23 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
useEffect(() => {
if (!open) return;
if (transaction) {
const hasSplits = transaction.splits.length > 0;
// A split's categories always share one parent (see
// routes/transactions.py's _build_splits) — derive that shared base
// from whichever split's category is still live. If every split's
// category was since deleted, there's nothing to derive from; the
// base field is left blank and the user has to pick one again.
const baseCategory = hasSplits ? transaction.splits.find((split) => split.category)?.category : null;
setForm({
type: transaction.type,
account_id: String(transaction.account_id),
category_id: transaction.category_id ? String(transaction.category_id) : "",
category_id: hasSplits
? baseCategory
? String(baseCategory.parent_id ?? baseCategory.id)
: ""
: transaction.category_id
? String(transaction.category_id)
: "",
transfer_account_id: transaction.transfer_account_id ? String(transaction.transfer_account_id) : "",
amount: transaction.amount,
description: transaction.description,
@@ -81,7 +94,6 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
date: transaction.date,
});
setTags(transaction.tags);
const hasSplits = transaction.splits.length > 0;
setSplitMode(hasSplits);
setSplitRows(
hasSplits
@@ -134,6 +146,34 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
const splitAllocatedCents = splitRows.reduce((sum, row) => sum + toCents(row.amount), 0);
const splitRemainingCents = toCents(form.amount) - splitAllocatedCents;
// The category select becomes the split's "base" category while
// splitting — restricted to top-level categories — and each split row can
// only pick that base itself or one of its direct children (see
// routes/transactions.py's _build_splits: a split's categories always
// share one parent).
const topLevelCategories = relevantCategories.filter((category) => !category.indented);
const baseChildCategories = kindCategories.filter((category) => category.parent_id === Number(form.category_id));
const categorySelectOptions = splitMode ? topLevelCategories : relevantCategories;
function toggleSplitMode() {
setSplitMode((prev) => {
const next = !prev;
if (next) {
const current = relevantCategories.find((category) => String(category.id) === form.category_id);
if (current?.parent_id) {
setForm((f) => ({ ...f, category_id: String(current.parent_id) }));
}
setSplitRows([emptySplitRow(), emptySplitRow()]);
}
return next;
});
}
function handleBaseCategoryChange(value: string) {
setForm((prev) => ({ ...prev, category_id: value }));
if (splitMode) setSplitRows([emptySplitRow(), emptySplitRow()]);
}
async function handleSubmit(event: React.FormEvent) {
event.preventDefault();
setError(null);
@@ -157,6 +197,10 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
// switched the transaction to a transfer, which can't carry splits).
let splits: TransactionSplitInput[] | undefined;
if (isSplitEditingNow) {
if (!form.category_id) {
setError(t("transactions.form.errorSplitNoBaseCategory"));
return;
}
const filledRows = splitRows.filter((row) => row.category_id || row.amount);
if (filledRows.length < 2) {
setError(t("transactions.form.errorSplitMinRows"));
@@ -318,29 +362,35 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
<button
type="button"
className="mb-1 text-xs text-series-1 hover:underline"
onClick={() => setSplitMode((prev) => !prev)}
onClick={toggleSplitMode}
>
{splitMode ? t("transactions.form.splitToggleOff") : t("transactions.form.splitToggle")}
</button>
</div>
{!splitMode ? (
<Select
id="category"
value={form.category_id}
onChange={(event) => setForm((prev) => ({ ...prev, category_id: event.target.value }))}
>
<option value="">{t("transactions.form.noCategory")}</option>
{relevantCategories.map((category) => (
<option key={category.id} value={category.id}>
{category.indented ? `    ↳ ` : ""}
{translateCategoryName(category.name)}
</option>
))}
</Select>
) : (
<div className="space-y-2">
<p className="text-xs text-text-muted">{t("transactions.form.splitHint")}</p>
<Select
id="category"
value={form.category_id}
onChange={(event) => handleBaseCategoryChange(event.target.value)}
>
<option value="">{t("transactions.form.noCategory")}</option>
{categorySelectOptions.map((category) => (
<option key={category.id} value={category.id}>
{category.indented ? `    ↳ ` : ""}
{translateCategoryName(category.name)}
</option>
))}
</Select>
{splitMode && (
<div className="mt-2 space-y-2">
{!form.category_id ? (
<p className="text-xs text-text-muted">{t("transactions.form.splitHint")}</p>
) : baseChildCategories.length === 0 ? (
<p className="text-xs text-text-muted">{t("transactions.form.splitNoChildren")}</p>
) : (
<p className="text-xs text-text-muted">{t("transactions.form.splitHint")}</p>
)}
{splitRows.map((row) => (
<div key={row.key} className="space-y-1.5 rounded-lg border border-border bg-surface-1 p-2">
<div className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-2">
@@ -348,14 +398,17 @@ export function TransactionFormModal({ open, onClose, transaction }: Transaction
aria-label={t("transactions.form.splitCategoryPlaceholder")}
className="sm:flex-1"
value={row.category_id}
disabled={!form.category_id}
onChange={(event) => updateSplitRow(row.key, { category_id: event.target.value })}
>
<option value="" disabled>
{t("transactions.form.splitCategoryPlaceholder")}
</option>
{relevantCategories.map((category) => (
{form.category_id && (
<option value={form.category_id}>{t("transactions.form.splitDirectOption")}</option>
)}
{baseChildCategories.map((category) => (
<option key={category.id} value={category.id}>
{category.indented ? `    ↳ ` : ""}
{translateCategoryName(category.name)}
</option>
))}

View File

@@ -29,6 +29,8 @@ const ru = {
"topbar.openMenu": "Открыть меню",
"common.loading": "Загрузка…",
"common.expand": "Развернуть",
"common.collapse": "Свернуть",
"common.back": "Назад",
"common.next": "Далее",
"common.clear": "Очистить",
@@ -285,6 +287,10 @@ const ru = {
"transactions.form.errorSplitMinRows": "Нужно как минимум 2 категории для разбивки",
"transactions.form.errorSplitIncomplete": "Выберите категорию и сумму для каждой строки разбивки",
"transactions.form.errorSplitMismatch": "Сумма по категориям должна совпадать с суммой транзакции",
"transactions.form.errorSplitNoBaseCategory": "Сначала выберите базовую категорию",
"transactions.form.splitDirectOption": "— без конкретной подкатегории —",
"transactions.form.splitNoChildren": "У этой категории пока нет подкатегорий — добавьте их на странице «Категории», чтобы разбивать покупки по ним.",
"reports.directSpendLabel": "Без подкатегории",
"reports.categoryLabel": "Категория",
"reports.expenseGroup": "Расходы",
@@ -504,6 +510,8 @@ const en: Record<keyof typeof ru, string> = {
"topbar.openMenu": "Open menu",
"common.loading": "Loading…",
"common.expand": "Expand",
"common.collapse": "Collapse",
"common.back": "Back",
"common.next": "Next",
"common.clear": "Clear",
@@ -760,6 +768,10 @@ const en: Record<keyof typeof ru, string> = {
"transactions.form.errorSplitMinRows": "Splitting needs at least 2 categories",
"transactions.form.errorSplitIncomplete": "Pick a category and an amount for every split row",
"transactions.form.errorSplitMismatch": "Split amounts must add up to the transaction amount",
"transactions.form.errorSplitNoBaseCategory": "Pick a base category first",
"transactions.form.splitDirectOption": "— no specific subcategory —",
"transactions.form.splitNoChildren": "This category has no subcategories yet — add some on the Categories page to split purchases across them.",
"reports.directSpendLabel": "No subcategory",
"reports.categoryLabel": "Category",
"reports.expenseGroup": "Expenses",

View File

@@ -161,6 +161,18 @@ export interface RecurringTransactionInput {
anchor_date: string;
}
// One subcategory's (or the parent's own direct, un-subcategorized) share
// of a CategoryBreakdownItem's total. Populated only when more than one
// distinct category fed the slice — a single-source category (the common
// case) leaves this off the parent item entirely.
export interface CategoryBreakdownChildItem {
category_id: number;
name: string;
color: string;
icon: string | null;
amount: string;
}
export interface CategoryBreakdownItem {
category_id: number | null;
name: string;
@@ -168,6 +180,7 @@ export interface CategoryBreakdownItem {
icon: string | null;
amount: string;
percent: number;
children: CategoryBreakdownChildItem[];
}
export interface DashboardSummary {
@@ -310,6 +323,14 @@ export interface CashFlowResponse {
total_net: string;
}
export interface CategoryRankingChildItem {
category_id: number;
name: string;
color: string;
icon: string | null;
amount: string;
}
export interface CategoryRankingItem {
category_id: number;
name: string;
@@ -318,6 +339,7 @@ export interface CategoryRankingItem {
amount: string;
percent: number;
transaction_count: number;
children: CategoryRankingChildItem[];
}
export interface CategoryRankingReport {