update shipment

This commit is contained in:
hamid zarghami
2025-09-29 11:47:35 +03:30
parent 53859d4bbb
commit 25148282ae
5 changed files with 313 additions and 1 deletions
+264
View File
@@ -0,0 +1,264 @@
import { type FC } from 'react'
import { useFormik } from 'formik'
import { type CreateShipper, type Cost } from './types/Types'
import * as Yup from 'yup'
import { useGetShipmentById, useUpdateShipment } from './hooks/useShipmentData'
import { useNavigate, useParams } 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 UpdateShipment: FC = () => {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const updateShipmentMutation = useUpdateShipment()
const { data: shipmentDetail, isLoading: shipmentDetailLoading, error: shipmentDetailError } = useGetShipmentById(id!)
const formik = useFormik<CreateShipper>({
initialValues: {
name: shipmentDetail?.name || '',
description: shipmentDetail?.description || '',
costs: shipmentDetail?.costs || [],
deliveryTime: shipmentDetail?.deliveryTime || 0,
deliveryType: shipmentDetail?.deliveryType || 'Standard',
},
enableReinitialize: true,
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)
updateShipmentMutation.mutate({ id: id!, params: 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)
}
if (shipmentDetailLoading) {
return (
<div className='mt-4'>
<div className='flex justify-center items-center h-64'>
<div className='text-center'>
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4'></div>
<p className='text-gray-600'>در حال بارگذاری...</p>
</div>
</div>
</div>
)
}
if (shipmentDetailError) {
return (
<div className='mt-4'>
<div className='bg-red-50 border border-red-200 rounded-lg p-4 text-center'>
<p className='text-red-600'>خطا در بارگذاری اطلاعات روش ارسال</p>
</div>
</div>
)
}
if (!shipmentDetail) {
return (
<div className='mt-4'>
<div className='bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-center'>
<p className='text-yellow-600'>روش ارسال یافت نشد</p>
</div>
</div>
)
}
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={updateShipmentMutation.isPending}
disabled={!formik.isValid || updateShipmentMutation.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 UpdateShipment
@@ -28,3 +28,21 @@ export const useDeleteShipment = () => {
},
});
};
export const useGetShipmentById = (id: string) => {
return useQuery({
queryKey: ["shipment", id],
queryFn: () => api.getShipmentById(id),
});
};
export const useUpdateShipment = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, params }: { id: string; params: CreateShipper }) =>
api.updateShipment(id, params),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["shipment"] });
},
});
};
+21 -1
View File
@@ -1,5 +1,10 @@
import axios from "../../../config/axios";
import type { ShipmentResponse, CreateShipper, Shipper } from "../types/Types";
import type {
ShipmentResponse,
CreateShipper,
Shipper,
ShipmentByIdResponse,
} from "../types/Types";
export const getShipment = async (
page: number = 1
@@ -17,3 +22,18 @@ export const deleteShipment = async (id: string): Promise<void> => {
const { data } = await axios.delete(`/admin/shipment/${id}`);
return data;
};
export const getShipmentById = async (id: string): Promise<Shipper> => {
const { data } = await axios.get<ShipmentByIdResponse>(
`/admin/shipment/${id}`
);
return data.results.shipper;
};
export const updateShipment = async (
id: string,
params: CreateShipper
): Promise<Shipper> => {
const { data } = await axios.patch<Shipper>(`/admin/shipment/${id}`, params);
return data;
};
+8
View File
@@ -46,3 +46,11 @@ export interface ShipmentResponse {
shipper: Shipper[];
};
}
export interface ShipmentByIdResponse {
status: number;
success: boolean;
results: {
shipper: Shipper;
};
}
+2
View File
@@ -38,6 +38,7 @@ import AdminCreate from '@/pages/admin/Create'
import UpdateBrand from '@/pages/brand/Update'
import UpdateWarranty from '@/pages/warranty/Update'
import PaymentList from '@/pages/payment/List'
import UpdateShipment from '@/pages/shipment/Update'
const MainRouter: FC = () => {
const { hasSubMenu } = useSharedStore()
@@ -86,6 +87,7 @@ const MainRouter: FC = () => {
<Route path={Pages.shipment.list} element={<ShippingList />} />
<Route path={Pages.shipment.create} element={<CreateShipment />} />
<Route path={`${Pages.shipment.update}:id`} element={<UpdateShipment />} />
<Route path={Pages.coupon.list} element={<CouponList />} />
<Route path={Pages.coupon.create} element={<CreateCoupon />} />