create discount
This commit is contained in:
@@ -0,0 +1,272 @@
|
||||
import { useFormik } from 'formik'
|
||||
import { type FC } from 'react'
|
||||
import { type CreateCouponType } from './types/Types'
|
||||
import * as Yup from 'yup'
|
||||
import { useCreateCoupon } 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 CreateCoupon: FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const { data: categoriesData } = useGetCategories()
|
||||
const createCouponMutation = useCreateCoupon()
|
||||
|
||||
const formik = useFormik<CreateCouponType>({
|
||||
initialValues: {
|
||||
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,
|
||||
}
|
||||
|
||||
createCouponMutation.mutate(submitData, {
|
||||
onSuccess: () => {
|
||||
toast.success('کوپن با موفقیت ایجاد شد')
|
||||
navigate(Pages.coupon.list)
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(extractErrorMessage(error))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const categoryOptions = categoriesData?.results?.data?.map((category: CategoryTreeNode) => ({
|
||||
value: category._id,
|
||||
label: category.title_fa
|
||||
})) || []
|
||||
|
||||
return (
|
||||
<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={createCouponMutation.isPending}
|
||||
disabled={!formik.isValid || createCouponMutation.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='انتخاب تاریخ'
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
export default CreateCoupon
|
||||
@@ -0,0 +1,23 @@
|
||||
import { type FC } from 'react'
|
||||
import { useGetCoupons } from './hooks/useCouponData'
|
||||
import PageLoading from '@/components/PageLoading'
|
||||
import Error from '@/components/Error'
|
||||
|
||||
const CouponList: FC = () => {
|
||||
|
||||
const { data, isLoading, error } = useGetCoupons()
|
||||
|
||||
if (isLoading) {
|
||||
return <PageLoading />
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <Error errorText="خطا در بارگذاری تخفیفات" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div>List</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CouponList
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import * as api from "../service/CouponService";
|
||||
import type { CreateCouponType } from "../types/Types";
|
||||
|
||||
export const useGetCoupons = (page: number = 1) => {
|
||||
return useQuery({
|
||||
queryKey: ["coupons", page],
|
||||
queryFn: () => api.getCoupons(page),
|
||||
});
|
||||
};
|
||||
|
||||
export const useCreateCoupon = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (couponData: CreateCouponType) => api.createCoupon(couponData),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["coupons"] });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import axios from "../../../config/axios";
|
||||
import type { CreateCouponType, CouponType } from "../types/Types";
|
||||
|
||||
export const getCoupons = async (page: number = 1) => {
|
||||
const { data } = await axios.get(`/admin/coupon/native?page=${page}`);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const createCoupon = async (
|
||||
couponData: CreateCouponType
|
||||
): Promise<CouponType> => {
|
||||
const { data } = await axios.post("/admin/coupon", couponData);
|
||||
return data;
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface CreateCouponType {
|
||||
discountPercentage?: number;
|
||||
discountAmount?: number;
|
||||
usageLimit: number;
|
||||
userUsageLimit: number;
|
||||
minPurchaseAmount?: number;
|
||||
category?: string[];
|
||||
includedProducts?: number[];
|
||||
excludedProducts?: number[];
|
||||
description: string;
|
||||
includeSpecialSale: boolean;
|
||||
expirationDate: string;
|
||||
}
|
||||
|
||||
export interface CouponType extends CreateCouponType {
|
||||
id: string;
|
||||
code: string;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -87,4 +87,12 @@ export const useUpdateProduct = () => {
|
||||
return useMutation({
|
||||
mutationFn: (variables: UpdateProductRequestType) => api.updateProduct(variables),
|
||||
});
|
||||
};
|
||||
|
||||
export const useSearchProducts = (search: string, enabled: boolean = true) => {
|
||||
return useQuery({
|
||||
queryKey: ['products-search', search],
|
||||
queryFn: () => api.getProducts(1, 50, search),
|
||||
enabled: enabled,
|
||||
});
|
||||
};
|
||||
@@ -9,61 +9,74 @@ import {
|
||||
type GetProductsResponseType,
|
||||
type GetProductVariantsResponseType,
|
||||
type CreateProductVariantRequestType,
|
||||
type CreateProductVariantResponseType,
|
||||
type GetProductByIdResponseType,
|
||||
type UpdateVariantRequestType,
|
||||
type UpdateVariantResponseType,
|
||||
type GetVariantByIdResponseType,
|
||||
type UpdateProductDetailRequestType,
|
||||
type UpdateProductDetailResponseType,
|
||||
type UpdateProductAttributeRequestType,
|
||||
type UpdateProductAttributeResponseType,
|
||||
type UpdateProductRequestType,
|
||||
type UpdateProductResponseType,
|
||||
type UpdateProductResponseType
|
||||
} from "../types/Types";
|
||||
|
||||
export const createProductDetail = async (params: CreateProductDetailRequestType): Promise<CreateProductDetailResponseType> => {
|
||||
const { data } = await axios.post(`/admin/products/creation/detail`, params);
|
||||
export const createProductDetail = async (
|
||||
variables: CreateProductDetailRequestType
|
||||
): Promise<CreateProductDetailResponseType> => {
|
||||
const { data } = await axios.post("/admin/products/create/detail", variables);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const createProductAttribute = async (params: CreateProductAttributeRequestType): Promise<CreateProductAttributeResponseType> => {
|
||||
const { data } = await axios.post(`/admin/products/creation/attribute`, params);
|
||||
export const createProductAttribute = async (
|
||||
variables: CreateProductAttributeRequestType
|
||||
): Promise<CreateProductAttributeResponseType> => {
|
||||
const { data } = await axios.post("/admin/products/create/attribute", variables);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const saveProduct = async (params: SaveProductRequestType): Promise<SaveProductResponseType> => {
|
||||
const { data } = await axios.post(`/admin/products/creation/save`, params);
|
||||
export const saveProduct = async (
|
||||
variables: SaveProductRequestType
|
||||
): Promise<SaveProductResponseType> => {
|
||||
const { data } = await axios.post("/admin/products/create/save", variables);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getProducts = async (page: number = 1, limit: number = 10): Promise<GetProductsResponseType> => {
|
||||
export const getProducts = async (page: number = 1, limit: number = 10, search?: string): Promise<GetProductsResponseType> => {
|
||||
const params: Record<string, string | number> = { page, limit };
|
||||
if (search && search.trim()) {
|
||||
params.q = search.trim();
|
||||
}
|
||||
|
||||
const { data } = await axios.get(`/admin/products/native`, {
|
||||
params: { page, limit }
|
||||
params
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getProductVariants = async (productId: string): Promise<GetProductVariantsResponseType> => {
|
||||
const { data } = await axios.get(`/admin/products/${productId}/variants`);
|
||||
const { data } = await axios.get(`/admin/products/variants/${productId}`);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const createProductVariant = async (params: CreateProductVariantRequestType)=> {
|
||||
const { data } = await axios.post(`/admin/products/${params.productId}/variants`, params);
|
||||
export const createProductVariant = async (variables: CreateProductVariantRequestType): Promise<CreateProductVariantResponseType> => {
|
||||
const { data } = await axios.post("/admin/products/variants/create", variables);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getProductById = async (id: string): Promise<GetProductByIdResponseType> => {
|
||||
const { data } = await axios.get(`/admin/products/${id}/details`);
|
||||
const { data } = await axios.get(`/admin/products/get/${id}`);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const updateVariant = async (params: UpdateVariantRequestType) => {
|
||||
const { data } = await axios.patch(`/admin/products/${params.productId}/variants`, params);
|
||||
export const updateVariant = async (variables: UpdateVariantRequestType): Promise<UpdateVariantResponseType> => {
|
||||
const { data } = await axios.patch(`/admin/products/variants/update`, variables);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getVariantById = async (productId: string, variantId: string): Promise<GetVariantByIdResponseType> => {
|
||||
const { data } = await axios.get(`/admin/products/${productId}/variants/${variantId}`);
|
||||
const { data } = await axios.get(`/admin/products/variant/${productId}/${variantId}`);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -80,4 +93,4 @@ export const updateProductAttribute = async (params: UpdateProductAttributeReque
|
||||
export const updateProduct = async (params: UpdateProductRequestType): Promise<UpdateProductResponseType> => {
|
||||
const { data } = await axios.patch(`/admin/products/update/save`, params);
|
||||
return data;
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user