create + list + delete shipment

This commit is contained in:
hamid zarghami
2025-09-27 09:59:10 +03:30
parent 834e575d17
commit ee89008a9f
9 changed files with 525 additions and 39 deletions
+5
View File
@@ -153,4 +153,9 @@ export const Pages = {
detailUser: "/orders/detail-user/",
detailSeller: "/orders/detail-seller/",
},
shipment: {
list: "/shipment/list",
create: "/shipment/create",
update: "/shipment/update/",
},
};
+228
View File
@@ -0,0 +1,228 @@
import { type FC } from 'react'
import { useFormik } from 'formik'
import { type CreateShipper, type Cost } from './types/Types'
import * as Yup from 'yup'
import { useCreateShipment } from './hooks/useShipmentData'
import { useNavigate } from 'react-router-dom'
import Input from '../../components/Input'
import Textarea from '../../components/Textarea'
import Button from '../../components/Button'
import Select from '../../components/Select'
import { TickCircle, Add, Trash } from 'iconsax-react'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '../../helpers/utils'
import { Pages } from '../../config/Pages'
const CreateShipment: FC = () => {
const navigate = useNavigate()
const createShipmentMutation = useCreateShipment()
const formik = useFormik<CreateShipper>({
initialValues: {
name: '',
description: '',
costs: [],
deliveryTime: 0,
deliveryType: 'Standard',
},
validationSchema: Yup.object({
name: Yup.string().required('عنوان روش ارسال الزامی است'),
description: Yup.string().required('توضیحات روش ارسال الزامی است'),
costs: Yup.array().min(1, 'حداقل یک محدوده وزنی الزامی است'),
deliveryTime: Yup.number().min(0, 'زمان ارسال باید بزرگتر از صفر باشد').required('زمان ارسال الزامی است'),
deliveryType: Yup.string().oneOf(['Standard', 'SameDay', 'Express'], 'نوع ارسال نامعتبر است'),
}),
onSubmit: async (values) => {
values.deliveryTime = Number(values.deliveryTime)
createShipmentMutation.mutate(values, {
onSuccess: () => {
toast.success('روش ارسال با موفقیت ایجاد شد')
navigate(Pages.shipment.list)
},
onError: (error) => {
toast.error(extractErrorMessage(error))
}
})
},
})
const addCostRange = () => {
const newCost: Cost = {
weightRange: { min: 0, max: 0 },
cost_first: 0,
cost_rest: 0
}
formik.setFieldValue('costs', [...formik.values.costs, newCost])
}
const removeCostRange = (index: number) => {
const newCosts = formik.values.costs.filter((_, i) => i !== index)
formik.setFieldValue('costs', newCosts)
}
const updateCostRange = (index: number, field: keyof Cost, value: number | { min?: number; max?: number }) => {
const newCosts = [...formik.values.costs]
if (field === 'weightRange') {
newCosts[index].weightRange = { ...newCosts[index].weightRange, ...(value as { min?: number; max?: number }) }
} else {
newCosts[index][field] = value as number
}
formik.setFieldValue('costs', newCosts)
}
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={createShipmentMutation.isPending}
disabled={!formik.isValid || createShipmentMutation.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='مثال: پست پیشتاز'
{...formik.getFieldProps('name')}
error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
/>
<Input
label='زمان ارسال (ساعت)'
type='number'
placeholder='مثال: 24'
{...formik.getFieldProps('deliveryTime')}
error_text={formik.touched.deliveryTime && formik.errors.deliveryTime ? formik.errors.deliveryTime : ''}
/>
</div>
<Select
label='نوع ارسال'
placeholder='انتخاب نوع ارسال'
items={[
{ value: 'Standard', label: 'معمولی' },
{ value: 'SameDay', label: 'همان روز' },
{ value: 'Express', label: 'اکسپرس' },
]}
value={formik.values.deliveryType}
onChange={(e) => formik.setFieldValue('deliveryType', e.target.value)}
error_text={formik.touched.deliveryType && formik.errors.deliveryType ? formik.errors.deliveryType : ''}
/>
<Textarea
label='توضیحات روش ارسال'
placeholder='توضیحات کامل روش ارسال را وارد کنید...'
{...formik.getFieldProps('description')}
error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
/>
</div>
</div>
{/* هزینه‌ها */}
<div className='w-80 space-y-6'>
<div className='text-sm bg-white py-8 px-6 rounded-3xl'>
<div className='flex justify-between items-center mb-6'>
<h2>هزینه ها</h2>
<Button
size='sm'
variant='outline'
onClick={addCostRange}
className='px-3 py-1 w-fit'
>
<Add size={14} />
افزودن
</Button>
</div>
<div className='space-y-4'>
{formik.values.costs.map((cost, index) => (
<div key={index} className='border border-gray-200 rounded-lg p-4'>
<div className='flex justify-between items-center mb-3'>
<h3 className='font-medium text-sm'>محدوده {index + 1}</h3>
<Button
size='sm'
variant='outline'
onClick={() => removeCostRange(index)}
className='px-2 py-1 text-red-500 hover:text-red-700 w-fit'
>
<Trash size={14} color='red' />
</Button>
</div>
<div className='space-y-3'>
<div className='flex flex-col gap-3'>
<Input
label='وزن حداقل (kg)'
type='number'
placeholder='0'
value={cost.weightRange.min}
onChange={(e) => updateCostRange(index, 'weightRange', { min: parseFloat(e.target.value) || 0 })}
/>
<Input
label='وزن حداکثر (kg)'
type='number'
placeholder='10'
value={cost.weightRange.max}
onChange={(e) => updateCostRange(index, 'weightRange', { max: parseFloat(e.target.value) || 0 })}
/>
</div>
<div className='flex flex-col gap-3'>
<Input
label='هزینه پایه (تومان)'
type='number'
placeholder='10000'
value={cost.cost_first}
onChange={(e) => updateCostRange(index, 'cost_first', parseFloat(e.target.value) || 0)}
/>
<Input
label='هزینه اضافی (تومان)'
type='number'
placeholder='5000'
value={cost.cost_rest}
onChange={(e) => updateCostRange(index, 'cost_rest', parseFloat(e.target.value) || 0)}
/>
</div>
</div>
</div>
))}
{formik.values.costs.length === 0 && (
<div className='text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg'>
<svg className='w-12 h-12 mx-auto mb-3 text-gray-300' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={1} d='M12 6v6m0 0v6m0-6h6m-6 0H6' />
</svg>
<p className='text-sm font-medium text-gray-400 mb-1'>هیچ محدوده وزنی تعریف نشده</p>
<p className='text-xs text-gray-400'>برای شروع، محدوده وزنی جدیدی اضافه کنید</p>
</div>
)}
{formik.touched.costs && formik.errors.costs && (
<p className='text-red-500 text-xs mt-1'>{String(formik.errors.costs)}</p>
)}
</div>
</div>
</div>
</div>
</div>
)
}
export default CreateShipment
+141
View File
@@ -0,0 +1,141 @@
import { type FC, useState } from 'react'
import { useGetShipment, useDeleteShipment } from './hooks/useShipmentData'
import { type Shipper } from './types/Types'
import PageLoading from '@/components/PageLoading';
import Error from '@/components/Error';
import Button from '@/components/Button';
import PaginationUi from '@/components/PaginationUi';
import Td from '@/components/Td';
import TrashWithConfrim from '@/components/TrashWithConfrim';
import { Edit } from 'iconsax-react';
import { Link } from 'react-router-dom';
import { Pages } from '@/config/Pages';
import { useNavigate } from 'react-router-dom';
const ShippingList: FC = () => {
const [currentPage, setCurrentPage] = useState(1);
const navigate = useNavigate();
const { data, isLoading, error, refetch } = useGetShipment(currentPage);
const deleteShipmentMutation = useDeleteShipment();
if (isLoading) {
return (
<div className="flex justify-center items-center min-h-[400px]">
<PageLoading />
</div>
);
}
if (error) {
return (
<div className="flex justify-center items-center min-h-[400px]">
<Error errorText="خطا در بارگذاری اطلاعات ارسال" />
</div>
);
}
const handleDeleteShipment = async (shipmentId: string) => {
await deleteShipmentMutation.mutateAsync(shipmentId);
refetch();
};
const shipments = data?.results?.shipper || [];
const pager = data?.results?.pager;
const getDeliveryTypeText = (type: string) => {
switch (type) {
case 'Standard':
return 'معمولی';
case 'SameDay':
return 'همان روز';
case 'Express':
return 'اکسپرس';
default:
return type;
}
};
return (
<div>
<div className='flex justify-end mt-5'>
<Button
label='افزودن روش ارسال'
onClick={() => navigate(`${Pages.shipment.create}`)}
className='w-fit'
/>
</div>
<div className='relative overflow-x-auto rounded-3xl mt-5 w-full'>
<table className='w-full text-sm'>
<thead className='thead'>
<tr>
<Td text={'نام روش ارسال'} />
<Td text={'توضیحات'} />
<Td text={'نوع ارسال'} />
<Td text={'زمان ارسال (روز)'} />
<Td text={'هزینه‌ها'} />
<Td text={'عملیات'} />
</tr>
</thead>
<tbody>
{shipments.length === 0 ? (
<tr className='tr'>
<td colSpan={7} className="text-center py-8 text-gray-500">
هیچ روش ارسالی یافت نشد
</td>
</tr>
) : (
shipments.map((shipment: Shipper) => (
<tr key={shipment._id} className='tr'>
<Td text={shipment.name} />
<Td text={shipment.description} />
<Td text={getDeliveryTypeText(shipment.deliveryType)} />
<Td text={shipment.deliveryTime.toString()} />
<Td text="">
<div className="text-sm">
{shipment.costs.length > 0 ? (
<div>
{shipment.costs.slice(0, 2).map((cost, index) => (
<div key={index} className="mb-1">
{cost.weightRange.min}-{cost.weightRange.max}kg:
{cost.cost_first}/{cost.cost_rest}
</div>
))}
{shipment.costs.length > 2 && (
<span className="text-gray-500">و {shipment.costs.length - 2} مورد دیگر...</span>
)}
</div>
) : (
'بدون هزینه'
)}
</div>
</Td>
<Td text="">
<div className="flex items-center gap-2">
<Link to={`${Pages.shipment.update}${shipment._id}`}>
<Edit color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500" />
</Link>
<TrashWithConfrim
onDelete={() => handleDeleteShipment(shipment._id.toString())}
isLoading={deleteShipmentMutation.isPending}
/>
</div>
</Td>
</tr>
))
)}
</tbody>
</table>
</div>
<PaginationUi
pager={pager}
onPageChange={(page) => {
setCurrentPage(page);
}}
/>
</div>
)
}
export default ShippingList
@@ -0,0 +1,30 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import * as api from "../servicce/Service";
import type { ShipmentResponse, CreateShipper } from "../types/Types";
export const useGetShipment = (page: number = 1) => {
return useQuery<ShipmentResponse>({
queryKey: ["shipment", page],
queryFn: () => api.getShipment(page),
});
};
export const useCreateShipment = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateShipper) => api.createShipment(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["shipment"] });
},
});
};
export const useDeleteShipment = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.deleteShipment,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["shipment"] });
},
});
};
+19
View File
@@ -0,0 +1,19 @@
import axios from "../../../config/axios";
import type { ShipmentResponse, CreateShipper, Shipper } from "../types/Types";
export const getShipment = async (
page: number = 1
): Promise<ShipmentResponse> => {
const { data } = await axios.get<ShipmentResponse>(`/shipment?page=${page}`);
return data;
};
export const createShipment = async (data: CreateShipper): Promise<Shipper> => {
const response = await axios.post<Shipper>("/admin/shipment", data);
return response.data;
};
export const deleteShipment = async (id: string): Promise<void> => {
const { data } = await axios.delete(`/admin/shipment/${id}`);
return data;
};
+48
View File
@@ -0,0 +1,48 @@
export interface WeightRange {
min: number;
max: number;
}
export interface Cost {
weightRange: WeightRange;
cost_first: number;
cost_rest: number;
}
export interface Shipper {
_id: number;
name: string;
description: string;
costs: Cost[];
deliveryType: "Standard" | "SameDay" | "Express";
deliveryTime: number;
deleted: boolean;
createdAt: string;
updatedAt: string;
}
export interface Pager {
page: number;
limit: number;
totalItems: number;
totalPages: number;
prevPage: boolean | null;
nextPage: string | null;
}
export interface CreateShipper {
name: string;
description: string;
costs: Cost[];
deliveryTime: number;
deliveryType?: "Standard" | "SameDay" | "Express";
}
export interface ShipmentResponse {
status: number;
success: boolean;
results: {
pager: Pager;
shipper: Shipper[];
};
}
+5
View File
@@ -27,6 +27,8 @@ import OrderDetail from '@/pages/orders/Detail'
import BlogsList from '@/pages/blogs/List'
import CreateBlog from '@/pages/blogs/Create'
import UpdateBlog from '@/pages/blogs/Update'
import ShippingList from '@/pages/shipment/List'
import CreateShipment from '@/pages/shipment/Create'
const MainRouter: FC = () => {
@@ -72,6 +74,9 @@ const MainRouter: FC = () => {
<Route path={Pages.blog.create} element={<CreateBlog />} />
<Route path={`${Pages.blog.detail}:id`} element={<UpdateBlog />} />
<Route path={Pages.shipment.list} element={<ShippingList />} />
<Route path={Pages.shipment.create} element={<CreateShipment />} />
</Routes>
</div>
</div>
+7 -39
View File
@@ -26,6 +26,7 @@ import { useLocation } from 'react-router-dom'
import { useSharedStore } from './store/sharedStore'
import { clx } from '../helpers/utils'
import BlogSubMenu from './components/BlogSubMenu'
import ShippingSubMenu from './components/ShippingSubMenu'
import SubMenuItem from './components/SubMenuItem'
import { Pages } from '../config/Pages'
@@ -44,7 +45,7 @@ const SideBar: FC = () => {
const split = location.pathname.split('/')
if (split[1] === 'dashboard' || split[1] === 'products' || split[1] === 'orders' ||
split[1] === 'blog' || split[1] === 'shipping' || split[1] === 'financial' ||
split[1] === 'blog' || split[1] === 'shipment' || split[1] === 'financial' ||
split[1] === 'sellers' || split[1] === 'buyers' || split[1] === 'users' ||
split[1] === 'tickets' || split[1] === 'reports' || split[1] === 'chat' ||
split[1] === 'contact' || split[1] === 'settings' || split[1] === 'pages' ||
@@ -136,11 +137,11 @@ const SideBar: FC = () => {
{/* روش های ارسال */}
<SideBarItem
icon={<Truck variant={isActive('shipping') ? 'Bold' : 'Outline'} color={isActive('shipping') ? 'black' : '#8C90A3'} size={iconSizeSideBar} />}
icon={<Truck variant={isActive('shipment') ? 'Bold' : 'Outline'} color={isActive('shipment') ? 'black' : '#8C90A3'} size={iconSizeSideBar} />}
title="روش های ارسال"
isActive={isActive('shipping')}
link="/shipping"
activeName='shipping'
isActive={isActive('shipment')}
link={Pages.shipment.list}
activeName='shipment'
/>
{/* مالی */}
@@ -267,7 +268,7 @@ const SideBar: FC = () => {
: subMenuName === 'dashboard' ? <DashboardSubMenu />
: subMenuName === 'products' ? <ProductsSubMenu />
: subMenuName === 'orders' ? <OrdersSubMenu />
: subMenuName === 'shipping' ? <ShippingSubMenu />
: subMenuName === 'shipment' ? <ShippingSubMenu />
: subMenuName === 'financial' ? <FinancialSubMenu />
: subMenuName === 'sellers' ? <SellersSubMenu />
: subMenuName === 'buyers' ? <BuyersSubMenu />
@@ -441,39 +442,6 @@ const OrdersSubMenu: FC = () => {
)
}
const ShippingSubMenu: FC = () => {
const isActive = (name: string) => {
return location.pathname.includes(name)
}
return (
<div className='py-12'>
<div className='flex gap-3 items-center border-b border-border pb-10 px-6'>
<Truck
size={24}
color='#000'
variant='Bold'
/>
<div className='text-xs'>
روش های ارسال
</div>
</div>
<div className='flex flex-col mt-10 gap-4'>
<SubMenuItem
title={'لیست روش های ارسال'}
isActive={isActive('methods')}
link="/shipping/methods"
/>
<SubMenuItem
title={'تنظیمات ارسال'}
isActive={isActive('settings')}
link="/shipping/settings"
/>
</div>
</div>
)
}
const FinancialSubMenu: FC = () => {
const isActive = (name: string) => {
+42
View File
@@ -0,0 +1,42 @@
import { Truck } from 'iconsax-react'
import { type FC } from 'react'
import SubMenuItem from './SubMenuItem'
import { Pages } from '../../config/Pages'
const ShippingSubMenu: FC = () => {
const isActive = (name: string) => {
return location.pathname.includes(name)
}
return (
<div className='py-12'>
<div className='flex gap-3 items-center border-b border-border pb-10 px-6'>
<Truck
size={24}
color='#000'
variant='Bold'
/>
<div className='text-xs'>
روش های ارسال
</div>
</div>
<div className='flex flex-col mt-10 gap-4'>
<SubMenuItem
title={'لیست روش های ارسال'}
isActive={isActive('list')}
link={Pages.shipment.list}
/>
<SubMenuItem
title={'ایجاد روش ارسال'}
isActive={isActive('create')}
link={Pages.shipment.create}
/>
</div>
</div>
)
}
export default ShippingSubMenu