crud coupon
This commit is contained in:
@@ -59,7 +59,7 @@ const PaginationUi: FC<PaginationUiProps> = ({ pager, onPageChange }) => {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex ی justify-center mt-6">
|
||||
<div className="flex justify-center mt-6">
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
{getPageNumbers().map((page, index) => (
|
||||
|
||||
@@ -35,7 +35,7 @@ const ProductMultiSelect: React.FC<ProductMultiSelectProps> = ({
|
||||
}, [searchTerm])
|
||||
|
||||
// Search products (includes initial load and search)
|
||||
const { data: searchResults, isLoading } = useSearchProducts(debouncedSearchTerm, dropdownOpen)
|
||||
const { data: searchResults, isLoading } = useSearchProducts(debouncedSearchTerm, true)
|
||||
|
||||
// Combine selected products with search results
|
||||
const allProducts = useMemo(() => {
|
||||
|
||||
+297
-2
@@ -1,8 +1,303 @@
|
||||
import { type FC } from 'react'
|
||||
import { useFormik } from 'formik'
|
||||
import { type FC, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { type CreateCouponType } from './types/Types'
|
||||
import * as Yup from 'yup'
|
||||
import { useGetCouponDetail, useUpdateCoupon } from './hooks/useCouponData'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useGetCategories, type CategoryTreeNode } from '../category'
|
||||
import Input from '../../components/Input'
|
||||
import DatePicker from '../../components/DatePicker'
|
||||
import Switch from '../../components/Switch'
|
||||
import Button from '../../components/Button'
|
||||
import Textarea from '../../components/Textarea'
|
||||
import MultiSelectSearchable from '../../components/MultiSelectSearchable'
|
||||
import ProductMultiSelect from '../../components/ProductMultiSelect'
|
||||
import { TickCircle } from 'iconsax-react'
|
||||
import { toast } from 'react-toastify'
|
||||
import { extractErrorMessage } from '@/helpers/utils'
|
||||
import { Pages } from '../../config/Pages'
|
||||
|
||||
const UpdateCoupon: FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { data } = useGetCouponDetail(id!)
|
||||
const { data: categoriesData } = useGetCategories()
|
||||
const updateCouponMutation = useUpdateCoupon()
|
||||
const hasInitialized = useRef(false)
|
||||
|
||||
const formik = useFormik<CreateCouponType>({
|
||||
initialValues: {
|
||||
couponId: id,
|
||||
discountPercentage: 0,
|
||||
discountAmount: 0,
|
||||
usageLimit: 1,
|
||||
userUsageLimit: 1,
|
||||
minPurchaseAmount: 0,
|
||||
category: [],
|
||||
includedProducts: [],
|
||||
excludedProducts: [],
|
||||
description: '',
|
||||
includeSpecialSale: false,
|
||||
expirationDate: '',
|
||||
},
|
||||
validationSchema: Yup.object({
|
||||
usageLimit: Yup.number().min(1, 'محدودیت استفاده باید حداقل ۱ باشد').required('محدودیت استفاده الزامی است'),
|
||||
userUsageLimit: Yup.number().min(1, 'محدودیت استفاده کاربر باید حداقل ۱ باشد').required('محدودیت استفاده کاربر الزامی است'),
|
||||
description: Yup.string().required('توضیحات کوپن الزامی است'),
|
||||
expirationDate: Yup.string().required('تاریخ انقضا الزامی است'),
|
||||
discountPercentage: Yup.number().optional(),
|
||||
discountAmount: Yup.number().optional(),
|
||||
minPurchaseAmount: Yup.number().min(0, 'حداقل مبلغ خرید نمیتواند منفی باشد').optional(),
|
||||
includedProducts: Yup.array().optional(),
|
||||
excludedProducts: Yup.array().optional(),
|
||||
}).test('at-least-one-discount', 'درصد تخفیف یا مبلغ تخفیف الزامی است', function (value) {
|
||||
const { discountPercentage, discountAmount } = value;
|
||||
|
||||
// چک کردن اینکه حداقل یکی از دو فیلد پر شده باشد
|
||||
if ((!discountPercentage || discountPercentage === 0) && (!discountAmount || discountAmount === 0)) {
|
||||
return this.createError({
|
||||
path: 'discountPercentage',
|
||||
message: 'درصد تخفیف یا مبلغ تخفیف الزامی است',
|
||||
});
|
||||
}
|
||||
|
||||
// چک کردن اینکه هر دو فیلد همزمان پر نشده باشند
|
||||
if ((discountPercentage && discountPercentage > 0) && (discountAmount && discountAmount > 0)) {
|
||||
return this.createError({
|
||||
path: 'discountPercentage',
|
||||
message: 'نباید هر دو مقدار مبلغ تخفیف و درصد را وارد کنید',
|
||||
});
|
||||
}
|
||||
|
||||
if (discountPercentage && (discountPercentage < 1 || discountPercentage > 100)) {
|
||||
return this.createError({
|
||||
path: 'discountPercentage',
|
||||
message: 'درصد تخفیف باید بین ۱ تا ۱۰۰ باشد',
|
||||
});
|
||||
}
|
||||
|
||||
if (discountAmount && discountAmount < 1) {
|
||||
return this.createError({
|
||||
path: 'discountAmount',
|
||||
message: 'مبلغ تخفیف باید حداقل ۱ باشد',
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}).test('products-validation', 'محصولات شامل و مستثنی نمیتوانند همزمان انتخاب شوند', function (value) {
|
||||
const { includedProducts, excludedProducts } = value;
|
||||
|
||||
// چک کردن اینکه هر دو فیلد همزمان پر نشده باشند
|
||||
if (includedProducts && includedProducts.length > 0 && excludedProducts && excludedProducts.length > 0) {
|
||||
return this.createError({
|
||||
path: 'includedProducts',
|
||||
message: 'نباید هر دو مقدار محصولات شامل و محصولات مستثنی را وارد کنید',
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
}),
|
||||
onSubmit: async (values) => {
|
||||
// تبدیل مقادیر به نوع مناسب
|
||||
// اگر هر دو فیلد تخفیف پر شده باشند، فقط یکی را ارسال میکنیم
|
||||
let discountPercentage: number | undefined
|
||||
let discountAmount: number | undefined
|
||||
|
||||
if (values.discountPercentage && values.discountPercentage > 0) {
|
||||
discountPercentage = Number(values.discountPercentage)
|
||||
discountAmount = undefined
|
||||
} else if (values.discountAmount && values.discountAmount > 0) {
|
||||
discountAmount = Number(values.discountAmount)
|
||||
discountPercentage = undefined
|
||||
} else {
|
||||
discountPercentage = undefined
|
||||
discountAmount = undefined
|
||||
}
|
||||
|
||||
const submitData = {
|
||||
...values,
|
||||
usageLimit: Number(values.usageLimit),
|
||||
userUsageLimit: Number(values.userUsageLimit),
|
||||
discountPercentage,
|
||||
discountAmount,
|
||||
minPurchaseAmount: values.minPurchaseAmount ? Number(values.minPurchaseAmount) : undefined,
|
||||
includedProducts: values.includedProducts?.length ? values.includedProducts : undefined,
|
||||
excludedProducts: values.excludedProducts?.length ? values.excludedProducts : undefined,
|
||||
}
|
||||
|
||||
updateCouponMutation.mutate(submitData, {
|
||||
onSuccess: () => {
|
||||
toast.success('کوپن با موفقیت بروزرسانی شد')
|
||||
navigate(Pages.coupon.list)
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(extractErrorMessage(error))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// بروزرسانی initialValues وقتی دادهها از API دریافت شوند
|
||||
useEffect(() => {
|
||||
if (data?.results?.coupon && !hasInitialized.current) {
|
||||
const coupon = data.results.coupon
|
||||
formik.setValues({
|
||||
couponId: coupon._id,
|
||||
discountPercentage: coupon.discountPercentage || 0,
|
||||
discountAmount: coupon.discountAmount || 0,
|
||||
usageLimit: coupon.usageLimit,
|
||||
userUsageLimit: coupon.userUsageLimit,
|
||||
minPurchaseAmount: coupon.minPurchaseAmount || 0,
|
||||
category: coupon.category || [],
|
||||
includedProducts: coupon.includedProducts || [],
|
||||
excludedProducts: coupon.excludedProducts || [],
|
||||
description: coupon.description,
|
||||
includeSpecialSale: coupon.includeSpecialSale,
|
||||
expirationDate: coupon.expirationDate,
|
||||
})
|
||||
hasInitialized.current = true
|
||||
}
|
||||
}, [data, formik])
|
||||
|
||||
const categoryOptions = categoriesData?.results?.data?.map((category: CategoryTreeNode) => ({
|
||||
value: category._id,
|
||||
label: category.title_fa
|
||||
})) || []
|
||||
|
||||
if (!data) {
|
||||
return <div>در حال بارگذاری...</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div>UpdateCoupon</div>
|
||||
<div className='mt-4'>
|
||||
<div className='flex justify-between items-center'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<h1>ویرایش کوپن</h1>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
className='px-6'
|
||||
onClick={() => formik.handleSubmit()}
|
||||
isLoading={updateCouponMutation.isPending}
|
||||
disabled={!formik.isValid || updateCouponMutation.isPending}
|
||||
>
|
||||
<div className='flex gap-2 items-center'>
|
||||
<TickCircle size={16} color='#fff' />
|
||||
<div>بروزرسانی کوپن</div>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex gap-6 xl:mt-8 mt-6'>
|
||||
{/* اطلاعات اصلی */}
|
||||
<div className='flex-1 text-sm bg-white py-8 xl:px-10 px-6 rounded-3xl'>
|
||||
<h2 className='text-lg font-medium mb-6'>اطلاعات اصلی</h2>
|
||||
|
||||
<div className='space-y-6'>
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
|
||||
<Input
|
||||
label='درصد تخفیف'
|
||||
placeholder='مثال: ۱۰'
|
||||
type='number'
|
||||
{...formik.getFieldProps('discountPercentage')}
|
||||
error_text={(formik.touched.discountPercentage || formik.touched.discountAmount) && formik.errors.discountPercentage ? formik.errors.discountPercentage : ''}
|
||||
/>
|
||||
<Input
|
||||
label='مبلغ تخفیف (تومان)'
|
||||
placeholder='مثال: ۵۰۰۰'
|
||||
type='number'
|
||||
{...formik.getFieldProps('discountAmount')}
|
||||
error_text={(formik.touched.discountPercentage || formik.touched.discountAmount) && formik.errors.discountAmount ? formik.errors.discountAmount : ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
|
||||
<Input
|
||||
label='محدودیت استفاده کل'
|
||||
placeholder='مثال: ۱۰۰'
|
||||
type='number'
|
||||
{...formik.getFieldProps('usageLimit')}
|
||||
error_text={formik.touched.usageLimit && formik.errors.usageLimit ? formik.errors.usageLimit : ''}
|
||||
/>
|
||||
<Input
|
||||
label='محدودیت استفاده هر کاربر'
|
||||
placeholder='مثال: ۵'
|
||||
type='number'
|
||||
{...formik.getFieldProps('userUsageLimit')}
|
||||
error_text={formik.touched.userUsageLimit && formik.errors.userUsageLimit ? formik.errors.userUsageLimit : ''}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label='حداقل مبلغ خرید (تومان)'
|
||||
placeholder='مثال: ۱۰۰۰۰'
|
||||
type='number'
|
||||
{...formik.getFieldProps('minPurchaseAmount')}
|
||||
error_text={formik.touched.minPurchaseAmount && formik.errors.minPurchaseAmount ? formik.errors.minPurchaseAmount : ''}
|
||||
/>
|
||||
|
||||
<DatePicker
|
||||
label='تاریخ انقضا'
|
||||
placeholder='انتخاب تاریخ'
|
||||
defaulValue={formik.values.expirationDate}
|
||||
onChange={(date) => formik.setFieldValue('expirationDate', date)}
|
||||
error_text={formik.touched.expirationDate && formik.errors.expirationDate ? formik.errors.expirationDate : ''}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label='توضیحات کوپن'
|
||||
placeholder='توضیحات کامل کوپن را وارد کنید...'
|
||||
{...formik.getFieldProps('description')}
|
||||
error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
|
||||
/>
|
||||
|
||||
<div className='flex items-center gap-3'>
|
||||
<Switch
|
||||
active={formik.values.includeSpecialSale}
|
||||
onChange={(value) => formik.setFieldValue('includeSpecialSale', value)}
|
||||
label='شامل فروش ویژه'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* تنظیمات پیشرفته */}
|
||||
<div className='w-80 space-y-6'>
|
||||
<div className='text-sm bg-white py-8 px-6 rounded-3xl'>
|
||||
<h2 className='text-lg font-medium mb-6'>تنظیمات پیشرفته</h2>
|
||||
|
||||
<div className='space-y-6'>
|
||||
<MultiSelectSearchable
|
||||
label='دستهبندیهای مجاز'
|
||||
placeholder='انتخاب دستهبندیها'
|
||||
options={categoryOptions}
|
||||
value={formik.values.category || []}
|
||||
onChange={(value) => formik.setFieldValue('category', value)}
|
||||
error_text={formik.touched.category && formik.errors.category ? formik.errors.category : ''}
|
||||
/>
|
||||
|
||||
<ProductMultiSelect
|
||||
label='محصولات شامل تخفیف'
|
||||
placeholder='انتخاب محصولات شامل تخفیف'
|
||||
value={formik.values.includedProducts || []}
|
||||
onChange={(value) => formik.setFieldValue('includedProducts', value)}
|
||||
error_text={formik.touched.includedProducts && formik.errors.includedProducts ? formik.errors.includedProducts : ''}
|
||||
/>
|
||||
|
||||
<ProductMultiSelect
|
||||
label='محصولات مستثنی از تخفیف'
|
||||
placeholder='انتخاب محصولات مستثنی از تخفیف'
|
||||
value={formik.values.excludedProducts || []}
|
||||
onChange={(value) => formik.setFieldValue('excludedProducts', value)}
|
||||
error_text={formik.touched.excludedProducts && formik.errors.excludedProducts ? formik.errors.excludedProducts : ''}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -30,3 +30,21 @@ export const useDeleteCoupon = () => {
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useGetCouponDetail = (couponId: string) => {
|
||||
return useQuery({
|
||||
queryKey: ["coupon", couponId],
|
||||
queryFn: () => api.getCouponDetail(couponId),
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateCoupon = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: api.updateCoupon,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["coupons"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["coupon"] });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
CreateCouponType,
|
||||
CouponType,
|
||||
CouponsResponse,
|
||||
GetCouponDetailResponseType,
|
||||
} from "../types/Types";
|
||||
|
||||
export const getCoupons = async (
|
||||
@@ -22,3 +23,20 @@ export const createCoupon = async (
|
||||
export const deleteCoupon = async (couponId: string): Promise<void> => {
|
||||
await axios.delete(`/admin/coupon/${couponId}`);
|
||||
};
|
||||
|
||||
export const getCouponDetail = async (
|
||||
couponId: string
|
||||
): Promise<GetCouponDetailResponseType> => {
|
||||
const { data } = await axios.get(`/admin/coupon/${couponId}`);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const updateCoupon = async (
|
||||
params: CreateCouponType
|
||||
): Promise<CouponType> => {
|
||||
const { data } = await axios.patch(
|
||||
`/admin/coupon/${params.couponId}`,
|
||||
params
|
||||
);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export interface CreateCouponType {
|
||||
couponId?: string;
|
||||
discountPercentage?: number;
|
||||
discountAmount?: number;
|
||||
usageLimit: number;
|
||||
@@ -59,3 +60,11 @@ export interface CouponsResponse {
|
||||
pager: PagerType;
|
||||
};
|
||||
}
|
||||
|
||||
export type GetCouponDetailResponseType = {
|
||||
status: number;
|
||||
success: boolean;
|
||||
results: {
|
||||
coupon: CouponResponseData;
|
||||
};
|
||||
};
|
||||
|
||||
+2
-1
@@ -31,6 +31,7 @@ import ShippingList from '@/pages/shipment/List'
|
||||
import CreateShipment from '@/pages/shipment/Create'
|
||||
import CouponList from '@/pages/Coupon/List'
|
||||
import CreateCoupon from '@/pages/Coupon/Create'
|
||||
import UpdateCoupon from '@/pages/Coupon/Update'
|
||||
|
||||
const MainRouter: FC = () => {
|
||||
|
||||
@@ -81,7 +82,7 @@ const MainRouter: FC = () => {
|
||||
|
||||
<Route path={Pages.coupon.list} element={<CouponList />} />
|
||||
<Route path={Pages.coupon.create} element={<CreateCoupon />} />
|
||||
|
||||
<Route path={`${Pages.coupon.detail}:id`} element={<UpdateCoupon />} />
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user