mirror of
https://github.com/chillpadclub/bedolaga-cabinet.git
synced 2026-07-28 09:33:46 +00:00
feat: extract promocodes and promo groups into separate pages
- Add AdminPromocodeCreate page for creating/editing promocodes - Add AdminPromoGroups page for listing discount groups - Add AdminPromoGroupCreate page for creating/editing discount groups - Move promo groups from Promocodes section to separate admin section - Simplify AdminPromocodes by removing embedded modals and groups tab - Add routes and navigation for new pages - Add i18n keys for all 4 locales (ru, en, zh, fa)
This commit is contained in:
53
src/App.tsx
53
src/App.tsx
@@ -41,6 +41,9 @@ const AdminBanSystem = lazy(() => import('./pages/AdminBanSystem'));
|
||||
const AdminBroadcasts = lazy(() => import('./pages/AdminBroadcasts'));
|
||||
const AdminBroadcastCreate = lazy(() => import('./pages/AdminBroadcastCreate'));
|
||||
const AdminPromocodes = lazy(() => import('./pages/AdminPromocodes'));
|
||||
const AdminPromocodeCreate = lazy(() => import('./pages/AdminPromocodeCreate'));
|
||||
const AdminPromoGroups = lazy(() => import('./pages/AdminPromoGroups'));
|
||||
const AdminPromoGroupCreate = lazy(() => import('./pages/AdminPromoGroupCreate'));
|
||||
const AdminCampaigns = lazy(() => import('./pages/AdminCampaigns'));
|
||||
const AdminCampaignCreate = lazy(() => import('./pages/AdminCampaignCreate'));
|
||||
const AdminUsers = lazy(() => import('./pages/AdminUsers'));
|
||||
@@ -370,6 +373,56 @@ function App() {
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/promocodes/create"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<LazyPage>
|
||||
<AdminPromocodeCreate />
|
||||
</LazyPage>
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/promocodes/:id/edit"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<LazyPage>
|
||||
<AdminPromocodeCreate />
|
||||
</LazyPage>
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/promo-groups"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<LazyPage>
|
||||
<AdminPromoGroups />
|
||||
</LazyPage>
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/promo-groups/create"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<LazyPage>
|
||||
<AdminPromoGroupCreate />
|
||||
</LazyPage>
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/promo-groups/:id/edit"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<LazyPage>
|
||||
<AdminPromoGroupCreate />
|
||||
</LazyPage>
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/campaigns"
|
||||
element={
|
||||
|
||||
@@ -737,7 +737,8 @@
|
||||
"paymentMethods": "Payment Methods",
|
||||
"campaigns": "Campaigns",
|
||||
"promoOffers": "Promo Offers",
|
||||
"promocodes": "Promo Codes"
|
||||
"promocodes": "Promo Codes",
|
||||
"promoGroups": "Discount Groups"
|
||||
},
|
||||
"panel": {
|
||||
"title": "Admin Panel",
|
||||
@@ -758,7 +759,8 @@
|
||||
"paymentMethodsDesc": "Configure payment methods and order",
|
||||
"campaignsDesc": "Advertising campaigns",
|
||||
"promoOffersDesc": "Personal discounts",
|
||||
"promocodesDesc": "Manage promo codes"
|
||||
"promocodesDesc": "Manage promo codes",
|
||||
"promoGroupsDesc": "Discount groups for users"
|
||||
},
|
||||
"emailTemplates": {
|
||||
"title": "Email Templates",
|
||||
@@ -1596,6 +1598,62 @@
|
||||
"deletePromocodeText": "The promo code will be permanently deleted.",
|
||||
"deleteGroupText": "The group will be deleted. Users will lose discounts from this group.",
|
||||
"deleteButton": "Delete"
|
||||
},
|
||||
"validation": {
|
||||
"codeRequired": "Enter promo code",
|
||||
"balanceRequired": "Bonus amount must be greater than 0",
|
||||
"daysRequired": "Number of days must be greater than 0",
|
||||
"groupRequired": "Select a discount group",
|
||||
"discountPercentInvalid": "Discount percent must be between 1 and 100",
|
||||
"discountHoursRequired": "Specify the discount validity period in hours"
|
||||
}
|
||||
},
|
||||
"promoGroups": {
|
||||
"title": "Discount Groups",
|
||||
"subtitle": "Manage discount groups for users",
|
||||
"addGroup": "Add Group",
|
||||
"noGroups": "No discount groups",
|
||||
"default": "Default",
|
||||
"servers": "Servers",
|
||||
"traffic": "Traffic",
|
||||
"devices": "Devices",
|
||||
"daysShort": "{{days}} days",
|
||||
"autoFrom": "Auto from {{amount}} rub.",
|
||||
"members": "{{count}} members",
|
||||
"createTitle": "Create Discount Group",
|
||||
"editTitle": "Edit Group",
|
||||
"stats": {
|
||||
"total": "Total groups",
|
||||
"members": "Members",
|
||||
"autoAssign": "With auto-assign"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "Delete group?",
|
||||
"text": "The group will be deleted. Users will lose discounts from this group.",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"form": {
|
||||
"name": "Group name",
|
||||
"namePlaceholder": "VIP customers",
|
||||
"categoryDiscounts": "Category discounts",
|
||||
"periodDiscounts": "Period discounts",
|
||||
"add": "Add",
|
||||
"periodHint": "Discount is applied when purchasing a subscription for the specified number of days",
|
||||
"noPeriods": "No period discounts",
|
||||
"daysPlaceholder": "Days",
|
||||
"arrow": "days →",
|
||||
"autoAssign": "Auto-assign when spent from",
|
||||
"rub": "rub.",
|
||||
"autoAssignHint": "0 = don't auto-assign",
|
||||
"applyToAddons": "Apply to additional services",
|
||||
"cancel": "Cancel",
|
||||
"saving": "Saving...",
|
||||
"save": "Save"
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
|
||||
@@ -626,6 +626,7 @@
|
||||
"payments": "پرداختها",
|
||||
"promoOffers": "پیشنهادات تبلیغاتی",
|
||||
"promocodes": "کدهای تخفیف",
|
||||
"promoGroups": "گروههای تخفیف",
|
||||
"remnawave": "RemnaWave",
|
||||
"users": "کاربران"
|
||||
},
|
||||
@@ -647,6 +648,7 @@
|
||||
"paymentsDesc": "تأیید پرداخت",
|
||||
"promoOffersDesc": "تخفیفهای شخصی",
|
||||
"promocodesDesc": "مدیریت کدهای تخفیف",
|
||||
"promoGroupsDesc": "گروههای تخفیف برای کاربران",
|
||||
"remnawaveDesc": "مدیریت پنل و آمار",
|
||||
"usersDesc": "مدیریت کاربران ربات"
|
||||
},
|
||||
@@ -1389,6 +1391,62 @@
|
||||
"deletePromocodeText": "کد تخفیف به طور دائم حذف خواهد شد.",
|
||||
"deleteGroupText": "گروه حذف خواهد شد. کاربران تخفیفهای این گروه را از دست خواهند داد.",
|
||||
"deleteButton": "حذف"
|
||||
},
|
||||
"validation": {
|
||||
"codeRequired": "کد تخفیف را وارد کنید",
|
||||
"balanceRequired": "مبلغ پاداش باید بیشتر از 0 باشد",
|
||||
"daysRequired": "تعداد روزها باید بیشتر از 0 باشد",
|
||||
"groupRequired": "یک گروه تخفیف انتخاب کنید",
|
||||
"discountPercentInvalid": "درصد تخفیف باید بین 1 تا 100 باشد",
|
||||
"discountHoursRequired": "مدت اعتبار تخفیف را به ساعت مشخص کنید"
|
||||
}
|
||||
},
|
||||
"promoGroups": {
|
||||
"title": "گروههای تخفیف",
|
||||
"subtitle": "مدیریت گروههای تخفیف برای کاربران",
|
||||
"addGroup": "افزودن گروه",
|
||||
"noGroups": "گروه تخفیفی وجود ندارد",
|
||||
"default": "پیشفرض",
|
||||
"servers": "سرورها",
|
||||
"traffic": "ترافیک",
|
||||
"devices": "دستگاهها",
|
||||
"daysShort": "{{days}} روز",
|
||||
"autoFrom": "خودکار از {{amount}} روبل",
|
||||
"members": "{{count}} عضو",
|
||||
"createTitle": "ایجاد گروه تخفیف",
|
||||
"editTitle": "ویرایش گروه",
|
||||
"stats": {
|
||||
"total": "کل گروهها",
|
||||
"members": "اعضا",
|
||||
"autoAssign": "با تخصیص خودکار"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "ویرایش",
|
||||
"delete": "حذف"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "گروه حذف شود؟",
|
||||
"text": "گروه حذف خواهد شد. کاربران تخفیفهای این گروه را از دست خواهند داد.",
|
||||
"cancel": "انصراف",
|
||||
"delete": "حذف"
|
||||
},
|
||||
"form": {
|
||||
"name": "نام گروه",
|
||||
"namePlaceholder": "مشتریان VIP",
|
||||
"categoryDiscounts": "تخفیفهای دستهبندی",
|
||||
"periodDiscounts": "تخفیفهای دورهای",
|
||||
"add": "افزودن",
|
||||
"periodHint": "تخفیف هنگام خرید اشتراک برای تعداد روز مشخص شده اعمال میشود",
|
||||
"noPeriods": "تخفیف دورهای وجود ندارد",
|
||||
"daysPlaceholder": "روز",
|
||||
"arrow": "روز ←",
|
||||
"autoAssign": "تخصیص خودکار هنگام هزینه از",
|
||||
"rub": "روبل",
|
||||
"autoAssignHint": "0 = تخصیص خودکار نشود",
|
||||
"applyToAddons": "اعمال به خدمات اضافی",
|
||||
"cancel": "انصراف",
|
||||
"saving": "در حال ذخیره...",
|
||||
"save": "ذخیره"
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
|
||||
@@ -753,7 +753,8 @@
|
||||
"paymentMethods": "Платёжные методы",
|
||||
"campaigns": "Кампании",
|
||||
"promoOffers": "Промопредложения",
|
||||
"promocodes": "Промокоды"
|
||||
"promocodes": "Промокоды",
|
||||
"promoGroups": "Группы скидок"
|
||||
},
|
||||
"panel": {
|
||||
"title": "Панель администратора",
|
||||
@@ -774,7 +775,8 @@
|
||||
"paymentMethodsDesc": "Настройка и порядок платежек",
|
||||
"campaignsDesc": "Рекламные кампании",
|
||||
"promoOffersDesc": "Персональные скидки",
|
||||
"promocodesDesc": "Управление промокодами"
|
||||
"promocodesDesc": "Управление промокодами",
|
||||
"promoGroupsDesc": "Группы скидок для пользователей"
|
||||
},
|
||||
"emailTemplates": {
|
||||
"title": "Email-шаблоны",
|
||||
@@ -2107,6 +2109,62 @@
|
||||
"deletePromocodeText": "Промокод будет удален безвозвратно.",
|
||||
"deleteGroupText": "Группа будет удалена. Пользователи потеряют скидки этой группы.",
|
||||
"deleteButton": "Удалить"
|
||||
},
|
||||
"validation": {
|
||||
"codeRequired": "Введите код промокода",
|
||||
"balanceRequired": "Сумма бонуса должна быть больше 0",
|
||||
"daysRequired": "Количество дней должно быть больше 0",
|
||||
"groupRequired": "Выберите группу скидок",
|
||||
"discountPercentInvalid": "Процент скидки должен быть от 1 до 100",
|
||||
"discountHoursRequired": "Укажите время действия скидки в часах"
|
||||
}
|
||||
},
|
||||
"promoGroups": {
|
||||
"title": "Группы скидок",
|
||||
"subtitle": "Управление группами скидок для пользователей",
|
||||
"addGroup": "Добавить группу",
|
||||
"noGroups": "Нет групп скидок",
|
||||
"default": "По умолчанию",
|
||||
"servers": "Серверы",
|
||||
"traffic": "Трафик",
|
||||
"devices": "Устройства",
|
||||
"daysShort": "{{days}} дн.",
|
||||
"autoFrom": "Авто от {{amount}} руб.",
|
||||
"members": "{{count}} участников",
|
||||
"createTitle": "Создание группы скидок",
|
||||
"editTitle": "Редактирование группы",
|
||||
"stats": {
|
||||
"total": "Всего групп",
|
||||
"members": "Участников",
|
||||
"autoAssign": "С авто-назначением"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Редактировать",
|
||||
"delete": "Удалить"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "Удалить группу?",
|
||||
"text": "Группа будет удалена. Пользователи потеряют скидки этой группы.",
|
||||
"cancel": "Отмена",
|
||||
"delete": "Удалить"
|
||||
},
|
||||
"form": {
|
||||
"name": "Название группы",
|
||||
"namePlaceholder": "VIP клиенты",
|
||||
"categoryDiscounts": "Скидки по категориям",
|
||||
"periodDiscounts": "Скидки по периодам",
|
||||
"add": "Добавить",
|
||||
"periodHint": "Скидка применяется при покупке подписки на указанное кол-во дней",
|
||||
"noPeriods": "Нет скидок по периодам",
|
||||
"daysPlaceholder": "Дни",
|
||||
"arrow": "дней →",
|
||||
"autoAssign": "Авто-назначение при тратах от",
|
||||
"rub": "руб.",
|
||||
"autoAssignHint": "0 = не назначать автоматически",
|
||||
"applyToAddons": "Применять к дополнительным услугам",
|
||||
"cancel": "Отмена",
|
||||
"saving": "Сохранение...",
|
||||
"save": "Сохранить"
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
|
||||
@@ -626,6 +626,7 @@
|
||||
"payments": "支付",
|
||||
"promoOffers": "促销优惠",
|
||||
"promocodes": "促销码",
|
||||
"promoGroups": "折扣组",
|
||||
"remnawave": "RemnaWave",
|
||||
"users": "用户"
|
||||
},
|
||||
@@ -647,6 +648,7 @@
|
||||
"paymentsDesc": "支付验证",
|
||||
"promoOffersDesc": "个性化折扣",
|
||||
"promocodesDesc": "管理促销码",
|
||||
"promoGroupsDesc": "用户折扣组",
|
||||
"remnawaveDesc": "面板管理和统计",
|
||||
"usersDesc": "管理机器人用户"
|
||||
},
|
||||
@@ -1388,6 +1390,62 @@
|
||||
"deletePromocodeText": "促销码将被永久删除。",
|
||||
"deleteGroupText": "该组将被删除。用户将失去该组的折扣。",
|
||||
"deleteButton": "删除"
|
||||
},
|
||||
"validation": {
|
||||
"codeRequired": "请输入促销码",
|
||||
"balanceRequired": "奖金金额必须大于0",
|
||||
"daysRequired": "天数必须大于0",
|
||||
"groupRequired": "请选择折扣组",
|
||||
"discountPercentInvalid": "折扣百分比必须在1到100之间",
|
||||
"discountHoursRequired": "请指定折扣有效期(小时)"
|
||||
}
|
||||
},
|
||||
"promoGroups": {
|
||||
"title": "折扣组",
|
||||
"subtitle": "管理用户折扣组",
|
||||
"addGroup": "添加组",
|
||||
"noGroups": "没有折扣组",
|
||||
"default": "默认",
|
||||
"servers": "服务器",
|
||||
"traffic": "流量",
|
||||
"devices": "设备",
|
||||
"daysShort": "{{days}} 天",
|
||||
"autoFrom": "自动 从 {{amount}} 卢布",
|
||||
"members": "{{count}} 名成员",
|
||||
"createTitle": "创建折扣组",
|
||||
"editTitle": "编辑组",
|
||||
"stats": {
|
||||
"total": "组总数",
|
||||
"members": "成员",
|
||||
"autoAssign": "自动分配"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "编辑",
|
||||
"delete": "删除"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "删除组?",
|
||||
"text": "该组将被删除。用户将失去该组的折扣。",
|
||||
"cancel": "取消",
|
||||
"delete": "删除"
|
||||
},
|
||||
"form": {
|
||||
"name": "组名称",
|
||||
"namePlaceholder": "VIP客户",
|
||||
"categoryDiscounts": "分类折扣",
|
||||
"periodDiscounts": "期间折扣",
|
||||
"add": "添加",
|
||||
"periodHint": "购买指定天数订阅时应用折扣",
|
||||
"noPeriods": "没有期间折扣",
|
||||
"daysPlaceholder": "天",
|
||||
"arrow": "天 →",
|
||||
"autoAssign": "消费满额自动分配",
|
||||
"rub": "卢布",
|
||||
"autoAssignHint": "0 = 不自动分配",
|
||||
"applyToAddons": "应用于附加服务",
|
||||
"cancel": "取消",
|
||||
"saving": "保存中...",
|
||||
"save": "保存"
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
|
||||
@@ -134,6 +134,16 @@ const GiftIcon = () => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
const UserGroupIcon = () => (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const MegaphoneIcon = () => (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path
|
||||
@@ -368,6 +378,12 @@ export default function AdminPanel() {
|
||||
title: t('admin.nav.promocodes'),
|
||||
description: t('admin.panel.promocodesDesc'),
|
||||
},
|
||||
{
|
||||
to: '/admin/promo-groups',
|
||||
icon: <UserGroupIcon />,
|
||||
title: t('admin.nav.promoGroups'),
|
||||
description: t('admin.panel.promoGroupsDesc'),
|
||||
},
|
||||
{
|
||||
to: '/admin/promo-offers',
|
||||
icon: <GiftIcon />,
|
||||
|
||||
409
src/pages/AdminPromoGroupCreate.tsx
Normal file
409
src/pages/AdminPromoGroupCreate.tsx
Normal file
@@ -0,0 +1,409 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
promocodesApi,
|
||||
PromoGroup,
|
||||
PromoGroupCreateRequest,
|
||||
PromoGroupUpdateRequest,
|
||||
} from '../api/promocodes';
|
||||
import { AdminBackButton } from '../components/admin';
|
||||
|
||||
// Icons
|
||||
const PlusIcon = () => (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
const TrashIcon = () => (
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const RefreshIcon = () => (
|
||||
<svg
|
||||
className="h-4 w-4 animate-spin"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
interface PeriodDiscount {
|
||||
days: number;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export default function AdminPromoGroupCreate() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const isEdit = !!id;
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('');
|
||||
const [serverDiscount, setServerDiscount] = useState<number | ''>(0);
|
||||
const [trafficDiscount, setTrafficDiscount] = useState<number | ''>(0);
|
||||
const [deviceDiscount, setDeviceDiscount] = useState<number | ''>(0);
|
||||
const [applyToAddons, setApplyToAddons] = useState(true);
|
||||
const [autoAssignSpent, setAutoAssignSpent] = useState<number | ''>(0);
|
||||
const [periodDiscounts, setPeriodDiscounts] = useState<PeriodDiscount[]>([]);
|
||||
|
||||
// Fetch promo group for editing
|
||||
const { isLoading: isLoadingGroup } = useQuery({
|
||||
queryKey: ['admin-promo-group', id],
|
||||
queryFn: () => promocodesApi.getPromoGroup(Number(id)),
|
||||
enabled: isEdit,
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
select: useCallback((data: PromoGroup) => {
|
||||
setName(data.name);
|
||||
setServerDiscount(data.server_discount_percent || 0);
|
||||
setTrafficDiscount(data.traffic_discount_percent || 0);
|
||||
setDeviceDiscount(data.device_discount_percent || 0);
|
||||
setApplyToAddons(data.apply_discounts_to_addons ?? true);
|
||||
setAutoAssignSpent(
|
||||
data.auto_assign_total_spent_kopeks ? data.auto_assign_total_spent_kopeks / 100 : 0,
|
||||
);
|
||||
if (data.period_discounts && typeof data.period_discounts === 'object') {
|
||||
setPeriodDiscounts(
|
||||
Object.entries(data.period_discounts).map(([days, percent]) => ({
|
||||
days: parseInt(days),
|
||||
percent: typeof percent === 'number' ? percent : 0,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return data;
|
||||
}, []),
|
||||
});
|
||||
|
||||
// Create mutation
|
||||
const createMutation = useMutation({
|
||||
mutationFn: promocodesApi.createPromoGroup,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-promo-groups'] });
|
||||
navigate('/admin/promo-groups');
|
||||
},
|
||||
});
|
||||
|
||||
// Update mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: PromoGroupUpdateRequest }) =>
|
||||
promocodesApi.updatePromoGroup(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-promo-groups'] });
|
||||
navigate('/admin/promo-groups');
|
||||
},
|
||||
});
|
||||
|
||||
const addPeriodDiscount = () => {
|
||||
setPeriodDiscounts([...periodDiscounts, { days: 30, percent: 0 }]);
|
||||
};
|
||||
|
||||
const removePeriodDiscount = (index: number) => {
|
||||
setPeriodDiscounts(periodDiscounts.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const updatePeriodDiscount = (index: number, field: 'days' | 'percent', value: number) => {
|
||||
const updated = [...periodDiscounts];
|
||||
updated[index][field] = value;
|
||||
setPeriodDiscounts(updated);
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
// Convert periodDiscounts array to Record<number, number>
|
||||
const periodDiscountsRecord: Record<number, number> = {};
|
||||
periodDiscounts.forEach((pd) => {
|
||||
if (pd.days > 0 && pd.percent > 0) {
|
||||
periodDiscountsRecord[pd.days] = pd.percent;
|
||||
}
|
||||
});
|
||||
|
||||
const serverVal = serverDiscount === '' ? 0 : serverDiscount;
|
||||
const trafficVal = trafficDiscount === '' ? 0 : trafficDiscount;
|
||||
const deviceVal = deviceDiscount === '' ? 0 : deviceDiscount;
|
||||
const autoAssignVal = autoAssignSpent === '' ? 0 : autoAssignSpent;
|
||||
|
||||
const data: PromoGroupCreateRequest | PromoGroupUpdateRequest = {
|
||||
name,
|
||||
server_discount_percent: serverVal,
|
||||
traffic_discount_percent: trafficVal,
|
||||
device_discount_percent: deviceVal,
|
||||
period_discounts:
|
||||
Object.keys(periodDiscountsRecord).length > 0 ? periodDiscountsRecord : undefined,
|
||||
apply_discounts_to_addons: applyToAddons,
|
||||
auto_assign_total_spent_kopeks: autoAssignVal > 0 ? Math.round(autoAssignVal * 100) : null,
|
||||
};
|
||||
|
||||
if (isEdit) {
|
||||
updateMutation.mutate({ id: Number(id), data });
|
||||
} else {
|
||||
createMutation.mutate(data as PromoGroupCreateRequest);
|
||||
}
|
||||
};
|
||||
|
||||
const isLoading = createMutation.isPending || updateMutation.isPending;
|
||||
const isValid = name.trim().length > 0;
|
||||
|
||||
// Loading state
|
||||
if (isEdit && isLoadingGroup) {
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<AdminBackButton to="/admin/promo-groups" />
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-100">
|
||||
{isEdit ? t('admin.promoGroups.editTitle') : t('admin.promoGroups.createTitle')}
|
||||
</h1>
|
||||
<p className="text-sm text-dark-400">{t('admin.promoGroups.subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="card space-y-4">
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promoGroups.form.name')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="input"
|
||||
placeholder={t('admin.promoGroups.form.namePlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category Discounts */}
|
||||
<div className="space-y-3 rounded-lg bg-dark-700/50 p-4">
|
||||
<h4 className="mb-3 text-sm font-medium text-dark-200">
|
||||
{t('admin.promoGroups.form.categoryDiscounts')}
|
||||
</h4>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-32 text-sm text-dark-400">{t('admin.promoGroups.servers')}:</span>
|
||||
<input
|
||||
type="number"
|
||||
value={serverDiscount}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setServerDiscount('');
|
||||
} else {
|
||||
setServerDiscount(Math.min(100, Math.max(0, parseInt(val) || 0)));
|
||||
}
|
||||
}}
|
||||
className="input w-20"
|
||||
min={0}
|
||||
max={100}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">%</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-32 text-sm text-dark-400">{t('admin.promoGroups.traffic')}:</span>
|
||||
<input
|
||||
type="number"
|
||||
value={trafficDiscount}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setTrafficDiscount('');
|
||||
} else {
|
||||
setTrafficDiscount(Math.min(100, Math.max(0, parseInt(val) || 0)));
|
||||
}
|
||||
}}
|
||||
className="input w-20"
|
||||
min={0}
|
||||
max={100}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">%</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-32 text-sm text-dark-400">{t('admin.promoGroups.devices')}:</span>
|
||||
<input
|
||||
type="number"
|
||||
value={deviceDiscount}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setDeviceDiscount('');
|
||||
} else {
|
||||
setDeviceDiscount(Math.min(100, Math.max(0, parseInt(val) || 0)));
|
||||
}
|
||||
}}
|
||||
className="input w-20"
|
||||
min={0}
|
||||
max={100}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Period Discounts */}
|
||||
<div className="space-y-3 rounded-lg bg-dark-700/50 p-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium text-dark-200">
|
||||
{t('admin.promoGroups.form.periodDiscounts')}
|
||||
</h4>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addPeriodDiscount}
|
||||
className="flex items-center gap-1 rounded bg-accent-500/20 px-2 py-1 text-xs text-accent-400 transition-colors hover:bg-accent-500/30"
|
||||
>
|
||||
<PlusIcon />
|
||||
{t('admin.promoGroups.form.add')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="mb-3 text-xs text-dark-500">{t('admin.promoGroups.form.periodHint')}</p>
|
||||
|
||||
{periodDiscounts.length === 0 ? (
|
||||
<p className="py-2 text-center text-sm text-dark-500">
|
||||
{t('admin.promoGroups.form.noPeriods')}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{periodDiscounts.map((pd, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={pd.days}
|
||||
onChange={(e) =>
|
||||
updatePeriodDiscount(
|
||||
index,
|
||||
'days',
|
||||
Math.max(1, parseInt(e.target.value) || 1),
|
||||
)
|
||||
}
|
||||
className="input w-20"
|
||||
min={1}
|
||||
placeholder={t('admin.promoGroups.form.daysPlaceholder')}
|
||||
/>
|
||||
<span className="text-xs text-dark-400">{t('admin.promoGroups.form.arrow')}</span>
|
||||
<input
|
||||
type="number"
|
||||
value={pd.percent}
|
||||
onChange={(e) =>
|
||||
updatePeriodDiscount(
|
||||
index,
|
||||
'percent',
|
||||
Math.min(100, Math.max(0, parseInt(e.target.value) || 0)),
|
||||
)
|
||||
}
|
||||
className="input w-20"
|
||||
min={0}
|
||||
max={100}
|
||||
placeholder="%"
|
||||
/>
|
||||
<span className="text-dark-400">%</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removePeriodDiscount(index)}
|
||||
className="p-1 text-dark-400 transition-colors hover:text-error-400"
|
||||
>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Auto-assign */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promoGroups.form.autoAssign')}
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={autoAssignSpent}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setAutoAssignSpent('');
|
||||
} else {
|
||||
setAutoAssignSpent(Math.max(0, parseFloat(val) || 0));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={0}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">{t('admin.promoGroups.form.rub')}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-dark-500">{t('admin.promoGroups.form.autoAssignHint')}</p>
|
||||
</div>
|
||||
|
||||
{/* Apply to addons */}
|
||||
<label className="flex cursor-pointer items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setApplyToAddons(!applyToAddons)}
|
||||
className={`relative h-6 w-10 rounded-full transition-colors ${
|
||||
applyToAddons ? 'bg-accent-500' : 'bg-dark-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-transform ${
|
||||
applyToAddons ? 'left-5' : 'left-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<span className="text-sm text-dark-200">{t('admin.promoGroups.form.applyToAddons')}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="card">
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => navigate('/admin/promo-groups')}
|
||||
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
||||
>
|
||||
{t('admin.promoGroups.form.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!isValid || isLoading}
|
||||
className="btn-primary flex items-center gap-2"
|
||||
>
|
||||
{isLoading && <RefreshIcon />}
|
||||
{isLoading ? t('admin.promoGroups.form.saving') : t('admin.promoGroups.form.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
222
src/pages/AdminPromoGroups.tsx
Normal file
222
src/pages/AdminPromoGroups.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { promocodesApi, PromoGroup } from '../api/promocodes';
|
||||
import { AdminBackButton } from '../components/admin';
|
||||
|
||||
// Icons
|
||||
const PlusIcon = () => (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
const EditIcon = () => (
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const TrashIcon = () => (
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const UsersIcon = () => (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default function AdminPromoGroups() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
|
||||
|
||||
// Query
|
||||
const { data: groupsData, isLoading } = useQuery({
|
||||
queryKey: ['admin-promo-groups'],
|
||||
queryFn: () => promocodesApi.getPromoGroups({ limit: 100 }),
|
||||
});
|
||||
|
||||
// Delete mutation
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: promocodesApi.deletePromoGroup,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-promo-groups'] });
|
||||
setDeleteConfirm(null);
|
||||
},
|
||||
});
|
||||
|
||||
const groups = groupsData?.items || [];
|
||||
|
||||
return (
|
||||
<div className="animate-fade-in">
|
||||
{/* Header */}
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<AdminBackButton />
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-dark-100">{t('admin.promoGroups.title')}</h1>
|
||||
<p className="text-sm text-dark-400">{t('admin.promoGroups.subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => navigate('/admin/promo-groups/create')}
|
||||
className="flex items-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
|
||||
>
|
||||
<PlusIcon />
|
||||
{t('admin.promoGroups.addGroup')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
{groups.length > 0 && (
|
||||
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
|
||||
<div className="text-2xl font-bold text-dark-100">{groups.length}</div>
|
||||
<div className="text-xs text-dark-400">{t('admin.promoGroups.stats.total')}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
|
||||
<div className="text-2xl font-bold text-accent-400">
|
||||
{groups.reduce((sum, g) => sum + g.members_count, 0)}
|
||||
</div>
|
||||
<div className="text-xs text-dark-400">{t('admin.promoGroups.stats.members')}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4">
|
||||
<div className="text-2xl font-bold text-warning-400">
|
||||
{groups.filter((g) => g.auto_assign_total_spent_kopeks).length}
|
||||
</div>
|
||||
<div className="text-xs text-dark-400">{t('admin.promoGroups.stats.autoAssign')}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* List */}
|
||||
{isLoading ? (
|
||||
<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>
|
||||
) : groups.length === 0 ? (
|
||||
<div className="py-12 text-center">
|
||||
<p className="text-dark-400">{t('admin.promoGroups.noGroups')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{groups.map((group: PromoGroup) => (
|
||||
<div key={group.id} className="rounded-xl border border-dark-700 bg-dark-800 p-4">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<h3 className="font-medium text-dark-100">{group.name}</h3>
|
||||
{group.is_default && (
|
||||
<span className="rounded bg-accent-500/20 px-2 py-0.5 text-xs text-accent-400">
|
||||
{t('admin.promoGroups.default')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-dark-400">
|
||||
{group.server_discount_percent > 0 && (
|
||||
<span>
|
||||
{t('admin.promoGroups.servers')}: -{group.server_discount_percent}%
|
||||
</span>
|
||||
)}
|
||||
{group.traffic_discount_percent > 0 && (
|
||||
<span>
|
||||
{t('admin.promoGroups.traffic')}: -{group.traffic_discount_percent}%
|
||||
</span>
|
||||
)}
|
||||
{group.device_discount_percent > 0 && (
|
||||
<span>
|
||||
{t('admin.promoGroups.devices')}: -{group.device_discount_percent}%
|
||||
</span>
|
||||
)}
|
||||
{group.period_discounts &&
|
||||
Object.keys(group.period_discounts).length > 0 &&
|
||||
Object.entries(group.period_discounts).map(([days, percent]) => (
|
||||
<span key={days} className="text-accent-400">
|
||||
{t('admin.promoGroups.daysShort', { days })}: -{percent}%
|
||||
</span>
|
||||
))}
|
||||
{group.auto_assign_total_spent_kopeks &&
|
||||
group.auto_assign_total_spent_kopeks > 0 && (
|
||||
<span className="text-warning-400">
|
||||
{t('admin.promoGroups.autoFrom', {
|
||||
amount: group.auto_assign_total_spent_kopeks / 100,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<UsersIcon />
|
||||
{t('admin.promoGroups.members', { count: group.members_count })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => navigate(`/admin/promo-groups/${group.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.promoGroups.actions.edit')}
|
||||
>
|
||||
<EditIcon />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(group.id)}
|
||||
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.promoGroups.actions.delete')}
|
||||
disabled={group.is_default}
|
||||
>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Delete Confirmation */}
|
||||
{deleteConfirm && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-sm rounded-xl bg-dark-800 p-6">
|
||||
<h3 className="mb-2 text-lg font-semibold text-dark-100">
|
||||
{t('admin.promoGroups.confirm.title')}
|
||||
</h3>
|
||||
<p className="mb-6 text-dark-400">{t('admin.promoGroups.confirm.text')}</p>
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(null)}
|
||||
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
||||
>
|
||||
{t('admin.promoGroups.confirm.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteMutation.mutate(deleteConfirm)}
|
||||
className="rounded-lg bg-error-500 px-4 py-2 text-white transition-colors hover:bg-error-600"
|
||||
>
|
||||
{t('admin.promoGroups.confirm.delete')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
490
src/pages/AdminPromocodeCreate.tsx
Normal file
490
src/pages/AdminPromocodeCreate.tsx
Normal file
@@ -0,0 +1,490 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
promocodesApi,
|
||||
PromoCodeDetail,
|
||||
PromoCodeType,
|
||||
PromoCodeCreateRequest,
|
||||
PromoCodeUpdateRequest,
|
||||
PromoGroup,
|
||||
} from '../api/promocodes';
|
||||
import { AdminBackButton } from '../components/admin';
|
||||
|
||||
// Icons
|
||||
const RefreshIcon = () => (
|
||||
<svg
|
||||
className="h-4 w-4 animate-spin"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
export default function AdminPromocodeCreate() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const isEdit = !!id;
|
||||
|
||||
// Form state
|
||||
const [code, setCode] = useState('');
|
||||
const [type, setType] = useState<PromoCodeType>('balance');
|
||||
const [balanceBonusRubles, setBalanceBonusRubles] = useState<number | ''>(0);
|
||||
const [subscriptionDays, setSubscriptionDays] = useState<number | ''>(0);
|
||||
const [maxUses, setMaxUses] = useState<number | ''>(1);
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
const [firstPurchaseOnly, setFirstPurchaseOnly] = useState(false);
|
||||
const [validUntil, setValidUntil] = useState('');
|
||||
const [promoGroupId, setPromoGroupId] = useState<number | null>(null);
|
||||
|
||||
// Fetch promo groups (for promo_group type)
|
||||
const { data: promoGroupsData } = useQuery({
|
||||
queryKey: ['admin-promo-groups'],
|
||||
queryFn: () => promocodesApi.getPromoGroups({ limit: 100 }),
|
||||
});
|
||||
|
||||
const promoGroups: PromoGroup[] = promoGroupsData?.items || [];
|
||||
|
||||
// Fetch promocode for editing
|
||||
const { isLoading: isLoadingPromocode } = useQuery({
|
||||
queryKey: ['admin-promocode', id],
|
||||
queryFn: () => promocodesApi.getPromocode(Number(id)),
|
||||
enabled: isEdit,
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
select: useCallback((data: PromoCodeDetail) => {
|
||||
setCode(data.code);
|
||||
setType(data.type);
|
||||
// For discount type, balance_bonus_kopeks is percentage directly
|
||||
// For balance type, balance_bonus_kopeks needs to be converted to rubles
|
||||
if (data.type === 'discount') {
|
||||
setBalanceBonusRubles(data.balance_bonus_kopeks);
|
||||
} else {
|
||||
setBalanceBonusRubles(data.balance_bonus_rubles || 0);
|
||||
}
|
||||
setSubscriptionDays(data.subscription_days || 0);
|
||||
setMaxUses(data.max_uses || 1);
|
||||
setIsActive(data.is_active ?? true);
|
||||
setFirstPurchaseOnly(data.first_purchase_only || false);
|
||||
setValidUntil(data.valid_until ? data.valid_until.split('T')[0] : '');
|
||||
setPromoGroupId(data.promo_group_id || null);
|
||||
return data;
|
||||
}, []),
|
||||
});
|
||||
|
||||
// Create mutation
|
||||
const createMutation = useMutation({
|
||||
mutationFn: promocodesApi.createPromocode,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-promocodes'] });
|
||||
navigate('/admin/promocodes');
|
||||
},
|
||||
});
|
||||
|
||||
// Update mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: PromoCodeUpdateRequest }) =>
|
||||
promocodesApi.updatePromocode(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-promocodes'] });
|
||||
navigate('/admin/promocodes');
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = () => {
|
||||
// For discount: balance_bonus_kopeks = percent (integer), subscription_days = hours
|
||||
// For balance: balance_bonus_kopeks = rubles * 100
|
||||
const balanceValue = balanceBonusRubles === '' ? 0 : balanceBonusRubles;
|
||||
const daysValue = subscriptionDays === '' ? 0 : subscriptionDays;
|
||||
const maxUsesValue = maxUses === '' ? 0 : maxUses;
|
||||
|
||||
const data: PromoCodeCreateRequest | PromoCodeUpdateRequest = {
|
||||
code: code.trim().toUpperCase(),
|
||||
type,
|
||||
balance_bonus_kopeks:
|
||||
type === 'discount'
|
||||
? Math.round(balanceValue) // percent as integer
|
||||
: Math.round(balanceValue * 100), // rubles to kopeks
|
||||
subscription_days: daysValue,
|
||||
max_uses: maxUsesValue,
|
||||
is_active: isActive,
|
||||
first_purchase_only: firstPurchaseOnly,
|
||||
valid_until: validUntil ? new Date(validUntil).toISOString() : null,
|
||||
promo_group_id: type === 'promo_group' ? promoGroupId : null,
|
||||
};
|
||||
|
||||
if (isEdit) {
|
||||
updateMutation.mutate({ id: Number(id), data });
|
||||
} else {
|
||||
createMutation.mutate(data as PromoCodeCreateRequest);
|
||||
}
|
||||
};
|
||||
|
||||
const isLoading = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
// Validation
|
||||
const isCodeValid = code.trim().length > 0;
|
||||
const balanceValue = balanceBonusRubles === '' ? 0 : balanceBonusRubles;
|
||||
const daysValue = subscriptionDays === '' ? 0 : subscriptionDays;
|
||||
|
||||
const isValid = (): boolean => {
|
||||
if (!isCodeValid) return false;
|
||||
if (type === 'balance' && balanceValue <= 0) return false;
|
||||
if ((type === 'subscription_days' || type === 'trial_subscription') && daysValue <= 0)
|
||||
return false;
|
||||
if (type === 'promo_group' && !promoGroupId) return false;
|
||||
if (type === 'discount' && (balanceValue <= 0 || balanceValue > 100 || daysValue <= 0))
|
||||
return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Collect validation errors for display
|
||||
const validationErrors: string[] = [];
|
||||
if (!isCodeValid) {
|
||||
validationErrors.push('codeRequired');
|
||||
}
|
||||
if (type === 'balance' && balanceValue <= 0) {
|
||||
validationErrors.push('balanceRequired');
|
||||
}
|
||||
if ((type === 'subscription_days' || type === 'trial_subscription') && daysValue <= 0) {
|
||||
validationErrors.push('daysRequired');
|
||||
}
|
||||
if (type === 'promo_group' && !promoGroupId) {
|
||||
validationErrors.push('groupRequired');
|
||||
}
|
||||
if (type === 'discount') {
|
||||
if (balanceValue <= 0 || balanceValue > 100) {
|
||||
validationErrors.push('discountPercentInvalid');
|
||||
}
|
||||
if (daysValue <= 0) {
|
||||
validationErrors.push('discountHoursRequired');
|
||||
}
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (isEdit && isLoadingPromocode) {
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<AdminBackButton to="/admin/promocodes" />
|
||||
<div>
|
||||
<h1 className="text-xl font-bold text-dark-100">
|
||||
{isEdit
|
||||
? t('admin.promocodes.modal.editPromocode')
|
||||
: t('admin.promocodes.modal.newPromocode')}
|
||||
</h1>
|
||||
<p className="text-sm text-dark-400">{t('admin.promocodes.subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="card space-y-4">
|
||||
{/* Code */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.code')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.toUpperCase())}
|
||||
className={`input uppercase ${!isCodeValid && code.length > 0 ? 'border-error-500/50' : ''}`}
|
||||
placeholder="SUMMER2025"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Type */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.type')}
|
||||
</label>
|
||||
<select
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as PromoCodeType)}
|
||||
className="input"
|
||||
>
|
||||
<option value="balance">{t('admin.promocodes.form.typeBalance')}</option>
|
||||
<option value="subscription_days">
|
||||
{t('admin.promocodes.form.typeSubscriptionDays')}
|
||||
</option>
|
||||
<option value="trial_subscription">
|
||||
{t('admin.promocodes.form.typeTrialSubscription')}
|
||||
</option>
|
||||
<option value="promo_group">{t('admin.promocodes.form.typePromoGroup')}</option>
|
||||
<option value="discount">{t('admin.promocodes.form.typeDiscount')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Type-specific fields */}
|
||||
{type === 'balance' && (
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.bonusAmount')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={balanceBonusRubles}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setBalanceBonusRubles('');
|
||||
} else {
|
||||
setBalanceBonusRubles(Math.max(0, parseFloat(val) || 0));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={0}
|
||||
step={1}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">{t('admin.promocodes.form.rub')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(type === 'subscription_days' || type === 'trial_subscription') && (
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.daysCount')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={subscriptionDays}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setSubscriptionDays('');
|
||||
} else {
|
||||
setSubscriptionDays(Math.max(0, parseInt(val) || 0));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={1}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">{t('admin.promocodes.form.days')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type === 'promo_group' && (
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.discountGroup')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={promoGroupId || ''}
|
||||
onChange={(e) => setPromoGroupId(e.target.value ? parseInt(e.target.value) : null)}
|
||||
className="input"
|
||||
>
|
||||
<option value="">{t('admin.promocodes.form.selectGroup')}</option>
|
||||
{promoGroups.map((group) => (
|
||||
<option key={group.id} value={group.id}>
|
||||
{group.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type === 'discount' && (
|
||||
<>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.discountPercent')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={balanceBonusRubles}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setBalanceBonusRubles('');
|
||||
} else {
|
||||
setBalanceBonusRubles(Math.min(100, Math.max(0, parseFloat(val) || 0)));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={1}
|
||||
max={100}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">%</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-dark-500">
|
||||
{t('admin.promocodes.form.discountHint')}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.validityPeriod')}
|
||||
<span className="text-error-400">*</span>
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={subscriptionDays}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setSubscriptionDays('');
|
||||
} else {
|
||||
setSubscriptionDays(Math.max(0, parseInt(val) || 0));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={1}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-dark-400">{t('admin.promocodes.form.hours')}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-dark-500">
|
||||
{t('admin.promocodes.form.validityHint')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Max Uses */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.maxUses')}
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
value={maxUses}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (val === '') {
|
||||
setMaxUses('');
|
||||
} else {
|
||||
setMaxUses(Math.max(0, parseInt(val) || 0));
|
||||
}
|
||||
}}
|
||||
className="input w-32"
|
||||
min={0}
|
||||
placeholder="0"
|
||||
/>
|
||||
<span className="text-xs text-dark-500">
|
||||
{t('admin.promocodes.form.unlimitedHint')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Valid Until */}
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-medium text-dark-300">
|
||||
{t('admin.promocodes.form.validUntil')}
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={validUntil}
|
||||
onChange={(e) => setValidUntil(e.target.value)}
|
||||
className="input"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-dark-500">{t('admin.promocodes.form.validUntilHint')}</p>
|
||||
</div>
|
||||
|
||||
{/* Options */}
|
||||
<div className="space-y-3">
|
||||
<label className="flex cursor-pointer items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsActive(!isActive)}
|
||||
className={`relative h-6 w-10 rounded-full transition-colors ${
|
||||
isActive ? 'bg-accent-500' : 'bg-dark-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-transform ${
|
||||
isActive ? 'left-5' : 'left-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<span className="text-sm text-dark-200">{t('admin.promocodes.form.active')}</span>
|
||||
</label>
|
||||
|
||||
<label className="flex cursor-pointer items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFirstPurchaseOnly(!firstPurchaseOnly)}
|
||||
className={`relative h-6 w-10 rounded-full transition-colors ${
|
||||
firstPurchaseOnly ? 'bg-accent-500' : 'bg-dark-600'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-transform ${
|
||||
firstPurchaseOnly ? 'left-5' : 'left-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<span className="text-sm text-dark-200">
|
||||
{t('admin.promocodes.form.firstPurchaseOnly')}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="card space-y-3">
|
||||
{validationErrors.length > 0 && (
|
||||
<div className="rounded-lg border border-error-500/30 bg-error-500/10 p-3">
|
||||
<p className="mb-1 text-sm font-medium text-error-400">
|
||||
{t('admin.tariffs.cannotSave')}
|
||||
</p>
|
||||
<ul className="list-inside list-disc space-y-1 text-xs text-error-300">
|
||||
{validationErrors.map((error) => (
|
||||
<li key={error}>{t(`admin.promocodes.validation.${error}`)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => navigate('/admin/promocodes')}
|
||||
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
||||
>
|
||||
{t('admin.promocodes.form.cancel')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!isValid() || isLoading}
|
||||
className="btn-primary flex items-center gap-2"
|
||||
>
|
||||
{isLoading && <RefreshIcon />}
|
||||
{isLoading ? t('admin.promocodes.form.saving') : t('admin.promocodes.form.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user