feat: creats frontend for the project
This commit is contained in:
117
frontend/src/components/AccountsList.tsx
Normal file
117
frontend/src/components/AccountsList.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { Account } from '@family-budget/shared';
|
||||
import { getAccounts, updateAccount } from '../api/accounts';
|
||||
|
||||
export function AccountsList() {
|
||||
const [accounts, setAccounts] = useState<Account[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [editAlias, setEditAlias] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
getAccounts()
|
||||
.then(setAccounts)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleEdit = (account: Account) => {
|
||||
setEditingId(account.id);
|
||||
setEditAlias(account.alias || '');
|
||||
};
|
||||
|
||||
const handleSave = async (id: number) => {
|
||||
try {
|
||||
const updated = await updateAccount(id, {
|
||||
alias: editAlias.trim(),
|
||||
});
|
||||
setAccounts((prev) =>
|
||||
prev.map((a) => (a.id === id ? updated : a)),
|
||||
);
|
||||
setEditingId(null);
|
||||
} catch {
|
||||
// error handled globally
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="section-loading">Загрузка...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-section">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Банк</th>
|
||||
<th>Номер счёта</th>
|
||||
<th>Валюта</th>
|
||||
<th>Алиас</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{accounts.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td>{a.bank}</td>
|
||||
<td>{a.accountNumberMasked}</td>
|
||||
<td>{a.currency}</td>
|
||||
<td>
|
||||
{editingId === a.id ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editAlias}
|
||||
onChange={(e) => setEditAlias(e.target.value)}
|
||||
maxLength={50}
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleSave(a.id);
|
||||
if (e.key === 'Escape') setEditingId(null);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
a.alias || (
|
||||
<span className="text-muted">не задан</span>
|
||||
)
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editingId === a.id ? (
|
||||
<div className="btn-group">
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => handleSave(a.id)}
|
||||
>
|
||||
Сохранить
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-secondary"
|
||||
onClick={() => setEditingId(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
className="btn btn-sm btn-secondary"
|
||||
onClick={() => handleEdit(a)}
|
||||
>
|
||||
Изменить
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{accounts.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={5} className="td-center text-muted">
|
||||
Нет счетов. Импортируйте выписку.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
51
frontend/src/components/CategoriesList.tsx
Normal file
51
frontend/src/components/CategoriesList.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { Category } from '@family-budget/shared';
|
||||
import { getCategories } from '../api/categories';
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
expense: 'Расход',
|
||||
income: 'Доход',
|
||||
transfer: 'Перевод',
|
||||
};
|
||||
|
||||
export function CategoriesList() {
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
getCategories({ isActive: true })
|
||||
.then(setCategories)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return <div className="section-loading">Загрузка...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-section">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Категория</th>
|
||||
<th>Тип</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categories.map((c) => (
|
||||
<tr key={c.id}>
|
||||
<td>{c.name}</td>
|
||||
<td>
|
||||
<span className={`badge badge-${c.type}`}>
|
||||
{TYPE_LABELS[c.type] ?? c.type}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
frontend/src/components/CategoryChart.tsx
Normal file
101
frontend/src/components/CategoryChart.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import type { ByCategoryItem } from '@family-budget/shared';
|
||||
import { formatAmount } from '../utils/format';
|
||||
|
||||
interface Props {
|
||||
data: ByCategoryItem[];
|
||||
}
|
||||
|
||||
const COLORS = [
|
||||
'#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6',
|
||||
'#ec4899', '#06b6d4', '#84cc16', '#f97316', '#6366f1',
|
||||
'#14b8a6', '#e11d48', '#0ea5e9', '#a855f7', '#22c55e',
|
||||
];
|
||||
|
||||
const rubFormatter = new Intl.NumberFormat('ru-RU', {
|
||||
style: 'currency',
|
||||
currency: 'RUB',
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
|
||||
export function CategoryChart({ data }: Props) {
|
||||
if (data.length === 0) {
|
||||
return <div className="chart-empty">Нет данных за период</div>;
|
||||
}
|
||||
|
||||
const chartData = data.map((item) => ({
|
||||
name: item.categoryName,
|
||||
value: Math.abs(item.amount) / 100,
|
||||
txCount: item.txCount,
|
||||
share: item.share,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="category-chart-wrapper">
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={100}
|
||||
dataKey="value"
|
||||
nameKey="name"
|
||||
label={({ name, share }: { name: string; share: number }) =>
|
||||
`${name} ${(share * 100).toFixed(0)}%`
|
||||
}
|
||||
labelLine
|
||||
>
|
||||
{chartData.map((_, idx) => (
|
||||
<Cell
|
||||
key={idx}
|
||||
fill={COLORS[idx % COLORS.length]}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value: number) => rubFormatter.format(value)}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
<table className="category-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Категория</th>
|
||||
<th>Сумма</th>
|
||||
<th className="th-center">Операций</th>
|
||||
<th className="th-center">Доля</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.map((item, idx) => (
|
||||
<tr key={item.categoryId}>
|
||||
<td>
|
||||
<span
|
||||
className="color-dot"
|
||||
style={{
|
||||
backgroundColor:
|
||||
COLORS[idx % COLORS.length],
|
||||
}}
|
||||
/>
|
||||
{item.categoryName}
|
||||
</td>
|
||||
<td>{formatAmount(item.amount)}</td>
|
||||
<td className="td-center">{item.txCount}</td>
|
||||
<td className="td-center">
|
||||
{(item.share * 100).toFixed(1)}%
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
197
frontend/src/components/EditTransactionModal.tsx
Normal file
197
frontend/src/components/EditTransactionModal.tsx
Normal file
@@ -0,0 +1,197 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import type {
|
||||
Transaction,
|
||||
Category,
|
||||
CreateCategoryRuleRequest,
|
||||
} from '@family-budget/shared';
|
||||
import { updateTransaction } from '../api/transactions';
|
||||
import { createCategoryRule } from '../api/rules';
|
||||
import { formatAmount, formatDateTime } from '../utils/format';
|
||||
|
||||
interface Props {
|
||||
transaction: Transaction;
|
||||
categories: Category[];
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
}
|
||||
|
||||
function extractPattern(description: string): string {
|
||||
return description
|
||||
.replace(/Оплата товаров и услуг\.\s*/i, '')
|
||||
.replace(/\s*по карте\s*\*\d+.*/i, '')
|
||||
.replace(/\s*Перевод средств.*/i, '')
|
||||
.trim()
|
||||
.slice(0, 50);
|
||||
}
|
||||
|
||||
export function EditTransactionModal({
|
||||
transaction,
|
||||
categories,
|
||||
onClose,
|
||||
onSave,
|
||||
}: Props) {
|
||||
const [categoryId, setCategoryId] = useState<string>(
|
||||
transaction.categoryId != null ? String(transaction.categoryId) : '',
|
||||
);
|
||||
const [comment, setComment] = useState(transaction.comment || '');
|
||||
const [createRule, setCreateRule] = useState(true);
|
||||
const [pattern, setPattern] = useState(
|
||||
extractPattern(transaction.description),
|
||||
);
|
||||
const [requiresConfirmation, setRequiresConfirmation] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
await updateTransaction(transaction.id, {
|
||||
categoryId: categoryId ? Number(categoryId) : null,
|
||||
comment: comment || null,
|
||||
});
|
||||
|
||||
if (createRule && categoryId && pattern.trim()) {
|
||||
const ruleData: CreateCategoryRuleRequest = {
|
||||
pattern: pattern.trim(),
|
||||
matchType: 'contains',
|
||||
categoryId: Number(categoryId),
|
||||
priority: 100,
|
||||
requiresConfirmation,
|
||||
};
|
||||
await createCategoryRule(ruleData);
|
||||
}
|
||||
|
||||
onSave();
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Ошибка сохранения';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onClose}>
|
||||
<div className="modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h2>Редактирование операции</h2>
|
||||
<button className="btn-close" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="modal-body">
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
|
||||
<div className="modal-tx-info">
|
||||
<div className="modal-tx-row">
|
||||
<span className="modal-tx-label">Дата</span>
|
||||
<span>{formatDateTime(transaction.operationAt)}</span>
|
||||
</div>
|
||||
<div className="modal-tx-row">
|
||||
<span className="modal-tx-label">Сумма</span>
|
||||
<span>{formatAmount(transaction.amountSigned)}</span>
|
||||
</div>
|
||||
<div className="modal-tx-row">
|
||||
<span className="modal-tx-label">Описание</span>
|
||||
<span className="modal-tx-description">
|
||||
{transaction.description}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="edit-category">Категория</label>
|
||||
<select
|
||||
id="edit-category"
|
||||
value={categoryId}
|
||||
onChange={(e) => setCategoryId(e.target.value)}
|
||||
>
|
||||
<option value="">— Без категории —</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="edit-comment">Комментарий</label>
|
||||
<textarea
|
||||
id="edit-comment"
|
||||
rows={2}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
placeholder="Комментарий к операции..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-divider" />
|
||||
|
||||
<div className="form-group form-group-checkbox">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={createRule}
|
||||
onChange={(e) => setCreateRule(e.target.checked)}
|
||||
/>
|
||||
Создать правило для похожих транзакций
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{createRule && (
|
||||
<>
|
||||
<div className="form-group">
|
||||
<label htmlFor="edit-pattern">
|
||||
Шаблон (ключевая строка)
|
||||
</label>
|
||||
<input
|
||||
id="edit-pattern"
|
||||
type="text"
|
||||
value={pattern}
|
||||
onChange={(e) => setPattern(e.target.value)}
|
||||
maxLength={200}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group form-group-checkbox">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={requiresConfirmation}
|
||||
onChange={(e) =>
|
||||
setRequiresConfirmation(e.target.checked)
|
||||
}
|
||||
/>
|
||||
Требовать подтверждения категории
|
||||
</label>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onClose}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
164
frontend/src/components/ImportModal.tsx
Normal file
164
frontend/src/components/ImportModal.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import { useState, useRef } from 'react';
|
||||
import type { ImportStatementResponse } from '@family-budget/shared';
|
||||
import { importStatement } from '../api/import';
|
||||
import { updateAccount } from '../api/accounts';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
onDone: () => void;
|
||||
}
|
||||
|
||||
export function ImportModal({ onClose, onDone }: Props) {
|
||||
const [result, setResult] = useState<ImportStatementResponse | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [alias, setAlias] = useState('');
|
||||
const [aliasSaved, setAliasSaved] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileChange = async (
|
||||
e: React.ChangeEvent<HTMLInputElement>,
|
||||
) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setResult(null);
|
||||
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const resp = await importStatement(json);
|
||||
setResult(resp);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof SyntaxError) {
|
||||
setError('Некорректный JSON-файл');
|
||||
} else {
|
||||
const msg =
|
||||
err instanceof Error ? err.message : 'Ошибка импорта';
|
||||
setError(msg);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAlias = async () => {
|
||||
if (!result || !alias.trim()) return;
|
||||
try {
|
||||
await updateAccount(result.accountId, { alias: alias.trim() });
|
||||
setAliasSaved(true);
|
||||
} catch {
|
||||
// handled globally
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onClose}>
|
||||
<div className="modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h2>Импорт выписки</h2>
|
||||
<button className="btn-close" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="modal-body">
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
|
||||
{!result && (
|
||||
<div className="import-upload">
|
||||
<p>Выберите JSON-файл выписки (формат 1.0)</p>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".json"
|
||||
onChange={handleFileChange}
|
||||
className="file-input"
|
||||
/>
|
||||
{loading && (
|
||||
<div className="import-loading">Импорт...</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="import-result">
|
||||
<div className="import-result-icon">✓</div>
|
||||
<h3>Импорт завершён</h3>
|
||||
<table className="import-stats">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Счёт</td>
|
||||
<td>{result.accountNumberMasked}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Новый счёт</td>
|
||||
<td>{result.isNewAccount ? 'Да' : 'Нет'}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Импортировано</td>
|
||||
<td>{result.imported}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Дубликатов пропущено</td>
|
||||
<td>{result.duplicatesSkipped}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Всего в файле</td>
|
||||
<td>{result.totalInFile}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{result.isNewAccount && !aliasSaved && (
|
||||
<div className="import-alias">
|
||||
<label>Алиас для нового счёта</label>
|
||||
<div className="import-alias-row">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Напр.: Текущий, Накопительный"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
maxLength={50}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={handleSaveAlias}
|
||||
disabled={!alias.trim()}
|
||||
>
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{aliasSaved && (
|
||||
<div className="import-alias-saved">
|
||||
Алиас сохранён
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
{result ? (
|
||||
<button className="btn btn-primary" onClick={onDone}>
|
||||
Готово
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
72
frontend/src/components/Layout.tsx
Normal file
72
frontend/src/components/Layout.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export function Layout({ children }: { children: ReactNode }) {
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="layout">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<span className="sidebar-brand-icon">₽</span>
|
||||
<span className="sidebar-brand-text">Семейный бюджет</span>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar-nav">
|
||||
<NavLink
|
||||
to="/history"
|
||||
className={({ isActive }) =>
|
||||
`nav-link${isActive ? ' active' : ''}`
|
||||
}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
|
||||
<polyline points="14,2 14,8 20,8" />
|
||||
<line x1="16" y1="13" x2="8" y2="13" />
|
||||
<line x1="16" y1="17" x2="8" y2="17" />
|
||||
<polyline points="10,9 9,9 8,9" />
|
||||
</svg>
|
||||
Операции
|
||||
</NavLink>
|
||||
|
||||
<NavLink
|
||||
to="/analytics"
|
||||
className={({ isActive }) =>
|
||||
`nav-link${isActive ? ' active' : ''}`
|
||||
}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="18" y1="20" x2="18" y2="10" />
|
||||
<line x1="12" y1="20" x2="12" y2="4" />
|
||||
<line x1="6" y1="20" x2="6" y2="14" />
|
||||
</svg>
|
||||
Аналитика
|
||||
</NavLink>
|
||||
|
||||
<NavLink
|
||||
to="/settings"
|
||||
className={({ isActive }) =>
|
||||
`nav-link${isActive ? ' active' : ''}`
|
||||
}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" />
|
||||
</svg>
|
||||
Настройки
|
||||
</NavLink>
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-footer">
|
||||
<span className="sidebar-user">{user?.login}</span>
|
||||
<button className="btn-logout" onClick={() => logout()}>
|
||||
Выход
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="main-content">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
frontend/src/components/Pagination.tsx
Normal file
58
frontend/src/components/Pagination.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
interface Props {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalItems: number;
|
||||
totalPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
}
|
||||
|
||||
export function Pagination({
|
||||
page,
|
||||
pageSize,
|
||||
totalItems,
|
||||
totalPages,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
}: Props) {
|
||||
const from = (page - 1) * pageSize + 1;
|
||||
const to = Math.min(page * pageSize, totalItems);
|
||||
|
||||
return (
|
||||
<div className="pagination">
|
||||
<div className="pagination-info">
|
||||
{totalItems > 0
|
||||
? `Показано ${from}–${to} из ${totalItems}`
|
||||
: 'Нет записей'}
|
||||
</div>
|
||||
<div className="pagination-controls">
|
||||
<select
|
||||
className="pagination-size"
|
||||
value={pageSize}
|
||||
onChange={(e) => onPageSizeChange(Number(e.target.value))}
|
||||
>
|
||||
<option value={10}>10</option>
|
||||
<option value={50}>50</option>
|
||||
<option value={100}>100</option>
|
||||
</select>
|
||||
<button
|
||||
className="btn-page"
|
||||
disabled={page <= 1}
|
||||
onClick={() => onPageChange(page - 1)}
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<span className="pagination-current">
|
||||
{page} / {totalPages || 1}
|
||||
</span>
|
||||
<button
|
||||
className="btn-page"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => onPageChange(page + 1)}
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
134
frontend/src/components/PeriodSelector.tsx
Normal file
134
frontend/src/components/PeriodSelector.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { toISODate } from '../utils/format';
|
||||
|
||||
export type PeriodMode = 'week' | 'month' | 'year' | 'custom';
|
||||
|
||||
export interface PeriodState {
|
||||
mode: PeriodMode;
|
||||
from: string;
|
||||
to: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
period: PeriodState;
|
||||
onChange: (period: PeriodState) => void;
|
||||
}
|
||||
|
||||
const MODE_LABELS: Record<PeriodMode, string> = {
|
||||
week: 'Неделя',
|
||||
month: 'Месяц',
|
||||
year: 'Год',
|
||||
custom: 'Период',
|
||||
};
|
||||
|
||||
export function PeriodSelector({ period, onChange }: Props) {
|
||||
const setMode = (mode: PeriodMode) => {
|
||||
const now = new Date();
|
||||
let from: Date;
|
||||
switch (mode) {
|
||||
case 'week': {
|
||||
const day = now.getDay();
|
||||
const diff = day === 0 ? 6 : day - 1;
|
||||
from = new Date(now);
|
||||
from.setDate(now.getDate() - diff);
|
||||
break;
|
||||
}
|
||||
case 'month':
|
||||
from = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
break;
|
||||
case 'year':
|
||||
from = new Date(now.getFullYear(), 0, 1);
|
||||
break;
|
||||
case 'custom':
|
||||
onChange({ mode, from: period.from, to: period.to });
|
||||
return;
|
||||
}
|
||||
onChange({ mode, from: toISODate(from), to: toISODate(now) });
|
||||
};
|
||||
|
||||
const navigate = (direction: -1 | 1) => {
|
||||
const fromDate = new Date(period.from);
|
||||
let newFrom: Date;
|
||||
let newTo: Date;
|
||||
|
||||
switch (period.mode) {
|
||||
case 'week':
|
||||
newFrom = new Date(fromDate);
|
||||
newFrom.setDate(fromDate.getDate() + 7 * direction);
|
||||
newTo = new Date(newFrom);
|
||||
newTo.setDate(newFrom.getDate() + 6);
|
||||
break;
|
||||
case 'month':
|
||||
newFrom = new Date(
|
||||
fromDate.getFullYear(),
|
||||
fromDate.getMonth() + direction,
|
||||
1,
|
||||
);
|
||||
newTo = new Date(
|
||||
newFrom.getFullYear(),
|
||||
newFrom.getMonth() + 1,
|
||||
0,
|
||||
);
|
||||
break;
|
||||
case 'year':
|
||||
newFrom = new Date(fromDate.getFullYear() + direction, 0, 1);
|
||||
newTo = new Date(newFrom.getFullYear(), 11, 31);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
onChange({
|
||||
mode: period.mode,
|
||||
from: toISODate(newFrom),
|
||||
to: toISODate(newTo),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="period-selector">
|
||||
<div className="period-modes">
|
||||
{(['week', 'month', 'year', 'custom'] as PeriodMode[]).map(
|
||||
(m) => (
|
||||
<button
|
||||
key={m}
|
||||
className={`btn-preset ${period.mode === m ? 'active' : ''}`}
|
||||
onClick={() => setMode(m)}
|
||||
>
|
||||
{MODE_LABELS[m]}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="period-nav">
|
||||
{period.mode !== 'custom' && (
|
||||
<button className="btn-page" onClick={() => navigate(-1)}>
|
||||
←
|
||||
</button>
|
||||
)}
|
||||
<div className="period-dates">
|
||||
<input
|
||||
type="date"
|
||||
value={period.from}
|
||||
onChange={(e) =>
|
||||
onChange({ ...period, mode: 'custom', from: e.target.value })
|
||||
}
|
||||
/>
|
||||
<span className="filter-separator">—</span>
|
||||
<input
|
||||
type="date"
|
||||
value={period.to}
|
||||
onChange={(e) =>
|
||||
onChange({ ...period, mode: 'custom', to: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{period.mode !== 'custom' && (
|
||||
<button className="btn-page" onClick={() => navigate(1)}>
|
||||
→
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
130
frontend/src/components/RulesList.tsx
Normal file
130
frontend/src/components/RulesList.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { CategoryRule } from '@family-budget/shared';
|
||||
import {
|
||||
getCategoryRules,
|
||||
updateCategoryRule,
|
||||
applyRule,
|
||||
} from '../api/rules';
|
||||
import { formatDate } from '../utils/format';
|
||||
|
||||
export function RulesList() {
|
||||
const [rules, setRules] = useState<CategoryRule[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [applyingId, setApplyingId] = useState<number | null>(null);
|
||||
const [applyResult, setApplyResult] = useState<{
|
||||
id: number;
|
||||
count: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
getCategoryRules()
|
||||
.then(setRules)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleToggle = async (rule: CategoryRule) => {
|
||||
try {
|
||||
const updated = await updateCategoryRule(rule.id, {
|
||||
isActive: !rule.isActive,
|
||||
});
|
||||
setRules((prev) =>
|
||||
prev.map((r) => (r.id === rule.id ? updated : r)),
|
||||
);
|
||||
} catch {
|
||||
// error handled globally
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async (id: number) => {
|
||||
setApplyingId(id);
|
||||
try {
|
||||
const resp = await applyRule(id);
|
||||
setApplyResult({ id, count: resp.applied });
|
||||
setTimeout(() => setApplyResult(null), 4000);
|
||||
} catch {
|
||||
// error handled globally
|
||||
} finally {
|
||||
setApplyingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="section-loading">Загрузка...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-section">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Шаблон</th>
|
||||
<th>Категория</th>
|
||||
<th className="th-center">Приоритет</th>
|
||||
<th className="th-center">Подтверждение</th>
|
||||
<th>Создано</th>
|
||||
<th className="th-center">Активно</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rules.map((r) => (
|
||||
<tr
|
||||
key={r.id}
|
||||
className={!r.isActive ? 'row-inactive' : ''}
|
||||
>
|
||||
<td>
|
||||
<code>{r.pattern}</code>
|
||||
</td>
|
||||
<td>{r.categoryName}</td>
|
||||
<td className="td-center">{r.priority}</td>
|
||||
<td className="td-center">
|
||||
{r.requiresConfirmation ? 'Да' : 'Нет'}
|
||||
</td>
|
||||
<td className="td-nowrap">
|
||||
{formatDate(r.createdAt)}
|
||||
</td>
|
||||
<td className="td-center">
|
||||
<button
|
||||
className={`toggle ${r.isActive ? 'toggle-on' : 'toggle-off'}`}
|
||||
onClick={() => handleToggle(r)}
|
||||
title={
|
||||
r.isActive ? 'Деактивировать' : 'Активировать'
|
||||
}
|
||||
>
|
||||
{r.isActive ? 'Вкл' : 'Выкл'}
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
<div className="rules-actions">
|
||||
{r.isActive && (
|
||||
<button
|
||||
className="btn btn-sm btn-secondary"
|
||||
onClick={() => handleApply(r.id)}
|
||||
disabled={applyingId === r.id}
|
||||
>
|
||||
{applyingId === r.id ? '...' : 'Применить'}
|
||||
</button>
|
||||
)}
|
||||
{applyResult?.id === r.id && (
|
||||
<span className="apply-result">
|
||||
Применено: {applyResult.count}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{rules.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={7} className="td-center text-muted">
|
||||
Нет правил
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
59
frontend/src/components/SummaryCards.tsx
Normal file
59
frontend/src/components/SummaryCards.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { AnalyticsSummaryResponse } from '@family-budget/shared';
|
||||
import { formatAmount } from '../utils/format';
|
||||
|
||||
interface Props {
|
||||
summary: AnalyticsSummaryResponse;
|
||||
}
|
||||
|
||||
export function SummaryCards({ summary }: Props) {
|
||||
return (
|
||||
<div className="summary-cards">
|
||||
<div className="summary-card summary-card-income">
|
||||
<div className="summary-label">Доходы</div>
|
||||
<div className="summary-value">
|
||||
{formatAmount(summary.totalIncome)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="summary-card summary-card-expense">
|
||||
<div className="summary-label">Расходы</div>
|
||||
<div className="summary-value">
|
||||
{formatAmount(summary.totalExpense)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`summary-card ${summary.net >= 0 ? 'summary-card-positive' : 'summary-card-negative'}`}
|
||||
>
|
||||
<div className="summary-label">Баланс</div>
|
||||
<div className="summary-value">
|
||||
{formatAmount(summary.net)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{summary.topCategories.length > 0 && (
|
||||
<div className="summary-card summary-card-top">
|
||||
<div className="summary-label">Топ расходов</div>
|
||||
<div className="summary-top-list">
|
||||
{summary.topCategories.map((cat) => (
|
||||
<div
|
||||
key={cat.categoryId}
|
||||
className="top-category-item"
|
||||
>
|
||||
<span className="top-category-name">
|
||||
{cat.categoryName}
|
||||
</span>
|
||||
<span className="top-category-amount">
|
||||
{formatAmount(cat.amount)}
|
||||
</span>
|
||||
<span className="top-category-share">
|
||||
{(cat.share * 100).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
71
frontend/src/components/TimeseriesChart.tsx
Normal file
71
frontend/src/components/TimeseriesChart.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
BarChart,
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import type { TimeseriesItem } from '@family-budget/shared';
|
||||
|
||||
interface Props {
|
||||
data: TimeseriesItem[];
|
||||
}
|
||||
|
||||
const rubFormatter = new Intl.NumberFormat('ru-RU', {
|
||||
style: 'currency',
|
||||
currency: 'RUB',
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
|
||||
export function TimeseriesChart({ data }: Props) {
|
||||
if (data.length === 0) {
|
||||
return <div className="chart-empty">Нет данных за период</div>;
|
||||
}
|
||||
|
||||
const chartData = data.map((item) => ({
|
||||
period: item.periodStart,
|
||||
Расходы: Math.abs(item.expenseAmount) / 100,
|
||||
Доходы: item.incomeAmount / 100,
|
||||
}));
|
||||
|
||||
return (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={chartData}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
|
||||
<XAxis
|
||||
dataKey="period"
|
||||
tickFormatter={(v: string) => {
|
||||
const d = new Date(v);
|
||||
return `${d.getDate()}.${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
}}
|
||||
fontSize={12}
|
||||
stroke="#64748b"
|
||||
/>
|
||||
<YAxis
|
||||
tickFormatter={(v: number) =>
|
||||
v >= 1000 ? `${(v / 1000).toFixed(0)}к` : String(v)
|
||||
}
|
||||
fontSize={12}
|
||||
stroke="#64748b"
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value: number) => rubFormatter.format(value)}
|
||||
/>
|
||||
<Legend />
|
||||
<Bar
|
||||
dataKey="Расходы"
|
||||
fill="#ef4444"
|
||||
radius={[4, 4, 0, 0]}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="Доходы"
|
||||
fill="#10b981"
|
||||
radius={[4, 4, 0, 0]}
|
||||
/>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
223
frontend/src/components/TransactionFilters.tsx
Normal file
223
frontend/src/components/TransactionFilters.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
import type {
|
||||
Account,
|
||||
Category,
|
||||
SortOrder,
|
||||
TransactionSortBy,
|
||||
} from '@family-budget/shared';
|
||||
import { toISODate } from '../utils/format';
|
||||
|
||||
export interface FiltersState {
|
||||
from: string;
|
||||
to: string;
|
||||
accountId: string;
|
||||
direction: string;
|
||||
categoryId: string;
|
||||
search: string;
|
||||
amountMin: string;
|
||||
amountMax: string;
|
||||
onlyUnconfirmed: boolean;
|
||||
sortBy: TransactionSortBy;
|
||||
sortOrder: SortOrder;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
filters: FiltersState;
|
||||
onChange: (filters: FiltersState) => void;
|
||||
accounts: Account[];
|
||||
categories: Category[];
|
||||
}
|
||||
|
||||
export function TransactionFilters({
|
||||
filters,
|
||||
onChange,
|
||||
accounts,
|
||||
categories,
|
||||
}: Props) {
|
||||
const set = <K extends keyof FiltersState>(
|
||||
key: K,
|
||||
value: FiltersState[K],
|
||||
) => {
|
||||
onChange({ ...filters, [key]: value });
|
||||
};
|
||||
|
||||
const applyPreset = (preset: 'week' | 'month' | 'year') => {
|
||||
const now = new Date();
|
||||
let from: Date;
|
||||
switch (preset) {
|
||||
case 'week': {
|
||||
const day = now.getDay();
|
||||
const diff = day === 0 ? 6 : day - 1;
|
||||
from = new Date(now);
|
||||
from.setDate(now.getDate() - diff);
|
||||
break;
|
||||
}
|
||||
case 'month':
|
||||
from = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
break;
|
||||
case 'year':
|
||||
from = new Date(now.getFullYear(), 0, 1);
|
||||
break;
|
||||
}
|
||||
onChange({ ...filters, from: toISODate(from), to: toISODate(now) });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="filters-panel">
|
||||
<div className="filters-row">
|
||||
<div className="filter-group">
|
||||
<label>Период</label>
|
||||
<div className="filter-dates">
|
||||
<input
|
||||
type="date"
|
||||
value={filters.from}
|
||||
onChange={(e) => set('from', e.target.value)}
|
||||
/>
|
||||
<span className="filter-separator">—</span>
|
||||
<input
|
||||
type="date"
|
||||
value={filters.to}
|
||||
onChange={(e) => set('to', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="filter-presets">
|
||||
<button
|
||||
className="btn-preset"
|
||||
onClick={() => applyPreset('week')}
|
||||
>
|
||||
Неделя
|
||||
</button>
|
||||
<button
|
||||
className="btn-preset"
|
||||
onClick={() => applyPreset('month')}
|
||||
>
|
||||
Месяц
|
||||
</button>
|
||||
<button
|
||||
className="btn-preset"
|
||||
onClick={() => applyPreset('year')}
|
||||
>
|
||||
Год
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Счёт</label>
|
||||
<select
|
||||
value={filters.accountId}
|
||||
onChange={(e) => set('accountId', e.target.value)}
|
||||
>
|
||||
<option value="">Все счета</option>
|
||||
{accounts.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.alias || a.accountNumberMasked}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Тип</label>
|
||||
<select
|
||||
value={filters.direction}
|
||||
onChange={(e) => set('direction', e.target.value)}
|
||||
>
|
||||
<option value="">Все</option>
|
||||
<option value="expense">Расход</option>
|
||||
<option value="income">Приход</option>
|
||||
<option value="transfer">Перевод</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Категория</label>
|
||||
<select
|
||||
value={filters.categoryId}
|
||||
onChange={(e) => set('categoryId', e.target.value)}
|
||||
>
|
||||
<option value="">Все категории</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="filters-row">
|
||||
<div className="filter-group filter-group-wide">
|
||||
<label>Поиск</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Поиск по описанию..."
|
||||
value={filters.search}
|
||||
onChange={(e) => set('search', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Сумма от (₽)</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="мин"
|
||||
value={filters.amountMin}
|
||||
onChange={(e) => set('amountMin', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Сумма до (₽)</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="макс"
|
||||
value={filters.amountMax}
|
||||
onChange={(e) => set('amountMax', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="filter-group filter-group-checkbox">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filters.onlyUnconfirmed}
|
||||
onChange={(e) => set('onlyUnconfirmed', e.target.checked)}
|
||||
/>
|
||||
Только неподтверждённые
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="filter-group">
|
||||
<label>Сортировка</label>
|
||||
<div className="filter-sort">
|
||||
<select
|
||||
value={filters.sortBy}
|
||||
onChange={(e) =>
|
||||
set('sortBy', e.target.value as TransactionSortBy)
|
||||
}
|
||||
>
|
||||
<option value="date">По дате</option>
|
||||
<option value="amount">По сумме</option>
|
||||
</select>
|
||||
<button
|
||||
className="btn-sort-order"
|
||||
onClick={() =>
|
||||
set(
|
||||
'sortOrder',
|
||||
filters.sortOrder === 'asc' ? 'desc' : 'asc',
|
||||
)
|
||||
}
|
||||
title={
|
||||
filters.sortOrder === 'asc'
|
||||
? 'По возрастанию'
|
||||
: 'По убыванию'
|
||||
}
|
||||
>
|
||||
{filters.sortOrder === 'asc' ? '↑' : '↓'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
107
frontend/src/components/TransactionTable.tsx
Normal file
107
frontend/src/components/TransactionTable.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { Transaction } from '@family-budget/shared';
|
||||
import { formatAmount, formatDateTime } from '../utils/format';
|
||||
|
||||
interface Props {
|
||||
transactions: Transaction[];
|
||||
loading: boolean;
|
||||
onEdit: (tx: Transaction) => void;
|
||||
}
|
||||
|
||||
const DIRECTION_LABELS: Record<string, string> = {
|
||||
income: 'Приход',
|
||||
expense: 'Расход',
|
||||
transfer: 'Перевод',
|
||||
};
|
||||
|
||||
const DIRECTION_CLASSES: Record<string, string> = {
|
||||
income: 'amount-income',
|
||||
expense: 'amount-expense',
|
||||
transfer: 'amount-transfer',
|
||||
};
|
||||
|
||||
export function TransactionTable({ transactions, loading, onEdit }: Props) {
|
||||
if (loading) {
|
||||
return <div className="table-loading">Загрузка операций...</div>;
|
||||
}
|
||||
|
||||
if (transactions.length === 0) {
|
||||
return <div className="table-empty">Операции не найдены</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="table-wrapper">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата</th>
|
||||
<th>Счёт</th>
|
||||
<th>Сумма</th>
|
||||
<th>Описание</th>
|
||||
<th>Категория</th>
|
||||
<th className="th-center">Статус</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{transactions.map((tx) => (
|
||||
<tr
|
||||
key={tx.id}
|
||||
className={
|
||||
!tx.isCategoryConfirmed && tx.categoryId
|
||||
? 'row-unconfirmed'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<td className="td-nowrap">
|
||||
{formatDateTime(tx.operationAt)}
|
||||
</td>
|
||||
<td className="td-nowrap">{tx.accountAlias || '—'}</td>
|
||||
<td
|
||||
className={`td-nowrap td-amount ${DIRECTION_CLASSES[tx.direction] ?? ''}`}
|
||||
>
|
||||
{formatAmount(tx.amountSigned)}
|
||||
</td>
|
||||
<td className="td-description">
|
||||
<span className="description-text">{tx.description}</span>
|
||||
{tx.comment && (
|
||||
<span className="comment-badge" title={tx.comment}>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" />
|
||||
</svg>
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="td-nowrap">
|
||||
{tx.categoryName || (
|
||||
<span className="text-muted">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="td-center">
|
||||
{tx.categoryId != null && !tx.isCategoryConfirmed && (
|
||||
<span
|
||||
className="badge badge-warning"
|
||||
title="Категория не подтверждена"
|
||||
>
|
||||
?
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn-icon"
|
||||
onClick={() => onEdit(tx)}
|
||||
title="Редактировать"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" />
|
||||
<path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" />
|
||||
</svg>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user