basic AI front epta

This commit is contained in:
arrelin
2025-12-15 12:16:37 +03:00
parent 74d55c43fd
commit 1e393c79b5
14 changed files with 1513 additions and 63 deletions

View File

@@ -0,0 +1,299 @@
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { categoryApi, expenseApi } from '../api/client';
import { useStore } from '../store/useStore';
import type { Category } from '../types';
export default function FamilyView() {
const { familyId } = useParams<{ familyId: string }>();
const navigate = useNavigate();
const { selectedFamily } = useStore();
const [categories, setCategories] = useState<Category[]>([]);
const [remainingLimits, setRemainingLimits] = useState<Map<number, number>>(new Map());
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [showAddCategory, setShowAddCategory] = useState(false);
const [newCategoryName, setNewCategoryName] = useState('');
const [newCategoryLimit, setNewCategoryLimit] = useState('');
const [showAddExpense, setShowAddExpense] = useState<number | null>(null);
const [expenseAmount, setExpenseAmount] = useState('');
const [expenseDescription, setExpenseDescription] = useState('');
useEffect(() => {
if (!familyId) {
navigate('/');
return;
}
loadCategories();
}, [familyId]);
const loadCategories = async () => {
if (!familyId) return;
try {
setLoading(true);
setError('');
console.log('Loading categories for family:', familyId);
const response = await categoryApi.getAllByFamily(parseInt(familyId));
console.log('Categories loaded:', response.data);
setCategories(response.data);
const limits = new Map<number, number>();
for (const category of response.data) {
const limitResponse = await expenseApi.getRemainingLimit(
parseInt(familyId),
category.id
);
const limitValue = typeof limitResponse.data.remaining_limit === 'string'
? parseFloat(limitResponse.data.remaining_limit)
: limitResponse.data.remaining_limit;
limits.set(category.id, limitValue);
}
setRemainingLimits(limits);
console.log('All data loaded successfully');
} catch (err: any) {
const errorMsg = err.response?.data?.message || err.message || 'Ошибка загрузки категорий';
setError(errorMsg);
console.error('Error loading categories:', err);
} finally {
setLoading(false);
}
};
const handleAddCategory = async () => {
if (!familyId || !newCategoryName || !newCategoryLimit) return;
try {
await categoryApi.create(parseInt(familyId), {
name: newCategoryName,
limit_amount: parseFloat(newCategoryLimit),
});
setNewCategoryName('');
setNewCategoryLimit('');
setShowAddCategory(false);
loadCategories();
} catch (err: any) {
const errorMsg = err.response?.data?.message || err.response?.statusText || err.message || 'Ошибка создания категории';
alert(`Ошибка создания категории: ${errorMsg} (Статус: ${err.response?.status})`);
console.error('Full error:', err);
}
};
const handleDeleteCategory = async (categoryId: number) => {
if (!familyId) return;
if (!confirm('Удалить категорию?')) return;
try {
await categoryApi.delete(parseInt(familyId), categoryId);
loadCategories();
} catch (err) {
alert('Ошибка удаления категории');
console.error(err);
}
};
const handleResetLimit = async (categoryId: number) => {
if (!familyId) return;
const newLimit = prompt('Введите новый лимит:');
if (!newLimit) return;
try {
await categoryApi.resetLimit(
parseInt(familyId),
categoryId,
parseFloat(newLimit)
);
loadCategories();
} catch (err) {
alert('Ошибка сброса лимита');
console.error(err);
}
};
const handleAddExpense = async (categoryId: number) => {
if (!familyId || !expenseAmount) return;
try {
await expenseApi.create(parseInt(familyId), categoryId, {
amount: parseFloat(expenseAmount),
description: expenseDescription || undefined,
});
setExpenseAmount('');
setExpenseDescription('');
setShowAddExpense(null);
loadCategories();
} catch (err) {
alert('Ошибка добавления расхода');
console.error(err);
}
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-xl text-gray-600">Загрузка...</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 py-12 px-4">
<div className="max-w-6xl mx-auto">
<div className="flex justify-between items-center mb-8">
<div>
<button
onClick={() => navigate('/')}
className="text-blue-600 hover:text-blue-700 mb-2"
>
Назад к списку семей
</button>
<h1 className="text-4xl font-bold text-gray-900">
{selectedFamily?.name || 'Семья'}
</h1>
</div>
</div>
{error && (
<div className="mb-6 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg">
{error}
</div>
)}
<div className="space-y-4">
{categories.map((category) => (
<div
key={category.id}
className="bg-white rounded-lg shadow-md p-6 flex items-center gap-6"
>
<div className="flex-1">
<h2 className="text-2xl font-semibold text-gray-900 mb-2">
{category.name}
</h2>
<p className="text-lg text-gray-700">
Остаток: <span className="font-bold text-green-600">
{remainingLimits.get(category.id)?.toFixed(2) || '0.00'}
</span>
{' / '}
{category.limit_amount.toString()}
</p>
</div>
<div className="flex flex-col gap-2">
{showAddExpense === category.id ? (
<div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
<input
type="number"
placeholder="Сумма"
value={expenseAmount}
onChange={(e) => setExpenseAmount(e.target.value)}
className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
/>
<input
type="text"
placeholder="Описание (опционально)"
value={expenseDescription}
onChange={(e) => setExpenseDescription(e.target.value)}
className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
/>
<div className="flex gap-2">
<button
onClick={() => handleAddExpense(category.id)}
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
>
Добавить
</button>
<button
onClick={() => setShowAddExpense(null)}
className="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400"
>
Отмена
</button>
</div>
</div>
) : (
<button
onClick={() => setShowAddExpense(category.id)}
className="px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
>
Вычесть из остатка
</button>
)}
</div>
</div>
))}
</div>
<div className="mt-8 bg-white rounded-lg shadow-md p-6">
<h2 className="text-2xl font-semibold text-gray-900 mb-4">
Управление категориями
</h2>
{showAddCategory ? (
<div className="mb-4">
<input
type="text"
placeholder="Название категории"
value={newCategoryName}
onChange={(e) => setNewCategoryName(e.target.value)}
className="w-full mb-2 px-4 py-2 border border-gray-300 rounded-lg"
/>
<input
type="number"
placeholder="Лимит"
value={newCategoryLimit}
onChange={(e) => setNewCategoryLimit(e.target.value)}
className="w-full mb-2 px-4 py-2 border border-gray-300 rounded-lg"
/>
<div className="flex gap-2">
<button
onClick={handleAddCategory}
className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
>
Создать
</button>
<button
onClick={() => setShowAddCategory(false)}
className="px-6 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
>
Отмена
</button>
</div>
</div>
) : (
<button
onClick={() => setShowAddCategory(true)}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 mb-4"
>
Добавить категорию
</button>
)}
<div className="space-y-2">
{categories.map((category) => (
<div key={category.id} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
<span className="font-medium">{category.name}</span>
<div className="flex gap-2">
<button
onClick={() => handleResetLimit(category.id)}
className="px-4 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600"
>
Сбросить лимит
</button>
<button
onClick={() => handleDeleteCategory(category.id)}
className="px-4 py-1 bg-red-500 text-white rounded hover:bg-red-600"
>
Удалить
</button>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
}