add tariff table, add edit tariff modal window

This commit is contained in:
smanylov
2026-05-29 18:43:37 +07:00
parent 96808c4a12
commit 8928960c34
7 changed files with 900 additions and 164 deletions
@@ -0,0 +1,223 @@
import { useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateTariffs } from '@/app/actions/tariffActions';
import { toast } from 'sonner';
import DropDownList from '@/app/components/dropDownList';
import { convertBytes } from '@/app/lib/convertBytes';
export interface EditingTariff {
id: number;
name: string;
type: string;
price: number;
tokens: number;
maxFilesCount: number;
diskSize: number;
maxUsers: number;
description: string;
tariffTerm: string;
}
export function TariffEditModal({ tariff, onClose, onSuccess }: {
tariff: EditingTariff;
onClose: () => void;
onSuccess: () => void;
}) {
const [formData, setFormData] = useState({
price: tariff.price,
name: tariff.name,
tokens: tariff.tokens,
maxFilesCount: tariff.maxFilesCount,
diskSize: tariff.diskSize,
maxUsers: tariff.maxUsers,
description: tariff.description,
tariffTerm: tariff.tariffTerm === 'YEAR' ? 'YEAR' : 'MONTHLY' as 'MONTHLY' | 'YEAR',
accountType: tariff.type.includes('TOKEN') ? 'token' : tariff.type.includes('STUDIO') ? 'b2b' : 'b2c' as 'b2c' | 'b2b' | 'token'
});
const updateTariffMutation = useMutation({
mutationFn: async () => {
return await updateTariffs(
tariff.id,
formData.price,
formData.name,
tariff.type,
formData.tokens,
formData.maxFilesCount,
formData.diskSize,
formData.maxUsers,
formData.description,
formData.tariffTerm,
formData.accountType
);
},
onSuccess: (data) => {
if (data !== null && data !== undefined) {
toast.success('Тариф успешно обновлен');
onSuccess();
} else {
toast.error('Не удалось обновить тариф');
}
},
onError: () => {
toast.error('Произошла ошибка при обновлении тарифа');
},
});
const handleSubmit = () => {
updateTariffMutation.mutate();
};
const handleChange = (field: string, value: any) => {
setFormData(prev => ({ ...prev, [field]: value }));
};
return (
<div className="tariff-edit-modal">
<h2 className="tariff-edit-modal__title">Редактирование тарифа</h2>
<div className="tariff-edit-modal__content">
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">ID тарифа</label>
<p className="tariff-edit-modal__value">{tariff.id}</p>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Тип тарифа</label>
<p className="tariff-edit-modal__value">{tariff.type}</p>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Название</label>
<input
type="text"
className="tariff-edit-modal__input"
value={formData.name}
onChange={(e) => handleChange('name', e.target.value)}
placeholder="Введите название тарифа"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Цена ()</label>
<input
type="number"
className="tariff-edit-modal__input"
value={formData.price}
onChange={(e) => handleChange('price', Number(e.target.value))}
placeholder="Введите цену"
min="0"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Количество токенов</label>
<input
type="number"
className="tariff-edit-modal__input"
value={formData.tokens}
onChange={(e) => handleChange('tokens', Number(e.target.value))}
placeholder="Введите количество токенов"
min="0"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Максимальное количество файлов</label>
<input
type="number"
className="tariff-edit-modal__input"
value={formData.maxFilesCount}
onChange={(e) => handleChange('maxFilesCount', Number(e.target.value))}
placeholder="Введите максимальное количество файлов"
min="0"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Размер диска</label>
<input
type="number"
className="tariff-edit-modal__input"
value={formData.diskSize}
onChange={(e) => handleChange('diskSize', Number(e.target.value))}
placeholder="Введите размер диска в ГБ"
min="0"
step="1"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Максимальное количество пользователей</label>
<input
type="number"
className="tariff-edit-modal__input"
value={formData.maxUsers}
onChange={(e) => handleChange('maxUsers', Number(e.target.value))}
placeholder="Введите максимальное количество пользователей"
min="0"
/>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Срок тарифа</label>
<DropDownList
value={formData.tariffTerm === 'YEAR' ? 'Год' : 'Месяц'}
callBack={(value: string) => {
handleChange('tariffTerm', value);
}}
>
<li value="MONTHLY">Месяц</li>
<li value="YEAR">Год</li>
</DropDownList>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Тип аккаунта</label>
<DropDownList
value={
formData.accountType === 'b2c' ? 'B2C' :
formData.accountType === 'b2b' ? 'B2B' : 'Token'
}
callBack={(value: string) => {
handleChange('accountType', value);
}}
>
<li value="b2c">B2C</li>
<li value="b2b">B2B</li>
<li value="token">Token</li>
</DropDownList>
</div>
<div className="tariff-edit-modal__info-section">
<label className="tariff-edit-modal__label">Описание</label>
<textarea
className="tariff-edit-modal__textarea"
value={formData.description}
onChange={(e) => handleChange('description', e.target.value)}
placeholder="Введите описание тарифа"
rows={4}
/>
</div>
<div className="tariff-edit-modal__actions">
<button
onClick={onClose}
className="btn btn-secondary"
disabled={updateTariffMutation.isPending}
>
Отмена
</button>
<button
onClick={handleSubmit}
className="btn btn-primary"
disabled={updateTariffMutation.isPending}
>
{updateTariffMutation.isPending ? 'Сохранение...' : 'Сохранить'}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,229 @@
'use client'
import { useTariffsData } from '@/app/hooks/react-query/useTariffsData';
import { useEffect, useState } from 'react';
import { convertBytes } from '@/app/lib/convertBytes';
import { IconDoubleArrowRight, IconArrowRight, IconDoubleArrowLeft, IconArrowLeft } from '@/app/ui/icons/icons';
import ModalWindow from '@/app/components/modalWindow';
import { useQueryClient } from '@tanstack/react-query';
import { EditingTariff, TariffEditModal } from './TariffEditModal'
export default function TariffManagment() {
const [currentPage, setCurrentPage] = useState(0);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingTariff, setEditingTariff] = useState<EditingTariff | null>(null);
const { data: tariffData, isLoading, isError, isFetching, error } = useTariffsData(currentPage);
const queryClient = useQueryClient();
useEffect(() => {
console.log(tariffData);
}, [tariffData])
useEffect(() => {
if (tariffData && tariffData.page !== currentPage) {
setCurrentPage(tariffData.page);
}
}, [tariffData, currentPage]);
const handlePageChange = (newPage: number) => {
if (tariffData && newPage >= 0 && newPage < tariffData.total_pages) {
setCurrentPage(newPage);
}
};
const handleEditClick = (tariff: any) => {
setEditingTariff({
id: tariff.id,
name: tariff.name,
type: tariff.type,
price: tariff.price,
tokens: tariff.tokens,
maxFilesCount: tariff.maxFilesCount,
diskSize: tariff.diskSize,
maxUsers: tariff.maxUsers,
description: tariff.description,
tariffTerm: tariff.tariffTerm
});
setIsModalOpen(true);
};
const formatPrice = (price: number) => {
return new Intl.NumberFormat('ru-RU').format(price);
};
const getDisplayName = (tariff: any) => {
if (tariff.name) {
return tariff.name.toUpperCase().replace(/_/g, ' ');
}
return tariff.type.replace(/_/g, ' ');
};
if (isLoading) {
return (
<div className="admin-content">
<div className="content-header">
<h3>Управление тарифными планами</h3>
</div>
<div className="content-body">
<div className="loading-spinner">Загрузка тарифов...</div>
</div>
</div>
);
}
if (isError) {
return (
<div className="admin-content">
<div className="content-header">
<h3>Управление тарифными планами</h3>
</div>
<div className="content-body">
<div className="error-message">
Ошибка загрузки тарифов: {error?.message || 'Неизвестная ошибка'}
</div>
</div>
</div>
);
}
return (
<div className="admin-content">
<div className="content-header">
<h3>Управление тарифными планами</h3>
<div className="content-header-actions">
<button className="btn btn-primary">
<span></span>
<span>Создать тариф</span>
</button>
</div>
</div>
<div className="content-body" id="plans-container">
<div className="stats-grid">
{tariffData?.tariffs?.map((tariff) => (
<div key={tariff.id} className="stat-card">
<div className="stat-card-header">
<span className="stat-card-title">{getDisplayName(tariff)}</span>
{tariff.tariffTerm && (
<span className="tariff-term-badge">{tariff.tariffTerm}</span>
)}
</div>
<div className="stat-card-value">{formatPrice(tariff.price)}</div>
<div className="stat-card-label">
{tariff.tokens > 0 && `${tariff.tokens.toLocaleString()} токенов`}
{tariff.diskSize > 0 && `${convertBytes(tariff.diskSize)}`}
{tariff.maxFilesCount > 0 && `${tariff.maxFilesCount} файлов`}
</div>
{tariff.description && (
<div className="stat-card-description">{tariff.description}</div>
)}
<div className="stat-card-footer">
<button
className="btn btn-outline btn-sm"
onClick={() => handleEditClick(tariff)}
>
Редактировать
</button>
</div>
</div>
))}
</div>
{/* Пагинация */}
{tariffData && tariffData.total_pages > 0 && (
<div className="tanstak-table-pagination">
<div className="pagination-info">
<span className="pagination-info-pages">
Страница{' '}
<strong>
{currentPage + 1} из {tariffData.total_pages}
</strong>
</span>
<span className="pagination-info-files">
| Показано {tariffData.tariffs?.length || 0} из {tariffData.total_elements}
</span>
</div>
<div className="pagination-controls">
<button
className="arrow"
onClick={() => handlePageChange(0)}
disabled={currentPage === 0 || isFetching}
>
<IconDoubleArrowLeft />
</button>
<button
className="arrow"
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 0 || isFetching}
>
<IconArrowLeft />
</button>
<div className="pagination-controls-pages">
{(() => {
const totalPages = tariffData.total_pages;
if (!totalPages || totalPages === 0) return null;
const maxVisiblePages = 5;
const visiblePagesCount = Math.min(maxVisiblePages, totalPages);
let startPage = currentPage - Math.floor(maxVisiblePages / 2);
startPage = Math.max(0, Math.min(startPage, totalPages - visiblePagesCount));
return Array.from({ length: visiblePagesCount }, (_, i) => {
const pageIndex = startPage + i;
return (
<button
key={pageIndex}
className={currentPage === pageIndex ? 'current' : 'other'}
onClick={() => handlePageChange(pageIndex)}
disabled={isFetching}
>
{pageIndex + 1}
</button>
);
});
})()}
</div>
<button
className="arrow"
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === tariffData.total_pages - 1 || isFetching}
>
<IconArrowRight />
</button>
<button
className="arrow"
onClick={() => handlePageChange(tariffData.total_pages - 1)}
disabled={currentPage === tariffData.total_pages - 1 || isFetching}
>
<IconDoubleArrowRight />
</button>
</div>
</div>
)}
{isFetching && !isLoading && (
<div className="refetching-indicator">Обновление...</div>
)}
</div>
{/* Модальное окно редактирования тарифа */}
<ModalWindow state={isModalOpen} callBack={setIsModalOpen}>
{editingTariff && (
<TariffEditModal
tariff={editingTariff}
onClose={() => setIsModalOpen(false)}
onSuccess={() => {
queryClient.invalidateQueries({ queryKey: ['tariffsData'] });
setIsModalOpen(false);
}}
/>
)}
</ModalWindow>
</div>
)
}