mirror of
https://github.com/Zproger/Aurum.git
synced 2026-11-18 08:02:49 +07:00
Initial public release
Aurum — a self-hosted personal finance operating system: cash flow, net worth tracking, budgets, goals, recurring payments, reports, proactive alerts, and a compound-interest returns calculator, all bilingual (RU/EN) and mobile-first. Ships as a three-container Docker Compose stack (Postgres + FastAPI + nginx-served React frontend). See README.md for setup and CONTRIBUTING.md for development.
This commit is contained in:
93
frontend/src/components/accounts/AccountFormModal.tsx
Normal file
93
frontend/src/components/accounts/AccountFormModal.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label, Select } from "@/components/ui/Input";
|
||||
import { useCreateAccount, useUpdateAccount } from "@/hooks/useAccounts";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { Account, AccountType } from "@/types";
|
||||
|
||||
interface AccountFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
account?: Account | null;
|
||||
}
|
||||
|
||||
const ACCOUNT_TYPES: AccountType[] = ["checking", "savings", "credit_card", "cash", "investment", "other"];
|
||||
|
||||
const EMPTY_FORM = { name: "", type: "checking" as AccountType };
|
||||
|
||||
export function AccountFormModal({ open, onClose, account }: AccountFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const createAccount = useCreateAccount();
|
||||
const updateAccount = useUpdateAccount();
|
||||
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setForm(account ? { name: account.name, type: account.type } : EMPTY_FORM);
|
||||
setError(null);
|
||||
}, [open, account]);
|
||||
|
||||
const isSaving = createAccount.isPending || updateAccount.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (account) {
|
||||
await updateAccount.mutateAsync({ id: account.id, input: form });
|
||||
} else {
|
||||
await createAccount.mutateAsync(form);
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("account.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={account ? t("account.form.editTitle") : t("account.form.newTitle")}>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="account-name">{t("account.form.nameLabel")}</Label>
|
||||
<Input
|
||||
id="account-name"
|
||||
required
|
||||
placeholder={t("account.form.namePlaceholder")}
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="account-type">{t("account.form.typeLabel")}</Label>
|
||||
<Select
|
||||
id="account-type"
|
||||
value={form.type}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, type: event.target.value as AccountType }))}
|
||||
>
|
||||
{ACCOUNT_TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{t(`account.type.${type}` as TranslationKey)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
90
frontend/src/components/accounts/AccountList.tsx
Normal file
90
frontend/src/components/accounts/AccountList.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import { Archive, ArchiveRestore, Banknote, CreditCard, Package, Pencil, PiggyBank, TrendingUp, Trash2, Wallet, type LucideIcon } from "lucide-react";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { Account, AccountType, AccountWithBalance } from "@/types";
|
||||
|
||||
interface AccountListProps {
|
||||
items: AccountWithBalance[];
|
||||
onEdit: (account: Account) => void;
|
||||
onToggleArchived: (account: AccountWithBalance) => void;
|
||||
onDelete: (account: AccountWithBalance) => void;
|
||||
}
|
||||
|
||||
const TYPE_ICONS: Record<AccountType, LucideIcon> = {
|
||||
checking: Wallet,
|
||||
savings: PiggyBank,
|
||||
credit_card: CreditCard,
|
||||
cash: Banknote,
|
||||
investment: TrendingUp,
|
||||
other: Package,
|
||||
};
|
||||
|
||||
export function AccountList({ items, onEdit, onToggleArchived, onDelete }: AccountListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-10 text-center text-sm text-text-muted">{t("account.empty")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((account) => {
|
||||
const Icon = TYPE_ICONS[account.type];
|
||||
const balance = Number(account.balance);
|
||||
|
||||
return (
|
||||
<li key={account.id} className={`flex items-center gap-3 py-3 ${account.is_archived ? "opacity-50" : ""}`}>
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2">
|
||||
<Icon size={16} className="text-text-secondary" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-1.5 truncate text-sm font-medium text-text-primary">
|
||||
{account.name}
|
||||
{account.is_archived && (
|
||||
<span className="shrink-0 rounded bg-surface-2 px-1 py-0.5 text-[10px] leading-none text-text-muted">
|
||||
{t("account.archivedBadge")}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="block truncate text-xs text-text-muted">
|
||||
{t(`account.type.${account.type}` as TranslationKey)}
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className="shrink-0 text-sm font-medium tabular-nums"
|
||||
style={{ color: balance < 0 ? "var(--danger)" : "var(--text-primary)" }}
|
||||
>
|
||||
{formatCurrency(balance)}
|
||||
</span>
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={account.is_archived ? t("account.unarchiveLabel") : t("account.archiveLabel")}
|
||||
onClick={() => onToggleArchived(account)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
{account.is_archived ? <ArchiveRestore size={15} /> : <Archive size={15} />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(account)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(account)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
112
frontend/src/components/budget/BudgetFormModal.tsx
Normal file
112
frontend/src/components/budget/BudgetFormModal.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label, Select } from "@/components/ui/Input";
|
||||
import { useCategories } from "@/hooks/useCategories";
|
||||
import { useCreateBudget, useUpdateBudget } from "@/hooks/useBudgets";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { Budget } from "@/types";
|
||||
|
||||
interface BudgetFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
budget?: Budget | null;
|
||||
/** Expense categories that already have a budget — excluded from the
|
||||
* create picker since each category can only carry one budget. */
|
||||
excludeCategoryIds: number[];
|
||||
}
|
||||
|
||||
export function BudgetFormModal({ open, onClose, budget, excludeCategoryIds }: BudgetFormModalProps) {
|
||||
const { t, language } = useTranslation();
|
||||
const { data: categories } = useCategories();
|
||||
const createBudget = useCreateBudget();
|
||||
const updateBudget = useUpdateBudget();
|
||||
|
||||
const [categoryId, setCategoryId] = useState("");
|
||||
const [monthlyLimit, setMonthlyLimit] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const availableCategories = (categories ?? [])
|
||||
.filter((category) => category.kind === "expense" && !excludeCategoryIds.includes(category.id))
|
||||
.sort((a, b) => translateCategoryName(a.name).localeCompare(translateCategoryName(b.name), language));
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (budget) {
|
||||
setCategoryId(String(budget.category_id));
|
||||
setMonthlyLimit(budget.monthly_limit);
|
||||
} else {
|
||||
setCategoryId(availableCategories[0] ? String(availableCategories[0].id) : "");
|
||||
setMonthlyLimit("");
|
||||
}
|
||||
setError(null);
|
||||
// availableCategories is derived from `categories`, not a stable dep — only re-run on open/budget change.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, budget]);
|
||||
|
||||
const isSaving = createBudget.isPending || updateBudget.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (budget) {
|
||||
await updateBudget.mutateAsync({ id: budget.id, monthlyLimit });
|
||||
} else {
|
||||
await createBudget.mutateAsync({ category_id: Number(categoryId), monthly_limit: monthlyLimit });
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("budget.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={budget ? t("budget.form.editTitle") : t("budget.form.newTitle")}>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="budget-category">{t("budget.form.categoryLabel")}</Label>
|
||||
{budget ? (
|
||||
<p className="text-sm text-text-primary">{translateCategoryName(budget.category_name)}</p>
|
||||
) : availableCategories.length === 0 ? (
|
||||
<p className="text-sm text-text-muted">{t("budget.form.noCategoriesAvailable")}</p>
|
||||
) : (
|
||||
<Select id="budget-category" required value={categoryId} onChange={(event) => setCategoryId(event.target.value)}>
|
||||
{availableCategories.map((category) => (
|
||||
<option key={category.id} value={category.id}>
|
||||
{translateCategoryName(category.name)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="budget-limit">{t("budget.form.limitLabel")}</Label>
|
||||
<Input
|
||||
id="budget-limit"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required
|
||||
value={monthlyLimit}
|
||||
onChange={(event) => setMonthlyLimit(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving || (!budget && availableCategories.length === 0)}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
85
frontend/src/components/budget/BudgetList.tsx
Normal file
85
frontend/src/components/budget/BudgetList.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { BudgetStatus } from "@/types";
|
||||
|
||||
interface BudgetListProps {
|
||||
items: BudgetStatus[];
|
||||
onEdit: (item: BudgetStatus) => void;
|
||||
onDelete: (item: BudgetStatus) => void;
|
||||
}
|
||||
|
||||
export function BudgetList({ items, onEdit, onDelete }: BudgetListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-10 text-center text-sm text-text-muted">{t("budget.empty")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((item) => {
|
||||
const Icon = getCategoryIcon(item.category_icon);
|
||||
const spent = Number(item.spent);
|
||||
const limit = Number(item.monthly_limit);
|
||||
const barColor = item.is_over_budget ? "var(--danger)" : "var(--success)";
|
||||
const fillPercent = Math.min(100, item.percent);
|
||||
|
||||
return (
|
||||
<li key={item.budget_id} className="py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full"
|
||||
style={{ backgroundColor: `${item.category_color}26` }}
|
||||
>
|
||||
<Icon size={16} style={{ color: item.category_color }} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-text-primary">
|
||||
{translateCategoryName(item.category_name)}
|
||||
</span>
|
||||
<span className="shrink-0 text-sm tabular-nums text-text-primary">
|
||||
{formatCurrency(spent)} <span className="text-text-muted">/ {formatCurrency(limit)}</span>
|
||||
</span>
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(item)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(item)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-2 pl-12">
|
||||
<span className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||
<span
|
||||
className="block h-full rounded-full"
|
||||
style={{ width: `${fillPercent}%`, backgroundColor: barColor }}
|
||||
/>
|
||||
</span>
|
||||
<span className="w-10 shrink-0 text-right text-xs tabular-nums text-text-muted">
|
||||
{item.percent.toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 pl-12 text-xs" style={{ color: item.is_over_budget ? "var(--danger)" : "var(--text-muted)" }}>
|
||||
{item.is_over_budget
|
||||
? t("budget.overBy", { amount: formatCurrency(spent - limit) })
|
||||
: t("budget.remaining", { amount: formatCurrency(limit - spent) })}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
157
frontend/src/components/cashflow/CashFlowChart.tsx
Normal file
157
frontend/src/components/cashflow/CashFlowChart.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import { Bar, BarChart, Legend, ResponsiveContainer, Tooltip, XAxis } from "recharts";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { formatCurrency, formatSignedCurrency, getIntlLocale } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { CashFlowResponse } from "@/types";
|
||||
|
||||
interface CashFlowChartProps {
|
||||
cashFlow: CashFlowResponse | 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`)
|
||||
);
|
||||
}
|
||||
|
||||
/** Same landmark idea as the Net Worth and category-spending charts: year
|
||||
* ticks only when the bars span more than one calendar year. */
|
||||
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;
|
||||
}
|
||||
|
||||
interface ChartPoint {
|
||||
key: string;
|
||||
income: number;
|
||||
expense: number;
|
||||
net: number;
|
||||
}
|
||||
|
||||
function ChartTooltip({
|
||||
active,
|
||||
payload,
|
||||
incomeLabel,
|
||||
expenseLabel,
|
||||
netLabel,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ payload: ChartPoint }>;
|
||||
incomeLabel: string;
|
||||
expenseLabel: string;
|
||||
netLabel: string;
|
||||
}) {
|
||||
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="text-success">
|
||||
{incomeLabel}: {formatCurrency(point.income)}
|
||||
</p>
|
||||
<p className="text-danger">
|
||||
{expenseLabel}: {formatCurrency(point.expense)}
|
||||
</p>
|
||||
<p className="font-medium text-text-primary">
|
||||
{netLabel}: {formatSignedCurrency(point.net)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CashFlowChart({ cashFlow, isLoading }: CashFlowChartProps) {
|
||||
const { t } = useTranslation();
|
||||
const incomeLabel = t("cashFlow.income");
|
||||
const expenseLabel = t("cashFlow.expense");
|
||||
const netLabel = t("cashFlow.net");
|
||||
|
||||
const chartData: ChartPoint[] =
|
||||
cashFlow?.points.map((point) => ({
|
||||
key: monthKey(point.year, point.month),
|
||||
income: Number(point.income),
|
||||
expense: Number(point.expense),
|
||||
net: Number(point.net),
|
||||
})) ?? [];
|
||||
const yearTicks = computeYearTicks(chartData.map((point) => point.key));
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="items-start">
|
||||
<div>
|
||||
<CardTitle>{t("nav.cashFlow")}</CardTitle>
|
||||
<p className="mt-1.5 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
||||
{isLoading || !cashFlow ? "…" : formatSignedCurrency(cashFlow.total_net)}
|
||||
</p>
|
||||
{cashFlow && (
|
||||
<p className="mt-1 text-sm">
|
||||
<span className="font-medium text-success">
|
||||
{incomeLabel} {formatCurrency(cashFlow.total_income)}
|
||||
</span>
|
||||
<span className="text-text-muted"> · </span>
|
||||
<span className="font-medium text-danger">
|
||||
{expenseLabel} {formatCurrency(cashFlow.total_expense)}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-56 w-full sm:h-64">
|
||||
{isLoading || !cashFlow || chartData.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-text-muted">
|
||||
{isLoading ? t("common.loading") : t("cashFlow.noData")}
|
||||
</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 incomeLabel={incomeLabel} expenseLabel={expenseLabel} netLabel={netLabel} />}
|
||||
cursor={{ fill: "var(--surface-2)" }}
|
||||
/>
|
||||
<Legend
|
||||
verticalAlign="top"
|
||||
height={24}
|
||||
formatter={(value) => (value === "income" ? incomeLabel : expenseLabel)}
|
||||
wrapperStyle={{ fontSize: 12, color: "var(--text-muted)" }}
|
||||
/>
|
||||
<Bar dataKey="income" fill="var(--success)" radius={[2, 2, 0, 0]} isAnimationActive={false} />
|
||||
<Bar dataKey="expense" fill="var(--danger)" 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>
|
||||
);
|
||||
}
|
||||
62
frontend/src/components/dashboard/RecentTransactionsCard.tsx
Normal file
62
frontend/src/components/dashboard/RecentTransactionsCard.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency, formatTransactionDate } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { useTransactions } from "@/hooks/useTransactions";
|
||||
|
||||
export function RecentTransactionsCard() {
|
||||
const { t } = useTranslation();
|
||||
const { data, isLoading } = useTransactions({ page: 1, page_size: 6 });
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("dashboard.recentTransactionsTitle")}</CardTitle>
|
||||
<Link to="/transactions" className="text-xs font-medium text-series-1 hover:underline">
|
||||
{t("dashboard.allTransactionsLink")}
|
||||
</Link>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||
) : !data?.items.length ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("dashboard.noTransactionsYet")}</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{data.items.map((tx) => {
|
||||
const Icon = getCategoryIcon(tx.category?.icon);
|
||||
const isTransfer = tx.type === "transfer";
|
||||
const isExpense = tx.type === "expense";
|
||||
const color = tx.category?.color ?? "var(--text-muted)";
|
||||
return (
|
||||
<li key={tx.id} 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: `${color}26` }}
|
||||
>
|
||||
<Icon size={15} style={{ color }} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm text-text-primary">{tx.description}</span>
|
||||
<span className="block text-xs text-text-muted">
|
||||
{formatTransactionDate(tx.date)} · {tx.account.name}
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className={`shrink-0 text-sm font-medium tabular-nums ${
|
||||
isTransfer ? "text-text-muted" : isExpense ? "text-text-primary" : "text-success"
|
||||
}`}
|
||||
>
|
||||
{isTransfer ? "" : isExpense ? "-" : "+"}
|
||||
{formatCurrency(Number(tx.amount))}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
95
frontend/src/components/dashboard/SpendingByCategoryCard.tsx
Normal file
95
frontend/src/components/dashboard/SpendingByCategoryCard.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
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 { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { CategoryBreakdownItem } from "@/types";
|
||||
|
||||
interface SpendingByCategoryCardProps {
|
||||
items: CategoryBreakdownItem[];
|
||||
}
|
||||
|
||||
function DonutTooltip({ active, payload }: { active?: boolean; payload?: Array<{ payload: CategoryBreakdownItem }> }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const item = payload[0].payload;
|
||||
return (
|
||||
<div className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm shadow-md">
|
||||
<p className="font-medium text-text-primary">{translateCategoryName(item.name)}</p>
|
||||
<p className="text-text-secondary">
|
||||
{formatCurrency(item.amount)} · {item.percent.toFixed(1)}%
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpendingByCategoryCard({ items }: SpendingByCategoryCardProps) {
|
||||
const { t } = useTranslation();
|
||||
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) }));
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("dashboard.spendingByCategoryTitle")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!hasData ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("dashboard.noExpensesThisMonth")}</p>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-6 sm:flex-row sm:items-center">
|
||||
<div className="h-56 w-56 shrink-0 sm:h-64 sm:w-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
dataKey="amount"
|
||||
nameKey="name"
|
||||
innerRadius="62%"
|
||||
outerRadius="100%"
|
||||
paddingAngle={2}
|
||||
stroke="var(--surface-1)"
|
||||
strokeWidth={2}
|
||||
isAnimationActive={false}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<Cell key={item.category_id ?? "other"} fill={item.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip content={<DonutTooltip />} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
<ul className="w-full min-w-0 flex-1 divide-y divide-gridline">
|
||||
{items.map((item) => {
|
||||
const Icon = getCategoryIcon(item.icon);
|
||||
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` }}
|
||||
>
|
||||
<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>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
27
frontend/src/components/dashboard/StatCard.tsx
Normal file
27
frontend/src/components/dashboard/StatCard.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Card } from "@/components/ui/Card";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
value: string;
|
||||
caption: string;
|
||||
tone?: "default" | "success" | "danger";
|
||||
}
|
||||
|
||||
const TONE_CLASSES: Record<NonNullable<StatCardProps["tone"]>, string> = {
|
||||
default: "text-text-primary",
|
||||
success: "text-success",
|
||||
danger: "text-danger",
|
||||
};
|
||||
|
||||
export function StatCard({ label, value, caption, tone = "default" }: StatCardProps) {
|
||||
return (
|
||||
<Card className="p-4 sm:p-5">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-text-muted">{label}</p>
|
||||
<p className={cn("mt-1.5 text-2xl font-semibold tabular-nums sm:text-[28px]", TONE_CLASSES[tone])}>
|
||||
{value}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-text-muted">{caption}</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
93
frontend/src/components/goals/GoalContributionModal.tsx
Normal file
93
frontend/src/components/goals/GoalContributionModal.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label } from "@/components/ui/Input";
|
||||
import { useAddGoalContribution } from "@/hooks/useGoals";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { Goal } from "@/types";
|
||||
|
||||
interface GoalContributionModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
goal: Goal | null;
|
||||
}
|
||||
|
||||
function todayIso() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function GoalContributionModal({ open, onClose, goal }: GoalContributionModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const addContribution = useAddGoalContribution();
|
||||
|
||||
const [amount, setAmount] = useState("");
|
||||
const [date, setDate] = useState(todayIso());
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setAmount("");
|
||||
setDate(todayIso());
|
||||
setError(null);
|
||||
}, [open, goal]);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!goal) return;
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await addContribution.mutateAsync({ id: goal.id, input: { amount, date } });
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("goal.contribution.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={goal ? t("goal.contribution.title", { name: goal.name }) : ""}
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="contribution-amount">{t("goal.contribution.amountLabel")}</Label>
|
||||
<Input
|
||||
id="contribution-amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
required
|
||||
placeholder={t("goal.contribution.amountPlaceholder")}
|
||||
value={amount}
|
||||
onChange={(event) => setAmount(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="contribution-date">{t("goal.contribution.dateLabel")}</Label>
|
||||
<Input
|
||||
id="contribution-date"
|
||||
type="date"
|
||||
required
|
||||
value={date}
|
||||
onChange={(event) => setDate(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">{t("goal.contribution.hint")}</p>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={addContribution.isPending}>
|
||||
{addContribution.isPending ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
110
frontend/src/components/goals/GoalFormModal.tsx
Normal file
110
frontend/src/components/goals/GoalFormModal.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label } from "@/components/ui/Input";
|
||||
import { useCreateGoal, useUpdateGoal } from "@/hooks/useGoals";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { Goal } from "@/types";
|
||||
|
||||
interface GoalFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
goal?: Goal | null;
|
||||
}
|
||||
|
||||
const EMPTY_FORM = { name: "", target_amount: "", target_date: "" };
|
||||
|
||||
export function GoalFormModal({ open, onClose, goal }: GoalFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const createGoal = useCreateGoal();
|
||||
const updateGoal = useUpdateGoal();
|
||||
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (goal) {
|
||||
setForm({ name: goal.name, target_amount: goal.target_amount, target_date: goal.target_date ?? "" });
|
||||
} else {
|
||||
setForm(EMPTY_FORM);
|
||||
}
|
||||
setError(null);
|
||||
}, [open, goal]);
|
||||
|
||||
const isSaving = createGoal.isPending || updateGoal.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
const input = {
|
||||
name: form.name,
|
||||
target_amount: form.target_amount,
|
||||
target_date: form.target_date || null,
|
||||
};
|
||||
|
||||
try {
|
||||
if (goal) {
|
||||
await updateGoal.mutateAsync({ id: goal.id, input });
|
||||
} else {
|
||||
await createGoal.mutateAsync(input);
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("goal.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={goal ? t("goal.form.editTitle") : t("goal.form.newTitle")}>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="goal-name">{t("goal.form.nameLabel")}</Label>
|
||||
<Input
|
||||
id="goal-name"
|
||||
required
|
||||
placeholder={t("goal.form.namePlaceholder")}
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="goal-target">{t("goal.form.targetAmountLabel")}</Label>
|
||||
<Input
|
||||
id="goal-target"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required
|
||||
value={form.target_amount}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, target_amount: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="goal-date">{t("goal.form.targetDateLabel")}</Label>
|
||||
<Input
|
||||
id="goal-date"
|
||||
type="date"
|
||||
value={form.target_date}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, target_date: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
94
frontend/src/components/goals/GoalList.tsx
Normal file
94
frontend/src/components/goals/GoalList.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Flag, PiggyBank, Pencil, Trash2 } from "lucide-react";
|
||||
import { formatCurrency, getIntlLocale } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { Goal } from "@/types";
|
||||
|
||||
interface GoalListProps {
|
||||
items: Goal[];
|
||||
onContribute: (goal: Goal) => void;
|
||||
onEdit: (goal: Goal) => void;
|
||||
onDelete: (goal: Goal) => void;
|
||||
}
|
||||
|
||||
function formatTargetDate(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(getIntlLocale(), { day: "numeric", month: "short", year: "numeric" }).format(
|
||||
new Date(`${isoDate}T00:00:00`)
|
||||
);
|
||||
}
|
||||
|
||||
export function GoalList({ items, onContribute, onEdit, onDelete }: GoalListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-10 text-center text-sm text-text-muted">{t("goal.empty")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((goal) => {
|
||||
const current = Number(goal.current_amount);
|
||||
const target = Number(goal.target_amount);
|
||||
const remaining = Number(goal.remaining);
|
||||
const fillPercent = Math.min(100, goal.percent);
|
||||
|
||||
return (
|
||||
<li key={goal.id} className="py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2">
|
||||
<Flag size={16} className="text-text-secondary" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium text-text-primary">{goal.name}</span>
|
||||
<span className="shrink-0 text-sm tabular-nums text-text-primary">
|
||||
{formatCurrency(current)} <span className="text-text-muted">/ {formatCurrency(target)}</span>
|
||||
</span>
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("goal.contributeLabel")}
|
||||
onClick={() => onContribute(goal)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-success"
|
||||
>
|
||||
<PiggyBank size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(goal)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(goal)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-2 pl-12">
|
||||
<span className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||
<span
|
||||
className="block h-full rounded-full bg-success"
|
||||
style={{ width: `${fillPercent}%` }}
|
||||
/>
|
||||
</span>
|
||||
<span className="w-10 shrink-0 text-right text-xs tabular-nums text-text-muted">
|
||||
{goal.percent.toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 pl-12 text-xs" style={{ color: goal.is_reached ? "var(--success)" : "var(--text-muted)" }}>
|
||||
{goal.is_reached
|
||||
? t("goal.reached")
|
||||
: goal.target_date
|
||||
? t("goal.remainingWithDate", { amount: formatCurrency(remaining), date: formatTargetDate(goal.target_date) })
|
||||
: t("goal.remaining", { amount: formatCurrency(remaining) })}
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
57
frontend/src/components/insights/AlertBanner.tsx
Normal file
57
frontend/src/components/insights/AlertBanner.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
import { useFinancialAlerts } from "@/hooks/useInsights";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { FinancialAlert } from "@/types";
|
||||
|
||||
// Maps the backend's alert key to the translation template that consumes its params.
|
||||
const ALERT_MESSAGE_KEYS: Record<string, TranslationKey> = {
|
||||
negative_cash_flow_streak: "insights.negativeCashFlow",
|
||||
net_worth_decline_streak: "insights.netWorthDecline",
|
||||
budget_exceeded: "insights.budgetExceeded",
|
||||
risky_allocation_exceeded: "insights.riskyAllocationExceeded",
|
||||
};
|
||||
|
||||
function alertMessage(alert: FinancialAlert, t: ReturnType<typeof useTranslation>["t"]): string {
|
||||
// "1 categories"/"в 1 категориях" is bad grammar in both languages —
|
||||
// singular gets its own pre-written key instead of trying to interpolate
|
||||
// a plural-aware word form through a plain {{count}} template.
|
||||
if (alert.key === "budget_exceeded" && alert.params.count === 1) {
|
||||
return t("insights.budgetExceededOne");
|
||||
}
|
||||
const messageKey = ALERT_MESSAGE_KEYS[alert.key];
|
||||
if (!messageKey) return alert.key;
|
||||
return t(messageKey, alert.params);
|
||||
}
|
||||
|
||||
interface AlertBannerProps {
|
||||
/** Alert keys to hide on this particular page — e.g. Dashboard omits
|
||||
* risky_allocation_exceeded because it reads as too alarming next to the
|
||||
* stat cards there; it still shows on Net Worth/Budget where the rest of
|
||||
* this banner is used unfiltered. */
|
||||
excludeKeys?: string[];
|
||||
}
|
||||
|
||||
/** Proactive early warnings — sustained negative cash flow or a sustained
|
||||
* net-worth decline — computed server-side from data that already exists,
|
||||
* no configuration. Renders nothing when there's nothing to flag. */
|
||||
export function AlertBanner({ excludeKeys }: AlertBannerProps = {}) {
|
||||
const { data } = useFinancialAlerts();
|
||||
const { t } = useTranslation();
|
||||
const alerts = (data?.alerts ?? []).filter((alert) => !excludeKeys?.includes(alert.key));
|
||||
|
||||
if (alerts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{alerts.map((alert) => (
|
||||
<div
|
||||
key={alert.key}
|
||||
className="flex items-start gap-2.5 rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger"
|
||||
>
|
||||
<TriangleAlert size={16} className="mt-0.5 shrink-0" />
|
||||
<span>{alertMessage(alert, t)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
frontend/src/components/layout/Logo.tsx
Normal file
38
frontend/src/components/layout/Logo.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Aurum's mark: a coin with an "A" monogram. Rendered as inline SVG (not the
|
||||
* 🜚 alchemical-gold emoji this replaced) because emoji glyph coverage for
|
||||
* that character is inconsistent across platforms/fonts and rendered
|
||||
* mangled for the user — an SVG always looks the same everywhere. Kept in
|
||||
* sync with public/favicon.svg.
|
||||
*/
|
||||
interface LogoProps {
|
||||
size?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Logo({ size = 24, className }: LogoProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 32 32" className={className} aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id="aurumCoin" x1="5" y1="4" x2="27" y2="28" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stopColor="#f7d488" />
|
||||
<stop offset="0.55" stopColor="#eda100" />
|
||||
<stop offset="1" stopColor="#a8690a" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<circle cx="16" cy="16" r="14.5" fill="url(#aurumCoin)" stroke="#7a4e08" strokeWidth="1.2" />
|
||||
<circle cx="16" cy="16" r="11.5" fill="none" stroke="#7a4e08" strokeWidth="0.6" opacity="0.45" />
|
||||
<text
|
||||
x="16"
|
||||
y="21.5"
|
||||
fontFamily="Georgia, 'Times New Roman', serif"
|
||||
fontSize="15"
|
||||
fontWeight="700"
|
||||
textAnchor="middle"
|
||||
fill="#3a2405"
|
||||
>
|
||||
A
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
37
frontend/src/components/layout/MonthSelector.tsx
Normal file
37
frontend/src/components/layout/MonthSelector.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { getMonthLabels } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface MonthSelectorProps {
|
||||
month: number; // 1-12
|
||||
onChange: (month: number) => void;
|
||||
}
|
||||
|
||||
export function MonthSelector({ month, onChange }: MonthSelectorProps) {
|
||||
const { language } = useTranslation();
|
||||
const monthLabels = getMonthLabels(language);
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{monthLabels.map((label, index) => {
|
||||
const value = index + 1;
|
||||
const active = value === month;
|
||||
return (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
onClick={() => onChange(value)}
|
||||
className={cn(
|
||||
"shrink-0 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors",
|
||||
active
|
||||
? "border-series-6 bg-series-6 text-white"
|
||||
: "border-border bg-surface-1 text-text-secondary hover:bg-surface-2"
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
35
frontend/src/components/layout/PillSelector.tsx
Normal file
35
frontend/src/components/layout/PillSelector.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface PillOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface PillSelectorProps<T extends string> {
|
||||
options: Array<PillOption<T>>;
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
}
|
||||
|
||||
export function PillSelector<T extends string>({ options, value, onChange }: PillSelectorProps<T>) {
|
||||
return (
|
||||
<div className="inline-flex gap-1 rounded-lg border border-border bg-surface-1 p-1">
|
||||
{options.map((option) => {
|
||||
const active = option.value === value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => onChange(option.value)}
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
|
||||
active ? "bg-surface-2 text-text-primary" : "text-text-muted hover:text-text-primary"
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
frontend/src/components/layout/RangeSelector.tsx
Normal file
21
frontend/src/components/layout/RangeSelector.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { PillSelector } from "@/components/layout/PillSelector";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { NetWorthRange } from "@/types";
|
||||
|
||||
interface RangeSelectorProps {
|
||||
value: NetWorthRange;
|
||||
onChange: (value: NetWorthRange) => void;
|
||||
}
|
||||
|
||||
export function RangeSelector({ value, onChange }: RangeSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const ranges: Array<{ value: NetWorthRange; label: string }> = [
|
||||
{ value: "30d", label: "30D" },
|
||||
{ value: "90d", label: "90D" },
|
||||
{ value: "1y", label: "1Y" },
|
||||
{ value: "5y", label: "5Y" },
|
||||
{ value: "all", label: t("common.allShort") },
|
||||
];
|
||||
|
||||
return <PillSelector options={ranges} value={value} onChange={onChange} />;
|
||||
}
|
||||
142
frontend/src/components/layout/Sidebar.tsx
Normal file
142
frontend/src/components/layout/Sidebar.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import { useEffect } from "react";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { PanelLeftClose, PanelLeftOpen, X } from "lucide-react";
|
||||
import { Logo } from "@/components/layout/Logo";
|
||||
import { NAV_ITEMS } from "@/lib/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
interface NavListProps {
|
||||
collapsed: boolean;
|
||||
onNavigate?: () => void;
|
||||
}
|
||||
|
||||
function NavList({ collapsed, onNavigate }: NavListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<nav className="flex flex-1 flex-col gap-0.5 overflow-y-auto px-2.5 py-2">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const label = t(item.labelKey);
|
||||
if (item.disabled) {
|
||||
return (
|
||||
<span
|
||||
key={item.to}
|
||||
title={collapsed ? `${label} (${t("nav.comingSoon")})` : undefined}
|
||||
className={cn(
|
||||
"flex cursor-not-allowed items-center gap-3 rounded-lg px-2.5 py-2 text-sm text-text-muted",
|
||||
collapsed && "justify-center px-0"
|
||||
)}
|
||||
>
|
||||
<Icon size={18} className="shrink-0" />
|
||||
{!collapsed && (
|
||||
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
|
||||
<span className="truncate">{label}</span>
|
||||
<span className="shrink-0 rounded bg-surface-2 px-1 py-0.5 text-[10px] leading-none">
|
||||
{t("nav.comingSoon")}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.to === "/"}
|
||||
onClick={onNavigate}
|
||||
title={collapsed ? label : undefined}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
"flex items-center gap-3 rounded-lg px-2.5 py-2 text-sm font-medium text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",
|
||||
collapsed && "justify-center px-0",
|
||||
isActive && "bg-surface-2 text-text-primary"
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon size={18} className="shrink-0" />
|
||||
{!collapsed && <span className="truncate">{label}</span>}
|
||||
</NavLink>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
interface SidebarProps {
|
||||
collapsed: boolean;
|
||||
onToggleCollapsed: () => void;
|
||||
mobileOpen: boolean;
|
||||
onCloseMobile: () => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ collapsed, onToggleCollapsed, mobileOpen, onCloseMobile }: SidebarProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (!mobileOpen) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onCloseMobile();
|
||||
};
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => document.removeEventListener("keydown", onKeyDown);
|
||||
}, [mobileOpen, onCloseMobile]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Desktop: persistent rail, collapsible between icon-only and full width. */}
|
||||
<aside
|
||||
className={cn(
|
||||
"sticky top-0 hidden h-screen shrink-0 flex-col border-r border-border bg-surface-1 transition-[width] duration-150 lg:flex",
|
||||
collapsed ? "w-[72px]" : "w-56"
|
||||
)}
|
||||
>
|
||||
<div className={cn("flex items-center gap-2 px-4 py-4", collapsed && "justify-center px-0")}>
|
||||
<Logo size={24} />
|
||||
{!collapsed && <span className="text-lg font-semibold tracking-tight text-text-primary">Aurum</span>}
|
||||
</div>
|
||||
<NavList collapsed={collapsed} />
|
||||
<div className="border-t border-border p-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleCollapsed}
|
||||
title={collapsed ? t("sidebar.expandMenu") : t("sidebar.collapseMenu")}
|
||||
className={cn(
|
||||
"flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-sm text-text-muted hover:bg-surface-2 hover:text-text-primary",
|
||||
collapsed && "justify-center px-0"
|
||||
)}
|
||||
>
|
||||
{collapsed ? <PanelLeftOpen size={18} /> : <PanelLeftClose size={18} />}
|
||||
{!collapsed && <span>{t("sidebar.collapse")}</span>}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Mobile: off-canvas drawer over a backdrop. */}
|
||||
{mobileOpen && (
|
||||
<div className="fixed inset-0 z-50 lg:hidden">
|
||||
<div className="absolute inset-0 bg-black/40" onClick={onCloseMobile} />
|
||||
<aside className="absolute inset-y-0 left-0 flex w-64 flex-col bg-surface-1 shadow-xl">
|
||||
<div className="flex items-center justify-between gap-2 px-4 py-4">
|
||||
<span className="flex items-center gap-2 text-lg font-semibold tracking-tight text-text-primary">
|
||||
<Logo size={24} /> Aurum
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCloseMobile}
|
||||
aria-label={t("sidebar.closeMenu")}
|
||||
className="rounded-md p-1 text-text-muted hover:bg-surface-2"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<NavList collapsed={false} onNavigate={onCloseMobile} />
|
||||
</aside>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
28
frontend/src/components/layout/Topbar.tsx
Normal file
28
frontend/src/components/layout/Topbar.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { Menu } from "lucide-react";
|
||||
import { NAV_ITEMS } from "@/lib/navigation";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
interface TopbarProps {
|
||||
onOpenMobileNav: () => void;
|
||||
}
|
||||
|
||||
export function Topbar({ onOpenMobileNav }: TopbarProps) {
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
const activeItem = NAV_ITEMS.find((item) => (item.to === "/" ? location.pathname === "/" : location.pathname.startsWith(item.to)));
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-30 flex items-center gap-3 border-b border-border bg-surface-0/95 px-4 py-3.5 backdrop-blur sm:px-6 lg:px-8">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenMobileNav}
|
||||
aria-label={t("topbar.openMenu")}
|
||||
className="rounded-md p-1.5 text-text-secondary hover:bg-surface-2 lg:hidden"
|
||||
>
|
||||
<Menu size={20} />
|
||||
</button>
|
||||
<h1 className="text-lg font-semibold text-text-primary">{activeItem ? t(activeItem.labelKey) : "Aurum"}</h1>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
96
frontend/src/components/networth/AssetAllocationCard.tsx
Normal file
96
frontend/src/components/networth/AssetAllocationCard.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { NetWorthBreakdownItem } from "@/types";
|
||||
|
||||
interface AssetAllocationCardProps {
|
||||
breakdown: NetWorthBreakdownItem[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
// Breakdown items come from the backend with a machine-readable `key`
|
||||
// ("cash" or an AssetClass value) — translate the label locally instead of
|
||||
// showing the backend's (Russian-only) pre-rendered `name`.
|
||||
function breakdownLabelKey(key: string): TranslationKey {
|
||||
return `netWorth.assetClass.${key}` as TranslationKey;
|
||||
}
|
||||
|
||||
export function AssetAllocationCard({ breakdown, isLoading }: AssetAllocationCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const total = breakdown.reduce((sum, item) => sum + Number(item.amount), 0);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{t("netWorth.assetsTitlePrefix")} · {formatCurrency(total)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex h-2.5 w-full overflow-hidden rounded-full bg-surface-2">
|
||||
{breakdown.map((item) =>
|
||||
item.percent > 0 ? (
|
||||
<div
|
||||
key={item.key}
|
||||
style={{ width: `${item.percent}%`, backgroundColor: item.color }}
|
||||
className="h-full first:rounded-l-full last:rounded-r-full"
|
||||
/>
|
||||
) : null
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ul className="mt-4 flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-text-secondary">
|
||||
{breakdown.map((item) => (
|
||||
<li key={item.key} className="flex items-center gap-1.5">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: item.color }} />
|
||||
{t(breakdownLabelKey(item.key))} {item.percent.toFixed(0)}%
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<ul className="mt-4 divide-y divide-gridline border-t border-gridline">
|
||||
{breakdown.map((item) => {
|
||||
const Icon = getCategoryIcon(item.icon);
|
||||
return (
|
||||
<li key={item.key} className="flex items-center gap-3 py-2.5 first:pt-3">
|
||||
<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="min-w-0 flex-1 truncate text-sm text-text-primary">
|
||||
{t(breakdownLabelKey(item.key))}
|
||||
</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>
|
||||
<span className="w-9 shrink-0 text-right text-xs text-text-muted tabular-nums">
|
||||
{item.percent.toFixed(0)}%
|
||||
</span>
|
||||
</span>
|
||||
<span className="w-14 shrink-0 text-right text-xs text-text-muted tabular-nums sm:hidden">
|
||||
{item.percent.toFixed(0)}%
|
||||
</span>
|
||||
<span className="shrink-0 text-sm font-medium tabular-nums text-text-primary">
|
||||
{formatCurrency(item.amount)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
229
frontend/src/components/networth/AssetFormModal.tsx
Normal file
229
frontend/src/components/networth/AssetFormModal.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label, Select } from "@/components/ui/Input";
|
||||
import { useAddAssetValuation, useCreateAsset, useUpdateAsset } from "@/hooks/useAssets";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { Asset, AssetClass, CapitalRole, RiskLevel } from "@/types";
|
||||
|
||||
interface AssetFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
asset?: Asset | null;
|
||||
}
|
||||
|
||||
const ASSET_CLASSES: AssetClass[] = ["investments", "crypto", "real_estate", "vehicles", "precious_metals", "other"];
|
||||
const CAPITAL_ROLES: CapitalRole[] = ["income", "neutral", "drain"];
|
||||
const RISK_LEVELS: RiskLevel[] = ["low", "medium", "high"];
|
||||
|
||||
function todayIso() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
const EMPTY_FORM = {
|
||||
name: "",
|
||||
asset_class: "investments" as AssetClass,
|
||||
value: "",
|
||||
as_of_date: todayIso(),
|
||||
notes: "",
|
||||
capital_role: "neutral" as CapitalRole,
|
||||
monthly_cash_flow: "",
|
||||
risk_level: "medium" as RiskLevel,
|
||||
};
|
||||
|
||||
export function AssetFormModal({ open, onClose, asset }: AssetFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const createAsset = useCreateAsset();
|
||||
const updateAsset = useUpdateAsset();
|
||||
const addValuation = useAddAssetValuation();
|
||||
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (asset) {
|
||||
setForm({
|
||||
name: asset.name,
|
||||
asset_class: asset.asset_class,
|
||||
value: asset.current_value,
|
||||
as_of_date: todayIso(),
|
||||
notes: asset.notes ?? "",
|
||||
capital_role: asset.capital_role,
|
||||
monthly_cash_flow: asset.monthly_cash_flow ?? "",
|
||||
risk_level: asset.risk_level,
|
||||
});
|
||||
} else {
|
||||
setForm(EMPTY_FORM);
|
||||
}
|
||||
setError(null);
|
||||
}, [open, asset]);
|
||||
|
||||
const isSaving = createAsset.isPending || updateAsset.isPending || addValuation.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (asset) {
|
||||
await updateAsset.mutateAsync({
|
||||
id: asset.id,
|
||||
input: {
|
||||
name: form.name,
|
||||
asset_class: form.asset_class,
|
||||
notes: form.notes || null,
|
||||
capital_role: form.capital_role,
|
||||
monthly_cash_flow: form.monthly_cash_flow || null,
|
||||
risk_level: form.risk_level,
|
||||
},
|
||||
});
|
||||
if (form.value !== asset.current_value) {
|
||||
await addValuation.mutateAsync({ id: asset.id, input: { value: form.value, as_of_date: form.as_of_date } });
|
||||
}
|
||||
} else {
|
||||
await createAsset.mutateAsync({
|
||||
name: form.name,
|
||||
asset_class: form.asset_class,
|
||||
value: form.value,
|
||||
as_of_date: form.as_of_date,
|
||||
notes: form.notes || null,
|
||||
capital_role: form.capital_role,
|
||||
monthly_cash_flow: form.monthly_cash_flow || null,
|
||||
risk_level: form.risk_level,
|
||||
});
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("netWorth.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={asset ? t("netWorth.form.editTitle") : t("netWorth.form.newTitle")}>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="asset-name">{t("netWorth.form.nameLabel")}</Label>
|
||||
<Input
|
||||
id="asset-name"
|
||||
required
|
||||
placeholder={t("netWorth.form.namePlaceholder")}
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="asset-class">{t("netWorth.form.classLabel")}</Label>
|
||||
<Select
|
||||
id="asset-class"
|
||||
value={form.asset_class}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, asset_class: event.target.value as AssetClass }))}
|
||||
>
|
||||
{ASSET_CLASSES.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(`netWorth.assetClass.${value}` as TranslationKey)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="asset-value">
|
||||
{asset ? t("netWorth.form.currentValueLabel") : t("netWorth.form.valueLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
id="asset-value"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
required
|
||||
value={form.value}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, value: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="asset-date">{t("netWorth.form.dateLabel")}</Label>
|
||||
<Input
|
||||
id="asset-date"
|
||||
type="date"
|
||||
required
|
||||
value={form.as_of_date}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, as_of_date: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="asset-role">{t("netWorth.form.roleLabel")}</Label>
|
||||
<Select
|
||||
id="asset-role"
|
||||
value={form.capital_role}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, capital_role: event.target.value as CapitalRole }))}
|
||||
>
|
||||
{CAPITAL_ROLES.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(`netWorth.capitalRole.${value}` as TranslationKey)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
{t(`netWorth.capitalRoleFormHint.${form.capital_role}` as TranslationKey)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="asset-risk">{t("netWorth.form.riskLevelLabel")}</Label>
|
||||
<Select
|
||||
id="asset-risk"
|
||||
value={form.risk_level}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, risk_level: event.target.value as RiskLevel }))}
|
||||
>
|
||||
{RISK_LEVELS.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(`netWorth.riskLevel.${value}` as TranslationKey)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
{t(`netWorth.riskLevelFormHint.${form.risk_level}` as TranslationKey)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="asset-cash-flow">{t("netWorth.form.cashFlowLabel")}</Label>
|
||||
<Input
|
||||
id="asset-cash-flow"
|
||||
type="number"
|
||||
step="0.01"
|
||||
placeholder={t("netWorth.form.cashFlowPlaceholder")}
|
||||
value={form.monthly_cash_flow}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, monthly_cash_flow: event.target.value }))}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-muted">{t("netWorth.form.cashFlowHint")}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="asset-notes">{t("netWorth.form.notesLabel")}</Label>
|
||||
<Input
|
||||
id="asset-notes"
|
||||
value={form.notes}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, notes: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
101
frontend/src/components/networth/AssetsTable.tsx
Normal file
101
frontend/src/components/networth/AssetsTable.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency, formatTransactionDate } from "@/lib/format";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { Asset, CapitalRole } from "@/types";
|
||||
|
||||
const CLASS_ICONS: Record<Asset["asset_class"], string> = {
|
||||
investments: "trending-up",
|
||||
crypto: "bitcoin",
|
||||
real_estate: "building-2",
|
||||
vehicles: "car",
|
||||
precious_metals: "gem",
|
||||
other: "package",
|
||||
};
|
||||
|
||||
const ROLE_COLORS: Record<CapitalRole, string> = {
|
||||
income: "var(--success)",
|
||||
neutral: "var(--text-muted)",
|
||||
drain: "var(--danger)",
|
||||
};
|
||||
|
||||
interface AssetsTableProps {
|
||||
items: Asset[];
|
||||
onEdit: (asset: Asset) => void;
|
||||
onDelete: (asset: Asset) => void;
|
||||
}
|
||||
|
||||
export function AssetsTable({ items, onEdit, onDelete }: AssetsTableProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-10 text-center text-sm text-text-muted">{t("netWorth.assetsTable.empty")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((asset) => {
|
||||
const Icon = getCategoryIcon(CLASS_ICONS[asset.asset_class]);
|
||||
const roleColor = ROLE_COLORS[asset.capital_role];
|
||||
const cashFlow = asset.monthly_cash_flow !== null ? Number(asset.monthly_cash_flow) : null;
|
||||
const currentValue = Number(asset.current_value);
|
||||
// Annual ROI only makes sense for money coming in against what was
|
||||
// paid for the asset — same formula as RoiCalculatorCard.
|
||||
const annualRoiPercent = cashFlow !== null && cashFlow > 0 && currentValue > 0 ? (cashFlow * 12) / currentValue * 100 : null;
|
||||
|
||||
return (
|
||||
<li key={asset.id} className="flex items-center gap-3 py-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2">
|
||||
<Icon size={16} className="text-text-secondary" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-text-primary">{asset.name}</span>
|
||||
<span className="flex items-center gap-1 truncate text-xs text-text-muted">
|
||||
{t(`netWorth.assetClass.${asset.asset_class}` as TranslationKey)} ·{" "}
|
||||
{t("netWorth.assetsTable.asOf", { date: formatTransactionDate(asset.as_of_date) })}
|
||||
<span className="inline-flex items-center gap-1" style={{ color: roleColor }}>
|
||||
· <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: roleColor }} />
|
||||
{t(`netWorth.capitalRole.${asset.capital_role}` as TranslationKey)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-right">
|
||||
<span className="block text-sm font-medium tabular-nums text-text-primary">
|
||||
{formatCurrency(asset.current_value)}
|
||||
</span>
|
||||
{cashFlow !== null && cashFlow !== 0 && (
|
||||
<span
|
||||
className="block text-xs tabular-nums"
|
||||
style={{ color: cashFlow > 0 ? "var(--success)" : "var(--danger)" }}
|
||||
>
|
||||
{cashFlow > 0 ? "+" : ""}
|
||||
{formatCurrency(cashFlow)}
|
||||
{t("common.perMonth")}
|
||||
{annualRoiPercent !== null && ` · ${t("netWorth.assetsTable.annualRoi", { percent: annualRoiPercent.toFixed(1) })}`}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(asset)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(asset)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
62
frontend/src/components/networth/CapitalRoleSummaryCard.tsx
Normal file
62
frontend/src/components/networth/CapitalRoleSummaryCard.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { formatCurrency, pluralizeRu } from "@/lib/format";
|
||||
import { useTranslation, type Language, type TranslationKey } from "@/lib/i18n";
|
||||
import type { CapitalRoleSummary } from "@/types";
|
||||
|
||||
interface CapitalRoleSummaryCardProps {
|
||||
roles: CapitalRoleSummary[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
function assetsCountLabel(count: number, language: Language): string {
|
||||
if (language === "ru") return pluralizeRu(count, "актив", "актива", "активов");
|
||||
return count === 1 ? "asset" : "assets";
|
||||
}
|
||||
|
||||
export function CapitalRoleSummaryCard({ roles, isLoading }: CapitalRoleSummaryCardProps) {
|
||||
const { t, language } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("netWorth.capitalByType")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
{roles.map((role) => {
|
||||
const cashFlow = Number(role.monthly_cash_flow);
|
||||
return (
|
||||
<div key={role.role} className="rounded-lg border border-border p-3.5">
|
||||
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-muted">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: role.color }} />
|
||||
{t(`netWorth.capitalRole.${role.role}` as TranslationKey)}
|
||||
</p>
|
||||
<p className="mt-1.5 text-xl font-semibold tabular-nums text-text-primary">
|
||||
{formatCurrency(role.total_value)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
{role.count} {assetsCountLabel(role.count, language)} ·{" "}
|
||||
{t(`netWorth.capitalRoleHint.${role.role}` as TranslationKey)}
|
||||
</p>
|
||||
{cashFlow !== 0 && (
|
||||
<p
|
||||
className="mt-1.5 text-sm font-medium tabular-nums"
|
||||
style={{ color: cashFlow > 0 ? "var(--success)" : "var(--danger)" }}
|
||||
>
|
||||
{cashFlow > 0 ? "+" : ""}
|
||||
{formatCurrency(cashFlow)}
|
||||
{t("common.perMonth")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
133
frontend/src/components/networth/NetWorthChart.tsx
Normal file
133
frontend/src/components/networth/NetWorthChart.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { Area, AreaChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
import { ArrowDown, ArrowUp } from "lucide-react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { RangeSelector } from "@/components/layout/RangeSelector";
|
||||
import { formatCurrency, formatSignedCurrency, getIntlLocale } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { NetWorthRange, NetWorthSummary } from "@/types";
|
||||
|
||||
interface NetWorthChartProps {
|
||||
summary: NetWorthSummary | undefined;
|
||||
isLoading: boolean;
|
||||
range: NetWorthRange;
|
||||
onRangeChange: (range: NetWorthRange) => void;
|
||||
}
|
||||
|
||||
function formatAxisDate(iso: string): string {
|
||||
return new Intl.DateTimeFormat(getIntlLocale(), { month: "short", day: "numeric", year: "numeric" }).format(
|
||||
new Date(`${iso}T00:00:00`)
|
||||
);
|
||||
}
|
||||
|
||||
/** Jan-1 of every year strictly inside the range, so a multi-year chart gets
|
||||
* a year landmark on its axis instead of just two endpoint dates — lets you
|
||||
* place "5 years ago" without hovering pixel-by-pixel. Single-year ranges
|
||||
* return an empty array and the axis stays hidden, unchanged from before. */
|
||||
function computeYearTicks(dates: string[]): string[] {
|
||||
if (dates.length < 2) return [];
|
||||
const start = dates[0];
|
||||
const end = dates[dates.length - 1];
|
||||
const startYear = Number(start.slice(0, 4));
|
||||
const endYear = Number(end.slice(0, 4));
|
||||
if (startYear === endYear) return [];
|
||||
|
||||
const ticks: string[] = [];
|
||||
for (let year = startYear + 1; year <= endYear; year++) {
|
||||
const jan1 = `${year}-01-01`;
|
||||
if (jan1 >= start && jan1 <= end) ticks.push(jan1);
|
||||
}
|
||||
return ticks;
|
||||
}
|
||||
|
||||
function ChartTooltip({ active, payload }: { active?: boolean; payload?: Array<{ payload: { date: string; value: 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">{formatAxisDate(point.date)}</p>
|
||||
<p className="font-medium text-text-primary">{formatCurrency(point.value)}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function NetWorthChart({ summary, isLoading, range, onRangeChange }: NetWorthChartProps) {
|
||||
const { t } = useTranslation();
|
||||
const isPositive = summary ? Number(summary.change_amount) >= 0 : true;
|
||||
const trendColor = isPositive ? "var(--success)" : "var(--danger)";
|
||||
const chartData = summary?.series.map((point) => ({ date: point.date, value: Number(point.value) })) ?? [];
|
||||
const yearTicks = computeYearTicks(chartData.map((point) => point.date));
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="items-start">
|
||||
<div>
|
||||
<CardTitle>{t("nav.netWorth")}</CardTitle>
|
||||
<p className="mt-1.5 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
||||
{isLoading ? "…" : formatCurrency(summary?.current ?? 0)}
|
||||
</p>
|
||||
{summary && (
|
||||
<p
|
||||
className="mt-1 flex items-center gap-1 text-sm font-medium"
|
||||
style={{ color: trendColor }}
|
||||
>
|
||||
{isPositive ? <ArrowUp size={14} /> : <ArrowDown size={14} />}
|
||||
{formatSignedCurrency(summary.change_amount)}
|
||||
{summary.change_percent !== null && ` (${isPositive ? "+" : ""}${summary.change_percent.toFixed(1)}%)`}
|
||||
<span className="font-normal text-text-muted">{t("netWorth.periodSuffix")}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<RangeSelector value={range} onChange={onRangeChange} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-56 w-full sm:h-64">
|
||||
{isLoading || chartData.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-text-muted">
|
||||
{isLoading ? t("common.loading") : t("netWorth.noChartData")}
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={chartData} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
|
||||
<defs>
|
||||
<linearGradient id="netWorthFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={trendColor} stopOpacity={0.18} />
|
||||
<stop offset="100%" stopColor={trendColor} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<YAxis hide domain={["auto", "auto"]} />
|
||||
{yearTicks.length > 0 && (
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
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={{ stroke: "var(--gridline)", strokeWidth: 1 }} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke={trendColor}
|
||||
strokeWidth={2}
|
||||
fill="url(#netWorthFill)"
|
||||
isAnimationActive={false}
|
||||
activeDot={{ r: 4, strokeWidth: 0 }}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
{chartData.length > 1 && (
|
||||
<div className="mt-2 flex justify-between text-xs text-text-muted">
|
||||
<span>{formatAxisDate(chartData[0].date)}</span>
|
||||
<span>{formatAxisDate(chartData[chartData.length - 1].date)}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
62
frontend/src/components/networth/RiskAllocationCard.tsx
Normal file
62
frontend/src/components/networth/RiskAllocationCard.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import type { RiskLevelSummary } from "@/types";
|
||||
|
||||
interface RiskAllocationCardProps {
|
||||
riskLevels: RiskLevelSummary[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export function RiskAllocationCard({ riskLevels, isLoading }: RiskAllocationCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("netWorth.riskAllocationTitle")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
{riskLevels.map((tier) => (
|
||||
<div key={tier.risk_level} className="rounded-lg border border-border p-3.5">
|
||||
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-text-muted">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: tier.color }} />
|
||||
{t(`netWorth.riskLevel.${tier.risk_level}` as TranslationKey)}
|
||||
</p>
|
||||
<p className="mt-1.5 text-xl font-semibold tabular-nums text-text-primary">
|
||||
{formatCurrency(tier.total_value)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-text-muted">{tier.percent.toFixed(0)}% {t("netWorth.riskAllocationOfCapital")}</p>
|
||||
|
||||
{tier.items.length > 0 && (
|
||||
<ul className="mt-3 space-y-1.5 border-t border-gridline pt-3">
|
||||
{tier.items.map((item) => (
|
||||
<li key={item.key} className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-xs text-text-secondary">
|
||||
{item.key === "cash" ? t("netWorth.assetClass.cash") : item.name}
|
||||
</span>
|
||||
<span className="h-1 w-10 shrink-0 overflow-hidden rounded-full bg-surface-2">
|
||||
<span
|
||||
className="block h-full rounded-full"
|
||||
style={{ width: `${item.percent}%`, backgroundColor: tier.color }}
|
||||
/>
|
||||
</span>
|
||||
<span className="w-8 shrink-0 text-right text-[11px] tabular-nums text-text-muted">
|
||||
{item.percent.toFixed(0)}%
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
263
frontend/src/components/recurring/RecurringFormModal.tsx
Normal file
263
frontend/src/components/recurring/RecurringFormModal.tsx
Normal file
@@ -0,0 +1,263 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label, Select } from "@/components/ui/Input";
|
||||
import { useAccounts } from "@/hooks/useAccounts";
|
||||
import { useCategories } from "@/hooks/useCategories";
|
||||
import { useCreateRecurring, useUpdateRecurring } from "@/hooks/useRecurring";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { RecurringFrequency, RecurringTransaction, TransactionType } from "@/types";
|
||||
|
||||
interface RecurringFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
recurring?: RecurringTransaction | null;
|
||||
}
|
||||
|
||||
function todayIso() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
const EMPTY_FORM = {
|
||||
type: "expense" as TransactionType,
|
||||
account_id: "",
|
||||
category_id: "",
|
||||
transfer_account_id: "",
|
||||
amount: "",
|
||||
description: "",
|
||||
merchant: "",
|
||||
frequency: "monthly" as RecurringFrequency,
|
||||
anchor_date: todayIso(),
|
||||
};
|
||||
|
||||
export function RecurringFormModal({ open, onClose, recurring }: RecurringFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: accounts } = useAccounts();
|
||||
const { data: categories } = useCategories();
|
||||
const createRecurring = useCreateRecurring();
|
||||
const updateRecurring = useUpdateRecurring();
|
||||
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (recurring) {
|
||||
setForm({
|
||||
type: recurring.type,
|
||||
account_id: String(recurring.account_id),
|
||||
category_id: recurring.category_id ? String(recurring.category_id) : "",
|
||||
transfer_account_id: recurring.transfer_account_id ? String(recurring.transfer_account_id) : "",
|
||||
amount: recurring.amount,
|
||||
description: recurring.description,
|
||||
merchant: recurring.merchant ?? "",
|
||||
frequency: recurring.frequency,
|
||||
anchor_date: recurring.anchor_date,
|
||||
});
|
||||
} else {
|
||||
setForm({ ...EMPTY_FORM, account_id: accounts?.[0] ? String(accounts[0].id) : "" });
|
||||
}
|
||||
setError(null);
|
||||
}, [open, recurring, accounts]);
|
||||
|
||||
const relevantCategories = (categories ?? []).filter((category) =>
|
||||
form.type === "income" ? category.kind === "income" : category.kind === "expense"
|
||||
);
|
||||
|
||||
const isSaving = createRecurring.isPending || updateRecurring.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!form.account_id) {
|
||||
setError(t("transactions.form.errorSelectAccount"));
|
||||
return;
|
||||
}
|
||||
if (form.type === "transfer" && !form.transfer_account_id) {
|
||||
setError(t("transactions.form.errorSelectDestination"));
|
||||
return;
|
||||
}
|
||||
if (form.type === "transfer" && form.transfer_account_id === form.account_id) {
|
||||
setError(t("transactions.form.errorSameAccount"));
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
type: form.type,
|
||||
account_id: Number(form.account_id),
|
||||
category_id: form.type === "transfer" ? null : form.category_id ? Number(form.category_id) : null,
|
||||
transfer_account_id: form.type === "transfer" ? Number(form.transfer_account_id) : null,
|
||||
amount: form.amount,
|
||||
description: form.description,
|
||||
merchant: form.merchant || null,
|
||||
frequency: form.frequency,
|
||||
anchor_date: form.anchor_date,
|
||||
};
|
||||
|
||||
try {
|
||||
if (recurring) {
|
||||
await updateRecurring.mutateAsync({ id: recurring.id, input: payload });
|
||||
} else {
|
||||
await createRecurring.mutateAsync(payload);
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("recurring.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={recurring ? t("recurring.form.editTitle") : t("recurring.form.newTitle")}
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="recurring-type">{t("transactions.form.typeLabel")}</Label>
|
||||
<Select
|
||||
id="recurring-type"
|
||||
value={form.type}
|
||||
onChange={(event) =>
|
||||
setForm((prev) => ({ ...prev, type: event.target.value as TransactionType, category_id: "" }))
|
||||
}
|
||||
>
|
||||
<option value="expense">{t("transactions.form.typeExpense")}</option>
|
||||
<option value="income">{t("transactions.form.typeIncome")}</option>
|
||||
<option value="transfer">{t("transactions.form.typeTransfer")}</option>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="recurring-frequency">{t("recurring.form.frequencyLabel")}</Label>
|
||||
<Select
|
||||
id="recurring-frequency"
|
||||
value={form.frequency}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, frequency: event.target.value as RecurringFrequency }))}
|
||||
>
|
||||
<option value="weekly">{t("recurring.frequency.weekly")}</option>
|
||||
<option value="monthly">{t("recurring.frequency.monthly")}</option>
|
||||
<option value="yearly">{t("recurring.frequency.yearly")}</option>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="recurring-amount">{t("transactions.form.amountLabel")}</Label>
|
||||
<Input
|
||||
id="recurring-amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required
|
||||
value={form.amount}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, amount: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="recurring-anchor-date">{t("recurring.form.anchorDateLabel")}</Label>
|
||||
<Input
|
||||
id="recurring-anchor-date"
|
||||
type="date"
|
||||
required
|
||||
value={form.anchor_date}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, anchor_date: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="recurring-description">{t("transactions.form.descriptionLabel")}</Label>
|
||||
<Input
|
||||
id="recurring-description"
|
||||
required
|
||||
placeholder={t("transactions.form.descriptionPlaceholder")}
|
||||
value={form.description}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, description: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="recurring-account">{t("transactions.form.accountLabel")}</Label>
|
||||
<Select
|
||||
id="recurring-account"
|
||||
required
|
||||
value={form.account_id}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, account_id: event.target.value }))}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{t("transactions.form.selectAccount")}
|
||||
</option>
|
||||
{accounts?.map((account) => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{form.type === "transfer" ? (
|
||||
<div>
|
||||
<Label htmlFor="recurring-transfer-account">{t("transactions.form.transferAccountLabel")}</Label>
|
||||
<Select
|
||||
id="recurring-transfer-account"
|
||||
required
|
||||
value={form.transfer_account_id}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, transfer_account_id: event.target.value }))}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{t("transactions.form.selectAccount")}
|
||||
</option>
|
||||
{accounts
|
||||
?.filter((account) => String(account.id) !== form.account_id)
|
||||
.map((account) => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Label htmlFor="recurring-category">{t("transactions.form.categoryLabel")}</Label>
|
||||
<Select
|
||||
id="recurring-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}>
|
||||
{translateCategoryName(category.name)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label htmlFor="recurring-merchant">{t("transactions.form.merchantLabel")}</Label>
|
||||
<Input
|
||||
id="recurring-merchant"
|
||||
value={form.merchant}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, merchant: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
103
frontend/src/components/recurring/RecurringList.tsx
Normal file
103
frontend/src/components/recurring/RecurringList.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import { ArrowLeftRight, CalendarCheck, Pencil, Trash2 } from "lucide-react";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency, getIntlLocale } from "@/lib/format";
|
||||
import { useTranslation, type TranslationKey } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { RecurringTransaction } from "@/types";
|
||||
|
||||
interface RecurringListProps {
|
||||
items: RecurringTransaction[];
|
||||
onPost: (item: RecurringTransaction) => void;
|
||||
onEdit: (item: RecurringTransaction) => void;
|
||||
onDelete: (item: RecurringTransaction) => void;
|
||||
isPosting: boolean;
|
||||
}
|
||||
|
||||
function formatDueDate(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(getIntlLocale(), { day: "numeric", month: "short", year: "numeric" }).format(
|
||||
new Date(`${isoDate}T00:00:00`)
|
||||
);
|
||||
}
|
||||
|
||||
export function RecurringList({ items, onPost, onEdit, onDelete, isPosting }: RecurringListProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-10 text-center text-sm text-text-muted">{t("recurring.empty")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((item) => {
|
||||
const isTransfer = item.type === "transfer";
|
||||
const isExpense = item.type === "expense";
|
||||
const Icon = isTransfer ? ArrowLeftRight : getCategoryIcon(item.category_icon);
|
||||
const color = isTransfer ? "var(--text-muted)" : item.category_color ?? "var(--text-muted)";
|
||||
|
||||
return (
|
||||
<li key={item.id} className="flex items-center gap-3 py-3">
|
||||
<span
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full"
|
||||
style={{ backgroundColor: color.startsWith("#") ? `${color}26` : "var(--surface-2)" }}
|
||||
>
|
||||
<Icon size={16} style={{ color }} />
|
||||
</span>
|
||||
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-text-primary">{item.description}</span>
|
||||
<span className="flex flex-wrap items-center gap-x-1 truncate text-xs text-text-muted">
|
||||
<span>{t(`recurring.frequency.${item.frequency}` as TranslationKey)}</span>
|
||||
{item.category_name && <span>· {translateCategoryName(item.category_name)}</span>}
|
||||
<span style={{ color: item.is_due ? "var(--danger)" : "var(--text-muted)" }}>
|
||||
·{" "}
|
||||
{item.is_due
|
||||
? item.days_until_due < 0
|
||||
? t("recurring.overdueDays", { days: Math.abs(item.days_until_due) })
|
||||
: t("recurring.dueToday")
|
||||
: t("recurring.dueInDays", { days: item.days_until_due, date: formatDueDate(item.next_due_date) })}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span
|
||||
className={`shrink-0 text-sm font-medium tabular-nums ${
|
||||
isTransfer ? "text-text-muted" : isExpense ? "text-text-primary" : "text-success"
|
||||
}`}
|
||||
>
|
||||
{isTransfer ? "" : isExpense ? "-" : "+"}
|
||||
{formatCurrency(item.amount)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("recurring.postLabel")}
|
||||
disabled={isPosting}
|
||||
onClick={() => onPost(item)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-success disabled:opacity-50"
|
||||
>
|
||||
<CalendarCheck size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(item)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(item)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
80
frontend/src/components/reports/CategoryRankingCard.tsx
Normal file
80
frontend/src/components/reports/CategoryRankingCard.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
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 { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { CategoryRankingItem } from "@/types";
|
||||
|
||||
interface CategoryRankingCardProps {
|
||||
items: CategoryRankingItem[];
|
||||
isLoading: boolean;
|
||||
selectedCategoryId: number | null;
|
||||
onSelectCategory: (categoryId: number) => void;
|
||||
}
|
||||
|
||||
/** Ranks every expense category by total spent over the currently selected
|
||||
* period — unlike the Dashboard breakdown (locked to one month) or the
|
||||
* 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. */
|
||||
export function CategoryRankingCard({ items, isLoading, selectedCategoryId, onSelectCategory }: CategoryRankingCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("reports.categoryRankingTitle")}</CardTitle>
|
||||
</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.noRankingData")}</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((item, index) => {
|
||||
const Icon = getCategoryIcon(item.icon);
|
||||
const isSelected = item.category_id === selectedCategoryId;
|
||||
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 ${
|
||||
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` }}
|
||||
>
|
||||
<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>
|
||||
<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 pr-1 text-sm font-medium tabular-nums text-text-primary">
|
||||
{formatCurrency(item.amount)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
114
frontend/src/components/reports/CategorySpendingChart.tsx
Normal file
114
frontend/src/components/reports/CategorySpendingChart.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
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 { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { CategorySpendingReport } from "@/types";
|
||||
|
||||
interface CategorySpendingChartProps {
|
||||
report: CategorySpendingReport | 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>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
87
frontend/src/components/roi/RoiCalculatorCard.tsx
Normal file
87
frontend/src/components/roi/RoiCalculatorCard.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { Input, Label } from "@/components/ui/Input";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
interface RoiCalculatorCardProps {
|
||||
investment: string;
|
||||
onInvestmentChange: (value: string) => void;
|
||||
monthlyIncome: string;
|
||||
onMonthlyIncomeChange: (value: string) => void;
|
||||
annualRoiPercent: number | null;
|
||||
paybackYears: number | null;
|
||||
}
|
||||
|
||||
/** Quick "is this a good deal" check — purchase price + expected monthly
|
||||
* income in, annual return % and payback period out. Purely a scratchpad:
|
||||
* not tied to any Asset, doesn't persist, doesn't read anything else you've
|
||||
* tracked in the app — only these two numbers. Same formula AssetsTable
|
||||
* already shows inline for assets that have monthly_cash_flow set, just
|
||||
* usable before you've committed to adding one. The multi-year, compound-
|
||||
* interest projection built from these same numbers lives in
|
||||
* RoiProjectionCard, rendered alongside this one on RoiPage. */
|
||||
export function RoiCalculatorCard({
|
||||
investment,
|
||||
onInvestmentChange,
|
||||
monthlyIncome,
|
||||
onMonthlyIncomeChange,
|
||||
annualRoiPercent,
|
||||
paybackYears,
|
||||
}: RoiCalculatorCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("roi.calculator.title")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="roi-investment">{t("roi.calculator.investmentLabel")}</Label>
|
||||
<Input
|
||||
id="roi-investment"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
placeholder="100000"
|
||||
value={investment}
|
||||
onChange={(event) => onInvestmentChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="roi-income">{t("roi.calculator.monthlyIncomeLabel")}</Label>
|
||||
<Input
|
||||
id="roi-income"
|
||||
type="number"
|
||||
step="0.01"
|
||||
placeholder="830"
|
||||
value={monthlyIncome}
|
||||
onChange={(event) => onMonthlyIncomeChange(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{annualRoiPercent === null ? (
|
||||
<p className="text-xs text-text-muted">{t("roi.calculator.hint")}</p>
|
||||
) : (
|
||||
<div className="rounded-lg bg-surface-2 p-3.5">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-text-muted">
|
||||
{t("roi.calculator.annualRoiLabel")}
|
||||
</p>
|
||||
<p
|
||||
className="mt-1 text-2xl font-semibold tabular-nums"
|
||||
style={{ color: annualRoiPercent >= 0 ? "var(--success)" : "var(--danger)" }}
|
||||
>
|
||||
{annualRoiPercent.toFixed(1)}%
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
{paybackYears !== null
|
||||
? t("roi.calculator.payback", { years: paybackYears.toFixed(1) })
|
||||
: t("roi.calculator.noPayback")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
162
frontend/src/components/roi/RoiProjectionCard.tsx
Normal file
162
frontend/src/components/roi/RoiProjectionCard.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis } from "recharts";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
interface RoiProjectionCardProps {
|
||||
investmentAmount: number;
|
||||
annualIncome: number;
|
||||
annualRoiPercent: number;
|
||||
}
|
||||
|
||||
const CHART_MAX_YEARS = 30;
|
||||
const CHART_TICKS = [0, 5, 10, 15, 20, 25, 30];
|
||||
const TABLE_YEARS = [1, 5, 10, 20, 30];
|
||||
|
||||
interface ChartPoint {
|
||||
year: number;
|
||||
compound: number;
|
||||
simple: number;
|
||||
}
|
||||
|
||||
function ChartTooltip({
|
||||
active,
|
||||
payload,
|
||||
compoundLabel,
|
||||
simpleLabel,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ payload: ChartPoint }>;
|
||||
compoundLabel: string;
|
||||
simpleLabel: string;
|
||||
}) {
|
||||
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">{point.year}</p>
|
||||
<p className="font-medium" style={{ color: "var(--series-1)" }}>
|
||||
{compoundLabel}: {formatCurrency(point.compound)}
|
||||
</p>
|
||||
<p className="text-text-muted">
|
||||
{simpleLabel}: {formatCurrency(point.simple)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everything here is derived only from the two numbers typed into
|
||||
* RoiCalculatorCard (investment amount, monthly income) — no data from
|
||||
* Asset/AssetValuation or anywhere else in the app. Two scenarios,
|
||||
* compounded annually from the same starting point:
|
||||
* compound(year) = investment × (1 + annualRoiPercent)^year — the whole
|
||||
* annual return (rent/dividends) is assumed reinvested back into the
|
||||
* same investment every year, so next year's return is earned on a
|
||||
* larger base too.
|
||||
* simple(year) = investment + annualIncome × year — the investment
|
||||
* itself never grows, income is just set aside in cash each year.
|
||||
* The gap between the two lines *is* what compounding is worth. */
|
||||
export function RoiProjectionCard({ investmentAmount, annualIncome, annualRoiPercent }: RoiProjectionCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const rate = annualRoiPercent / 100;
|
||||
const compoundLabel = t("roi.calculator.chartCompoundLabel");
|
||||
const simpleLabel = t("roi.calculator.chartSimpleLabel");
|
||||
|
||||
const chartData: ChartPoint[] = Array.from({ length: CHART_MAX_YEARS + 1 }, (_, year) => ({
|
||||
year,
|
||||
compound: investmentAmount * Math.pow(1 + rate, year),
|
||||
simple: investmentAmount + annualIncome * year,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("roi.calculator.projectionTitle")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<p className="text-xs text-text-muted">{t("roi.calculator.projectionHint", { percent: annualRoiPercent.toFixed(1) })}</p>
|
||||
|
||||
<div className="h-56 w-full sm:h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={chartData} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
|
||||
<XAxis
|
||||
dataKey="year"
|
||||
type="number"
|
||||
domain={[0, CHART_MAX_YEARS]}
|
||||
ticks={CHART_TICKS}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "var(--text-muted)", fontSize: 11 }}
|
||||
/>
|
||||
<Tooltip content={<ChartTooltip compoundLabel={compoundLabel} simpleLabel={simpleLabel} />} cursor={{ stroke: "var(--gridline)", strokeWidth: 1 }} />
|
||||
<Legend
|
||||
verticalAlign="top"
|
||||
height={24}
|
||||
formatter={(value) => (value === "compound" ? compoundLabel : simpleLabel)}
|
||||
wrapperStyle={{ fontSize: 12, color: "var(--text-muted)" }}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="compound"
|
||||
stroke="var(--series-1)"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="simple"
|
||||
stroke="var(--text-muted)"
|
||||
strokeWidth={2}
|
||||
strokeDasharray="4 4"
|
||||
dot={false}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-text-muted">{t("roi.calculator.tableTitle")}</p>
|
||||
<ul className="mt-2 divide-y divide-gridline">
|
||||
<li className="flex items-center gap-3 py-2 text-xs font-medium text-text-muted">
|
||||
<span className="flex-1" />
|
||||
<span className="w-28 shrink-0 text-right">{t("roi.calculator.colCompound")}</span>
|
||||
<span className="hidden w-28 shrink-0 text-right sm:block">{t("roi.calculator.colSimple")}</span>
|
||||
<span className="w-24 shrink-0 text-right">{t("roi.calculator.colDifference")}</span>
|
||||
</li>
|
||||
{TABLE_YEARS.map((year) => {
|
||||
const compound = investmentAmount * Math.pow(1 + rate, year);
|
||||
const simple = investmentAmount + annualIncome * year;
|
||||
// Rounded to the cent before comparing sign — compound and simple
|
||||
// agree exactly in year 1, but Math.pow's floating-point error
|
||||
// can leave a sub-cent residue. `|| 0` also normalizes -0 (which
|
||||
// is >= 0 but still formats as "-$0") to a plain positive 0.
|
||||
const difference = Math.round((compound - simple) * 100) / 100 || 0;
|
||||
return (
|
||||
<li key={year} className="flex items-center gap-3 py-2.5">
|
||||
<span className="flex-1 text-sm text-text-secondary">
|
||||
{year === 1 ? t("roi.calculator.yearOne") : t("roi.calculator.yearN", { years: year })}
|
||||
</span>
|
||||
<span className="w-28 shrink-0 text-right text-sm font-medium tabular-nums text-text-primary">
|
||||
{formatCurrency(compound)}
|
||||
</span>
|
||||
<span className="hidden w-28 shrink-0 text-right text-sm tabular-nums text-text-muted sm:block">
|
||||
{formatCurrency(simple)}
|
||||
</span>
|
||||
<span
|
||||
className="w-24 shrink-0 text-right text-sm tabular-nums"
|
||||
style={{ color: difference >= 0 ? "var(--success)" : "var(--danger)" }}
|
||||
>
|
||||
{difference >= 0 ? "+" : ""}
|
||||
{formatCurrency(difference)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
107
frontend/src/components/settings/AlertThresholdsCard.tsx
Normal file
107
frontend/src/components/settings/AlertThresholdsCard.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { Input, Label } from "@/components/ui/Input";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { useAppSettings, useUpdateAppSettings } from "@/hooks/useSettings";
|
||||
|
||||
const MIN_MONTHS = 1;
|
||||
const MAX_MONTHS = 24;
|
||||
const MIN_PERCENT = 1;
|
||||
const MAX_PERCENT = 100;
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
export function AlertThresholdsCard() {
|
||||
const { t } = useTranslation();
|
||||
const { data: settings } = useAppSettings();
|
||||
const updateSettings = useUpdateAppSettings();
|
||||
|
||||
const [cashFlowMonths, setCashFlowMonths] = useState("");
|
||||
const [netWorthMonths, setNetWorthMonths] = useState("");
|
||||
const [riskyPercent, setRiskyPercent] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!settings) return;
|
||||
setCashFlowMonths(String(settings.negative_cash_flow_threshold_months));
|
||||
setNetWorthMonths(String(settings.net_worth_decline_threshold_months));
|
||||
setRiskyPercent(String(settings.risky_allocation_threshold_percent));
|
||||
}, [settings]);
|
||||
|
||||
function commitCashFlowMonths() {
|
||||
const value = clamp(Number(cashFlowMonths) || MIN_MONTHS, MIN_MONTHS, MAX_MONTHS);
|
||||
setCashFlowMonths(String(value));
|
||||
if (settings && value !== settings.negative_cash_flow_threshold_months) {
|
||||
updateSettings.mutate({ negative_cash_flow_threshold_months: value });
|
||||
}
|
||||
}
|
||||
|
||||
function commitNetWorthMonths() {
|
||||
const value = clamp(Number(netWorthMonths) || MIN_MONTHS, MIN_MONTHS, MAX_MONTHS);
|
||||
setNetWorthMonths(String(value));
|
||||
if (settings && value !== settings.net_worth_decline_threshold_months) {
|
||||
updateSettings.mutate({ net_worth_decline_threshold_months: value });
|
||||
}
|
||||
}
|
||||
|
||||
function commitRiskyPercent() {
|
||||
const value = clamp(Number(riskyPercent) || MIN_PERCENT, MIN_PERCENT, MAX_PERCENT);
|
||||
setRiskyPercent(String(value));
|
||||
if (settings && value !== settings.risky_allocation_threshold_percent) {
|
||||
updateSettings.mutate({ risky_allocation_threshold_percent: value });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("settings.alertsTitle")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<Label htmlFor="cash-flow-threshold">{t("settings.negativeCashFlowThresholdLabel")}</Label>
|
||||
<Input
|
||||
id="cash-flow-threshold"
|
||||
type="number"
|
||||
min={MIN_MONTHS}
|
||||
max={MAX_MONTHS}
|
||||
step={1}
|
||||
value={cashFlowMonths}
|
||||
onChange={(event) => setCashFlowMonths(event.target.value)}
|
||||
onBlur={commitCashFlowMonths}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="net-worth-threshold">{t("settings.netWorthDeclineThresholdLabel")}</Label>
|
||||
<Input
|
||||
id="net-worth-threshold"
|
||||
type="number"
|
||||
min={MIN_MONTHS}
|
||||
max={MAX_MONTHS}
|
||||
step={1}
|
||||
value={netWorthMonths}
|
||||
onChange={(event) => setNetWorthMonths(event.target.value)}
|
||||
onBlur={commitNetWorthMonths}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="risky-allocation-threshold">{t("settings.riskyAllocationThresholdLabel")}</Label>
|
||||
<Input
|
||||
id="risky-allocation-threshold"
|
||||
type="number"
|
||||
min={MIN_PERCENT}
|
||||
max={MAX_PERCENT}
|
||||
step={1}
|
||||
value={riskyPercent}
|
||||
onChange={(event) => setRiskyPercent(event.target.value)}
|
||||
onBlur={commitRiskyPercent}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">{t("settings.alertsHint")}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
100
frontend/src/components/settings/BackupCard.tsx
Normal file
100
frontend/src/components/settings/BackupCard.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Download, Upload } from "lucide-react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { exportBackup, importBackup } from "@/api/backup";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
export function BackupCard() {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [message, setMessage] = useState<{ kind: "success" | "error"; text: string } | null>(null);
|
||||
|
||||
async function handleExport() {
|
||||
setIsExporting(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await exportBackup();
|
||||
setMessage({ kind: "success", text: t("backup.exportSuccess") });
|
||||
} catch {
|
||||
// Never surface error.message here — it's the raw backend/HTTP
|
||||
// response text (English, unlocalized), unlike every other error
|
||||
// path in the app, which always shows a translated fallback.
|
||||
setMessage({ kind: "error", text: t("backup.exportError") });
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleImportClick() {
|
||||
fileInputRef.current?.click();
|
||||
}
|
||||
|
||||
async function handleFileSelected(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
|
||||
const confirmed = window.confirm(t("backup.confirmImport", { filename: file.name }));
|
||||
if (!confirmed) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await importBackup(file);
|
||||
await queryClient.invalidateQueries();
|
||||
setMessage({ kind: "success", text: t("backup.importSuccess") });
|
||||
} catch (error) {
|
||||
// importBackup throws a plain Error with an already-translated message
|
||||
// for a malformed file (t("backup.invalidFile")) — relay that one
|
||||
// as-is. A failed API call throws ApiError with the raw backend detail
|
||||
// text (English, unlocalized) instead — never show that, fall back to
|
||||
// the generic translated message like every other error path in the app.
|
||||
const text = error instanceof ApiError ? t("backup.importError") : error instanceof Error ? error.message : t("backup.importError");
|
||||
setMessage({ kind: "error", text });
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("backup.title")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-text-secondary">{t("backup.description")}</p>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Button onClick={handleExport} disabled={isExporting} className="sm:w-auto">
|
||||
<Download size={16} />
|
||||
{isExporting ? t("backup.exporting") : t("backup.exportButton")}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleImportClick} disabled={isImporting} className="sm:w-auto">
|
||||
<Upload size={16} />
|
||||
{isImporting ? t("backup.importing") : t("backup.importButton")}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
onChange={handleFileSelected}
|
||||
className="hidden"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<p className={`text-sm ${message.kind === "error" ? "text-danger" : "text-success"}`}>{message.text}</p>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-text-muted">{t("backup.footerWarning")}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
34
frontend/src/components/settings/CurrencyCard.tsx
Normal file
34
frontend/src/components/settings/CurrencyCard.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { Select } from "@/components/ui/Input";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { CURRENCIES, getCurrencyLabel } from "@/lib/currency";
|
||||
import { useAppSettings, useUpdateAppSettings } from "@/hooks/useSettings";
|
||||
|
||||
export function CurrencyCard() {
|
||||
const { t, language } = useTranslation();
|
||||
const { data: settings, isLoading } = useAppSettings();
|
||||
const updateSettings = useUpdateAppSettings();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("settings.currency")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Select
|
||||
value={settings?.currency ?? ""}
|
||||
disabled={isLoading || updateSettings.isPending}
|
||||
onChange={(event) => updateSettings.mutate({ currency: event.target.value })}
|
||||
className="max-w-xs"
|
||||
>
|
||||
{CURRENCIES.map((currency) => (
|
||||
<option key={currency.code} value={currency.code}>
|
||||
{getCurrencyLabel(currency.code, language)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<p className="text-xs text-text-muted">{t("settings.currencyHint")}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
23
frontend/src/components/settings/LanguageCard.tsx
Normal file
23
frontend/src/components/settings/LanguageCard.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { PillSelector } from "@/components/layout/PillSelector";
|
||||
import { useTranslation, type Language } from "@/lib/i18n";
|
||||
|
||||
export function LanguageCard() {
|
||||
const { t, language, setLanguage } = useTranslation();
|
||||
|
||||
const options: Array<{ value: Language; label: string }> = [
|
||||
{ value: "ru", label: t("settings.languageRussian") },
|
||||
{ value: "en", label: t("settings.languageEnglish") },
|
||||
];
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("settings.language")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<PillSelector options={options} value={language} onChange={setLanguage} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
249
frontend/src/components/transactions/TransactionFormModal.tsx
Normal file
249
frontend/src/components/transactions/TransactionFormModal.tsx
Normal file
@@ -0,0 +1,249 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dialog } from "@/components/ui/Dialog";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input, Label, Select } from "@/components/ui/Input";
|
||||
import { useAccounts } from "@/hooks/useAccounts";
|
||||
import { useCategories } from "@/hooks/useCategories";
|
||||
import { useCreateTransaction, useUpdateTransaction } from "@/hooks/useTransactions";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { Transaction, TransactionInput, TransactionType } from "@/types";
|
||||
|
||||
interface TransactionFormModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
transaction?: Transaction | null;
|
||||
}
|
||||
|
||||
function todayIso() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
const EMPTY_FORM = {
|
||||
type: "expense" as TransactionType,
|
||||
account_id: "",
|
||||
category_id: "",
|
||||
transfer_account_id: "",
|
||||
amount: "",
|
||||
description: "",
|
||||
merchant: "",
|
||||
notes: "",
|
||||
date: todayIso(),
|
||||
};
|
||||
|
||||
export function TransactionFormModal({ open, onClose, transaction }: TransactionFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: accounts } = useAccounts();
|
||||
const { data: categories } = useCategories();
|
||||
const createTransaction = useCreateTransaction();
|
||||
const updateTransaction = useUpdateTransaction();
|
||||
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (transaction) {
|
||||
setForm({
|
||||
type: transaction.type,
|
||||
account_id: String(transaction.account_id),
|
||||
category_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,
|
||||
merchant: transaction.merchant ?? "",
|
||||
notes: transaction.notes ?? "",
|
||||
date: transaction.date,
|
||||
});
|
||||
} else {
|
||||
setForm({ ...EMPTY_FORM, account_id: accounts?.[0] ? String(accounts[0].id) : "" });
|
||||
}
|
||||
setError(null);
|
||||
}, [open, transaction, accounts]);
|
||||
|
||||
const relevantCategories = (categories ?? []).filter((category) =>
|
||||
form.type === "income" ? category.kind === "income" : category.kind === "expense"
|
||||
);
|
||||
|
||||
const isSaving = createTransaction.isPending || updateTransaction.isPending;
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!form.account_id) {
|
||||
setError(t("transactions.form.errorSelectAccount"));
|
||||
return;
|
||||
}
|
||||
if (form.type === "transfer" && !form.transfer_account_id) {
|
||||
setError(t("transactions.form.errorSelectDestination"));
|
||||
return;
|
||||
}
|
||||
if (form.type === "transfer" && form.transfer_account_id === form.account_id) {
|
||||
setError(t("transactions.form.errorSameAccount"));
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: TransactionInput = {
|
||||
type: form.type,
|
||||
account_id: Number(form.account_id),
|
||||
category_id: form.type === "transfer" ? null : form.category_id ? Number(form.category_id) : null,
|
||||
transfer_account_id: form.type === "transfer" ? Number(form.transfer_account_id) : null,
|
||||
amount: form.amount,
|
||||
description: form.description,
|
||||
merchant: form.merchant || null,
|
||||
notes: form.notes || null,
|
||||
date: form.date,
|
||||
};
|
||||
|
||||
try {
|
||||
if (transaction) {
|
||||
await updateTransaction.mutateAsync({ id: transaction.id, input: payload });
|
||||
} else {
|
||||
await createTransaction.mutateAsync(payload);
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
setError(t("transactions.form.saveError"));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={transaction ? t("transactions.form.editTitle") : t("transactions.form.newTitle")}
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="type">{t("transactions.form.typeLabel")}</Label>
|
||||
<Select
|
||||
id="type"
|
||||
value={form.type}
|
||||
onChange={(event) =>
|
||||
setForm((prev) => ({ ...prev, type: event.target.value as TransactionType, category_id: "" }))
|
||||
}
|
||||
>
|
||||
<option value="expense">{t("transactions.form.typeExpense")}</option>
|
||||
<option value="income">{t("transactions.form.typeIncome")}</option>
|
||||
<option value="transfer">{t("transactions.form.typeTransfer")}</option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="amount">{t("transactions.form.amountLabel")}</Label>
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required
|
||||
value={form.amount}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, amount: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="date">{t("transactions.form.dateLabel")}</Label>
|
||||
<Input
|
||||
id="date"
|
||||
type="date"
|
||||
required
|
||||
value={form.date}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, date: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="description">{t("transactions.form.descriptionLabel")}</Label>
|
||||
<Input
|
||||
id="description"
|
||||
required
|
||||
placeholder={t("transactions.form.descriptionPlaceholder")}
|
||||
value={form.description}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, description: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="account">{t("transactions.form.accountLabel")}</Label>
|
||||
<Select
|
||||
id="account"
|
||||
required
|
||||
value={form.account_id}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, account_id: event.target.value }))}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{t("transactions.form.selectAccount")}
|
||||
</option>
|
||||
{accounts?.map((account) => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{form.type === "transfer" ? (
|
||||
<div>
|
||||
<Label htmlFor="transfer_account">{t("transactions.form.transferAccountLabel")}</Label>
|
||||
<Select
|
||||
id="transfer_account"
|
||||
required
|
||||
value={form.transfer_account_id}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, transfer_account_id: event.target.value }))}
|
||||
>
|
||||
<option value="" disabled>
|
||||
{t("transactions.form.selectAccount")}
|
||||
</option>
|
||||
{accounts
|
||||
?.filter((account) => String(account.id) !== form.account_id)
|
||||
.map((account) => (
|
||||
<option key={account.id} value={account.id}>
|
||||
{account.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<Label htmlFor="category">{t("transactions.form.categoryLabel")}</Label>
|
||||
<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}>
|
||||
{translateCategoryName(category.name)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label htmlFor="merchant">{t("transactions.form.merchantLabel")}</Label>
|
||||
<Input
|
||||
id="merchant"
|
||||
value={form.merchant}
|
||||
onChange={(event) => setForm((prev) => ({ ...prev, merchant: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSaving}>
|
||||
{isSaving ? t("common.saving") : t("common.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
79
frontend/src/components/transactions/TransactionsTable.tsx
Normal file
79
frontend/src/components/transactions/TransactionsTable.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import { ArrowLeftRight, Pencil, Trash2 } from "lucide-react";
|
||||
import { getCategoryIcon } from "@/lib/icons";
|
||||
import { formatCurrency, formatTransactionDate } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import { translateCategoryName } from "@/lib/categoryLabels";
|
||||
import type { Transaction } from "@/types";
|
||||
|
||||
interface TransactionsTableProps {
|
||||
items: Transaction[];
|
||||
onEdit: (transaction: Transaction) => void;
|
||||
onDelete: (transaction: Transaction) => void;
|
||||
}
|
||||
|
||||
export function TransactionsTable({ items, onEdit, onDelete }: TransactionsTableProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (items.length === 0) {
|
||||
return <p className="py-12 text-center text-sm text-text-muted">{t("transactions.noneFound")}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="divide-y divide-gridline">
|
||||
{items.map((tx) => {
|
||||
const isTransfer = tx.type === "transfer";
|
||||
const isExpense = tx.type === "expense";
|
||||
const Icon = isTransfer ? ArrowLeftRight : getCategoryIcon(tx.category?.icon);
|
||||
const color = isTransfer ? "var(--text-muted)" : tx.category?.color ?? "var(--text-muted)";
|
||||
|
||||
return (
|
||||
<li key={tx.id} className="group flex items-center gap-3 py-3">
|
||||
<span
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full"
|
||||
style={{ backgroundColor: typeof color === "string" && color.startsWith("#") ? `${color}26` : "var(--surface-2)" }}
|
||||
>
|
||||
<Icon size={16} style={{ color }} />
|
||||
</span>
|
||||
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium text-text-primary">{tx.description}</span>
|
||||
<span className="block truncate text-xs text-text-muted">
|
||||
{formatTransactionDate(tx.date)} · {tx.account.name}
|
||||
{isTransfer && tx.transfer_account_id ? ` ${t("transactions.transferSuffix")}` : ""}
|
||||
{tx.category ? ` · ${translateCategoryName(tx.category.name)}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
<span
|
||||
className={`shrink-0 text-sm font-medium tabular-nums ${
|
||||
isTransfer ? "text-text-muted" : isExpense ? "text-text-primary" : "text-success"
|
||||
}`}
|
||||
>
|
||||
{isTransfer ? "" : isExpense ? "-" : "+"}
|
||||
{formatCurrency(tx.amount)}
|
||||
</span>
|
||||
|
||||
<span className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.edit")}
|
||||
onClick={() => onEdit(tx)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.delete")}
|
||||
onClick={() => onDelete(tx)}
|
||||
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
14
frontend/src/components/ui/Badge.tsx
Normal file
14
frontend/src/components/ui/Badge.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Badge({ className, ...props }: HTMLAttributes<HTMLSpanElement>) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full bg-surface-2 px-2 py-0.5 text-xs font-medium text-text-secondary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
28
frontend/src/components/ui/Button.tsx
Normal file
28
frontend/src/components/ui/Button.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { ButtonHTMLAttributes } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Variant = "primary" | "secondary" | "ghost" | "danger";
|
||||
|
||||
const VARIANT_CLASSES: Record<Variant, string> = {
|
||||
primary: "bg-text-primary text-surface-1 hover:opacity-90",
|
||||
secondary: "bg-surface-2 text-text-primary hover:bg-surface-2/70",
|
||||
ghost: "bg-transparent text-text-secondary hover:bg-surface-2",
|
||||
danger: "bg-danger text-white hover:opacity-90",
|
||||
};
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: Variant;
|
||||
}
|
||||
|
||||
export function Button({ className, variant = "primary", ...props }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"inline-flex h-9 items-center justify-center gap-1.5 rounded-lg px-3.5 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",
|
||||
VARIANT_CLASSES[variant],
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
28
frontend/src/components/ui/Card.tsx
Normal file
28
frontend/src/components/ui/Card.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { HTMLAttributes } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Card({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("rounded-xl border border-border bg-surface-1 shadow-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("flex items-center justify-between gap-2 p-4 sm:p-5", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardTitle({ className, ...props }: HTMLAttributes<HTMLHeadingElement>) {
|
||||
return (
|
||||
<h3
|
||||
className={cn("text-xs font-semibold uppercase tracking-wide text-text-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardContent({ className, ...props }: HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("p-4 pt-0 sm:p-5 sm:pt-0", className)} {...props} />;
|
||||
}
|
||||
53
frontend/src/components/ui/Dialog.tsx
Normal file
53
frontend/src/components/ui/Dialog.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import type { PropsWithChildren, ReactNode } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
|
||||
interface DialogProps extends PropsWithChildren {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: ReactNode;
|
||||
}
|
||||
|
||||
export function Dialog({ open, onClose, title, children }: DialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
};
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => document.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4"
|
||||
)}
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="max-h-[90vh] w-full overflow-y-auto rounded-t-2xl border border-border bg-surface-1 p-5 shadow-xl sm:max-w-md sm:rounded-2xl"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-text-primary">{title}</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t("common.close")}
|
||||
className="rounded-md p-1 text-text-muted hover:bg-surface-2"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
32
frontend/src/components/ui/Input.tsx
Normal file
32
frontend/src/components/ui/Input.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { InputHTMLAttributes, LabelHTMLAttributes, SelectHTMLAttributes } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<input
|
||||
className={cn(
|
||||
"h-9 w-full rounded-lg border border-border bg-surface-1 px-3 text-sm text-text-primary outline-none focus:border-series-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function Select({ className, children, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
|
||||
return (
|
||||
<select
|
||||
className={cn(
|
||||
"h-9 w-full rounded-lg border border-border bg-surface-1 px-3 text-sm text-text-primary outline-none focus:border-series-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
export function Label({ className, ...props }: LabelHTMLAttributes<HTMLLabelElement>) {
|
||||
return <label className={cn("mb-1 block text-xs font-medium text-text-secondary", className)} {...props} />;
|
||||
}
|
||||
Reference in New Issue
Block a user