feat: add drag-and-drop tariff sorting in admin panel

Implement DnD reorder for tariffs using @dnd-kit, matching the
pattern from AdminPaymentMethods. Add updateOrder API method
and i18n keys for all locales.
This commit is contained in:
Fringg
2026-02-06 16:27:41 +03:00
committed by c0mrade
parent 57a97efa4b
commit ef365db16b
6 changed files with 286 additions and 113 deletions

View File

@@ -231,6 +231,11 @@ export const tariffsApi = {
return response.data; return response.data;
}, },
// Update tariff display order
updateOrder: async (tariffIds: number[]): Promise<void> => {
await apiClient.put('/cabinet/admin/tariffs/order', { tariff_ids: tariffIds });
},
// Get available servers for selection // Get available servers for selection
getAvailableServers: async (): Promise<ServerInfo[]> => { getAvailableServers: async (): Promise<ServerInfo[]> => {
const response = await apiClient.get('/cabinet/admin/tariffs/available-servers'); const response = await apiClient.get('/cabinet/admin/tariffs/available-servers');

View File

@@ -1306,6 +1306,9 @@
"confirmDeleteText": "This action cannot be undone. The tariff will be permanently deleted.", "confirmDeleteText": "This action cannot be undone. The tariff will be permanently deleted.",
"confirmDeleteWithSubscriptions": "This tariff has {{count}} active subscriptions. After deletion, users will need to select a new tariff when renewing.", "confirmDeleteWithSubscriptions": "This tariff has {{count}} active subscriptions. After deletion, users will need to select a new tariff when renewing.",
"deleteSuccess": "Tariff deleted successfully", "deleteSuccess": "Tariff deleted successfully",
"saveOrder": "Save order",
"orderSaved": "Order saved",
"dragToReorder": "Drag to reorder",
"days": "days", "days": "days",
"days_one": "{{count}} day", "days_one": "{{count}} day",
"days_other": "{{count}} days", "days_other": "{{count}} days",

View File

@@ -1012,6 +1012,9 @@
"confirmDeleteText": "این عمل قابل بازگشت نیست. تعرفه برای همیشه حذف می‌شود.", "confirmDeleteText": "این عمل قابل بازگشت نیست. تعرفه برای همیشه حذف می‌شود.",
"confirmDeleteWithSubscriptions": "این تعرفه {{count}} اشتراک فعال دارد. پس از حذف، کاربران هنگام تمدید باید تعرفه جدید انتخاب کنند.", "confirmDeleteWithSubscriptions": "این تعرفه {{count}} اشتراک فعال دارد. پس از حذف، کاربران هنگام تمدید باید تعرفه جدید انتخاب کنند.",
"deleteSuccess": "تعرفه با موفقیت حذف شد", "deleteSuccess": "تعرفه با موفقیت حذف شد",
"saveOrder": "ذخیره ترتیب",
"orderSaved": "ترتیب ذخیره شد",
"dragToReorder": "برای تغییر ترتیب بکشید",
"days": "روز", "days": "روز",
"days_other": "{{count}} روز", "days_other": "{{count}} روز",
"tabs": { "tabs": {

View File

@@ -1824,6 +1824,9 @@
"confirmDeleteText": "Это действие нельзя отменить. Тариф будет удалён навсегда.", "confirmDeleteText": "Это действие нельзя отменить. Тариф будет удалён навсегда.",
"confirmDeleteWithSubscriptions": "У этого тарифа {{count}} активных подписок. При удалении пользователям потребуется выбрать новый тариф при продлении.", "confirmDeleteWithSubscriptions": "У этого тарифа {{count}} активных подписок. При удалении пользователям потребуется выбрать новый тариф при продлении.",
"deleteSuccess": "Тариф успешно удален", "deleteSuccess": "Тариф успешно удален",
"saveOrder": "Сохранить порядок",
"orderSaved": "Порядок сохранён",
"dragToReorder": "Перетащите для изменения порядка",
"days": "дней", "days": "дней",
"days_one": "{{count}} день", "days_one": "{{count}} день",
"days_few": "{{count}} дня", "days_few": "{{count}} дня",

View File

@@ -1050,6 +1050,9 @@
"confirmDeleteText": "此操作不可撤销。套餐将被永久删除。", "confirmDeleteText": "此操作不可撤销。套餐将被永久删除。",
"confirmDeleteWithSubscriptions": "此套餐有 {{count}} 个活跃订阅。删除后,用户续订时需要选择新套餐。", "confirmDeleteWithSubscriptions": "此套餐有 {{count}} 个活跃订阅。删除后,用户续订时需要选择新套餐。",
"deleteSuccess": "套餐删除成功", "deleteSuccess": "套餐删除成功",
"saveOrder": "保存排序",
"orderSaved": "排序已保存",
"dragToReorder": "拖动以重新排序",
"days": "天", "days": "天",
"days_other": "{{count}} 天", "days_other": "{{count}} 天",
"tabs": { "tabs": {

View File

@@ -1,9 +1,26 @@
import { useState, useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { tariffsApi, TariffListItem } from '../api/tariffs'; import { tariffsApi, TariffListItem } from '../api/tariffs';
import { useDestructiveConfirm, useNotify } from '@/platform'; import { useDestructiveConfirm, useNotify } from '@/platform';
import { usePlatform } from '../platform/hooks/usePlatform'; import { usePlatform } from '../platform/hooks/usePlatform';
import {
DndContext,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
// Icons // Icons
const PlusIcon = () => ( const PlusIcon = () => (
@@ -54,7 +71,6 @@ const GiftIcon = () => (
</svg> </svg>
); );
// BackIcon
const BackIcon = () => ( const BackIcon = () => (
<svg <svg
className="h-5 w-5 text-dark-400" className="h-5 w-5 text-dark-400"
@@ -67,6 +83,168 @@ const BackIcon = () => (
</svg> </svg>
); );
const GripIcon = () => (
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
/>
</svg>
);
const SaveIcon = () => (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"
/>
</svg>
);
// ============ Sortable Tariff Card ============
interface SortableTariffCardProps {
tariff: TariffListItem;
onEdit: () => void;
onDelete: () => void;
onToggle: () => void;
onToggleTrial: () => void;
}
function SortableTariffCard({
tariff,
onEdit,
onDelete,
onToggle,
onToggleTrial,
}: SortableTariffCardProps) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: tariff.id,
});
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 50 : undefined,
position: isDragging ? 'relative' : undefined,
};
return (
<div
ref={setNodeRef}
style={style}
className={`rounded-xl border bg-dark-800 p-4 transition-colors ${
isDragging
? 'border-accent-500/50 shadow-xl shadow-accent-500/20'
: tariff.is_active
? 'border-dark-700'
: 'border-dark-700/50 opacity-60'
}`}
>
<div className="flex items-start gap-3">
{/* Drag handle */}
<button
{...attributes}
{...listeners}
className="mt-1 flex-shrink-0 cursor-grab touch-none rounded-lg p-2.5 text-dark-500 hover:bg-dark-700/50 hover:text-dark-300 active:cursor-grabbing sm:p-1.5"
title={t('admin.tariffs.dragToReorder')}
>
<GripIcon />
</button>
{/* Content */}
<div className="min-w-0 flex-1">
<div className="mb-1 flex items-center gap-2">
<h3 className="truncate font-medium text-dark-100">{tariff.name}</h3>
{tariff.is_daily ? (
<span className="rounded bg-warning-500/20 px-2 py-0.5 text-xs text-warning-400">
{t('admin.tariffs.dailyType')}
</span>
) : (
<span className="rounded bg-accent-500/20 px-2 py-0.5 text-xs text-accent-400">
{t('admin.tariffs.periodType')}
</span>
)}
{tariff.is_trial_available && (
<span className="rounded bg-success-500/20 px-2 py-0.5 text-xs text-success-400">
{t('admin.tariffs.trial')}
</span>
)}
{!tariff.is_active && (
<span className="rounded bg-dark-600 px-2 py-0.5 text-xs text-dark-400">
{t('admin.tariffs.inactive')}
</span>
)}
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-dark-400">
{tariff.is_daily && tariff.daily_price_kopeks > 0 && (
<span className="text-warning-400">
{(tariff.daily_price_kopeks / 100).toFixed(2)} {t('admin.tariffs.currencyPerDay')}
</span>
)}
<span>
{tariff.traffic_limit_gb === 0
? t('admin.tariffs.unlimited')
: `${tariff.traffic_limit_gb} GB`}
</span>
<span>{t('admin.tariffs.devices', { count: tariff.device_limit })}</span>
<span>{t('admin.tariffs.servers', { count: tariff.servers_count })}</span>
<span>{t('admin.tariffs.subscriptions', { count: tariff.subscriptions_count })}</span>
</div>
</div>
{/* Actions */}
<div className="flex items-center gap-2">
<button
onClick={onToggle}
className={`rounded-lg p-2 transition-colors ${
tariff.is_active
? 'bg-success-500/20 text-success-400 hover:bg-success-500/30'
: 'bg-dark-700 text-dark-400 hover:bg-dark-600'
}`}
title={tariff.is_active ? t('admin.tariffs.deactivate') : t('admin.tariffs.activate')}
>
{tariff.is_active ? <CheckIcon /> : <XIcon />}
</button>
<button
onClick={onToggleTrial}
className={`rounded-lg p-2 transition-colors ${
tariff.is_trial_available
? 'bg-accent-500/20 text-accent-400 hover:bg-accent-500/30'
: 'bg-dark-700 text-dark-400 hover:bg-dark-600'
}`}
title={t('admin.tariffs.toggleTrial')}
>
<GiftIcon />
</button>
<button
onClick={onEdit}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100"
title={t('admin.tariffs.edit')}
>
<EditIcon />
</button>
<button
onClick={onDelete}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-error-500/20 hover:text-error-400"
title={t('admin.tariffs.delete')}
>
<TrashIcon />
</button>
</div>
</div>
</div>
);
}
// ============ Main Page ============
export default function AdminTariffs() { export default function AdminTariffs() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -75,12 +253,32 @@ export default function AdminTariffs() {
const notify = useNotify(); const notify = useNotify();
const { capabilities } = usePlatform(); const { capabilities } = usePlatform();
const [localTariffs, setLocalTariffs] = useState<TariffListItem[]>([]);
const [orderChanged, setOrderChanged] = useState(false);
// Queries // Queries
const { data: tariffsData, isLoading } = useQuery({ const { data: tariffsData, isLoading } = useQuery({
queryKey: ['admin-tariffs'], queryKey: ['admin-tariffs'],
queryFn: () => tariffsApi.getTariffs(true), queryFn: () => tariffsApi.getTariffs(true),
}); });
// Sync fetched data to local state
useEffect(() => {
if (tariffsData?.tariffs && !orderChanged) {
setLocalTariffs(tariffsData.tariffs);
}
}, [tariffsData, orderChanged]);
// Save order mutation
const saveOrderMutation = useMutation({
mutationFn: (tariffIds: number[]) => tariffsApi.updateOrder(tariffIds),
onSuccess: () => {
setOrderChanged(false);
queryClient.invalidateQueries({ queryKey: ['admin-tariffs'] });
notify.success(t('admin.tariffs.orderSaved'));
},
});
// Mutations // Mutations
const deleteMutation = useMutation({ const deleteMutation = useMutation({
mutationFn: tariffsApi.deleteTariff, mutationFn: tariffsApi.deleteTariff,
@@ -91,7 +289,6 @@ export default function AdminTariffs() {
}); });
const handleDelete = async (tariff: TariffListItem) => { const handleDelete = async (tariff: TariffListItem) => {
// If tariff has active subscriptions, show warning but still allow deletion
const confirmText = const confirmText =
tariff.subscriptions_count > 0 tariff.subscriptions_count > 0
? t('admin.tariffs.confirmDeleteWithSubscriptions', { ? t('admin.tariffs.confirmDeleteWithSubscriptions', {
@@ -124,7 +321,28 @@ export default function AdminTariffs() {
}, },
}); });
const tariffs = tariffsData?.tariffs || []; // DnD sensors
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const handleDragEnd = useCallback((event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
setLocalTariffs((prev) => {
const oldIndex = prev.findIndex((t) => t.id === active.id);
const newIndex = prev.findIndex((t) => t.id === over.id);
if (oldIndex === -1 || newIndex === -1) return prev;
return arrayMove(prev, oldIndex, newIndex);
});
setOrderChanged(true);
}
}, []);
const handleSaveOrder = () => {
saveOrderMutation.mutate(localTariffs.map((t) => t.id));
};
return ( return (
<div className="animate-fade-in"> <div className="animate-fade-in">
@@ -145,13 +363,35 @@ export default function AdminTariffs() {
<p className="text-sm text-dark-400">{t('admin.tariffs.subtitle')}</p> <p className="text-sm text-dark-400">{t('admin.tariffs.subtitle')}</p>
</div> </div>
</div> </div>
<button <div className="flex items-center gap-2">
onClick={() => navigate('/admin/tariffs/create')} {orderChanged && (
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600" <button
> onClick={handleSaveOrder}
<PlusIcon /> disabled={saveOrderMutation.isPending}
{t('admin.tariffs.create')} className="flex items-center gap-2 rounded-lg bg-success-500 px-4 py-2 text-white transition-colors hover:bg-success-600"
</button> >
{saveOrderMutation.isPending ? (
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
) : (
<SaveIcon />
)}
{t('admin.tariffs.saveOrder')}
</button>
)}
<button
onClick={() => navigate('/admin/tariffs/create')}
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
>
<PlusIcon />
{t('admin.tariffs.create')}
</button>
</div>
</div>
{/* Drag hint */}
<div className="mb-4 flex items-center gap-2 text-sm text-dark-500">
<GripIcon />
{t('admin.tariffs.dragToReorder')}
</div> </div>
{/* Tariffs List */} {/* Tariffs List */}
@@ -159,114 +399,30 @@ export default function AdminTariffs() {
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" /> <div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
</div> </div>
) : tariffs.length === 0 ? ( ) : localTariffs.length === 0 ? (
<div className="py-12 text-center"> <div className="py-12 text-center">
<p className="text-dark-400">{t('admin.tariffs.noTariffs')}</p> <p className="text-dark-400">{t('admin.tariffs.noTariffs')}</p>
</div> </div>
) : ( ) : (
<div className="space-y-3"> <DndContext sensors={sensors} onDragEnd={handleDragEnd}>
{tariffs.map((tariff: TariffListItem) => ( <SortableContext
<div items={localTariffs.map((t) => t.id)}
key={tariff.id} strategy={verticalListSortingStrategy}
className={`rounded-xl border bg-dark-800 p-4 transition-colors ${ >
tariff.is_active ? 'border-dark-700' : 'border-dark-700/50 opacity-60' <div className="space-y-3">
}`} {localTariffs.map((tariff) => (
> <SortableTariffCard
<div className="flex items-start justify-between gap-4"> key={tariff.id}
<div className="min-w-0 flex-1"> tariff={tariff}
<div className="mb-1 flex items-center gap-2"> onEdit={() => navigate(`/admin/tariffs/${tariff.id}/edit`)}
<h3 className="truncate font-medium text-dark-100">{tariff.name}</h3> onDelete={() => handleDelete(tariff)}
{tariff.is_daily ? ( onToggle={() => toggleMutation.mutate(tariff.id)}
<span className="rounded bg-warning-500/20 px-2 py-0.5 text-xs text-warning-400"> onToggleTrial={() => toggleTrialMutation.mutate(tariff.id)}
{t('admin.tariffs.dailyType')} />
</span> ))}
) : (
<span className="rounded bg-accent-500/20 px-2 py-0.5 text-xs text-accent-400">
{t('admin.tariffs.periodType')}
</span>
)}
{tariff.is_trial_available && (
<span className="rounded bg-success-500/20 px-2 py-0.5 text-xs text-success-400">
{t('admin.tariffs.trial')}
</span>
)}
{!tariff.is_active && (
<span className="rounded bg-dark-600 px-2 py-0.5 text-xs text-dark-400">
{t('admin.tariffs.inactive')}
</span>
)}
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-dark-400">
{tariff.is_daily && tariff.daily_price_kopeks > 0 && (
<span className="text-warning-400">
{(tariff.daily_price_kopeks / 100).toFixed(2)}{' '}
{t('admin.tariffs.currencyPerDay')}
</span>
)}
<span>
{tariff.traffic_limit_gb === 0
? t('admin.tariffs.unlimited')
: `${tariff.traffic_limit_gb} GB`}
</span>
<span>{t('admin.tariffs.devices', { count: tariff.device_limit })}</span>
<span>{t('admin.tariffs.servers', { count: tariff.servers_count })}</span>
<span>
{t('admin.tariffs.subscriptions', { count: tariff.subscriptions_count })}
</span>
</div>
</div>
<div className="flex items-center gap-2">
{/* Toggle Active */}
<button
onClick={() => toggleMutation.mutate(tariff.id)}
className={`rounded-lg p-2 transition-colors ${
tariff.is_active
? 'bg-success-500/20 text-success-400 hover:bg-success-500/30'
: 'bg-dark-700 text-dark-400 hover:bg-dark-600'
}`}
title={
tariff.is_active ? t('admin.tariffs.deactivate') : t('admin.tariffs.activate')
}
>
{tariff.is_active ? <CheckIcon /> : <XIcon />}
</button>
{/* Toggle Trial */}
<button
onClick={() => toggleTrialMutation.mutate(tariff.id)}
className={`rounded-lg p-2 transition-colors ${
tariff.is_trial_available
? 'bg-accent-500/20 text-accent-400 hover:bg-accent-500/30'
: 'bg-dark-700 text-dark-400 hover:bg-dark-600'
}`}
title={t('admin.tariffs.toggleTrial')}
>
<GiftIcon />
</button>
{/* Edit */}
<button
onClick={() => navigate(`/admin/tariffs/${tariff.id}/edit`)}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100"
title={t('admin.tariffs.edit')}
>
<EditIcon />
</button>
{/* Delete */}
<button
onClick={() => handleDelete(tariff)}
className="rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-error-500/20 hover:text-error-400"
title={t('admin.tariffs.delete')}
>
<TrashIcon />
</button>
</div>
</div>
</div> </div>
))} </SortableContext>
</div> </DndContext>
)} )}
</div> </div>
); );