2
0

ExpressCompanies.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. import { useState } from 'react'
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
  3. import { zodResolver } from '@hookform/resolvers/zod'
  4. import { useForm } from 'react-hook-form'
  5. import { Plus, Search, Edit, Trash2 } from 'lucide-react'
  6. import { toast } from 'react-toastify'
  7. import { Button } from '@/client/components/ui/button'
  8. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card'
  9. import { Input } from '@/client/components/ui/input'
  10. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table'
  11. import { Badge } from '@/client/components/ui/badge'
  12. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog'
  13. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form'
  14. import { DataTablePagination } from '@/client/admin-shadcn/components/DataTablePagination'
  15. import { expressCompanyClient } from '@/client/api'
  16. import type { InferRequestType, InferResponseType } from 'hono/client'
  17. import { CreateExpressCompanyDto, UpdateExpressCompanyDto } from '@/server/modules/logistics/express-company.schema'
  18. // 类型定义
  19. type CreateRequest = InferRequestType<typeof expressCompanyClient.$post>['json']
  20. type UpdateRequest = InferRequestType<typeof expressCompanyClient[':id']['$put']>['json']
  21. type ExpressCompanyResponse = InferResponseType<typeof expressCompanyClient.$get, 200>['data'][0]
  22. // 表单Schema直接使用后端定义
  23. const createFormSchema = CreateExpressCompanyDto
  24. const updateFormSchema = UpdateExpressCompanyDto
  25. export const ExpressCompaniesPage = () => {
  26. const queryClient = useQueryClient()
  27. // 状态管理
  28. const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '' })
  29. const [isModalOpen, setIsModalOpen] = useState(false)
  30. const [editingCompany, setEditingCompany] = useState<ExpressCompanyResponse | null>(null)
  31. const [isCreateForm, setIsCreateForm] = useState(true)
  32. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  33. const [companyToDelete, setCompanyToDelete] = useState<number | null>(null)
  34. // 表单实例
  35. const createForm = useForm<CreateRequest>({
  36. resolver: zodResolver(createFormSchema),
  37. defaultValues: {
  38. name: '',
  39. code: '',
  40. state: 1,
  41. sort: 100
  42. },
  43. })
  44. const updateForm = useForm<UpdateRequest>({
  45. resolver: zodResolver(updateFormSchema),
  46. })
  47. // 数据查询
  48. const { data, isLoading, refetch } = useQuery({
  49. queryKey: ['express-companies', searchParams],
  50. queryFn: async () => {
  51. const res = await expressCompanyClient.$get({
  52. query: {
  53. page: searchParams.page,
  54. pageSize: searchParams.limit,
  55. keyword: searchParams.search,
  56. }
  57. })
  58. if (res.status !== 200) throw new Error('获取快递公司列表失败')
  59. return await res.json()
  60. }
  61. })
  62. // 创建快递公司
  63. const createMutation = useMutation({
  64. mutationFn: async (data: CreateRequest) => {
  65. const res = await expressCompanyClient.$post({ json: data })
  66. if (res.status !== 201) throw new Error('创建快递公司失败')
  67. return await res.json()
  68. },
  69. onSuccess: () => {
  70. toast.success('快递公司创建成功')
  71. setIsModalOpen(false)
  72. queryClient.invalidateQueries({ queryKey: ['express-companies'] })
  73. createForm.reset()
  74. },
  75. onError: (error) => {
  76. toast.error(error instanceof Error ? error.message : '创建失败,请重试')
  77. }
  78. })
  79. // 更新快递公司
  80. const updateMutation = useMutation({
  81. mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
  82. const res = await expressCompanyClient[':id']['$put']({
  83. param: { id: id.toString() },
  84. json: data
  85. })
  86. if (res.status !== 200) throw new Error('更新快递公司失败')
  87. return await res.json()
  88. },
  89. onSuccess: () => {
  90. toast.success('快递公司更新成功')
  91. setIsModalOpen(false)
  92. queryClient.invalidateQueries({ queryKey: ['express-companies'] })
  93. },
  94. onError: (error) => {
  95. toast.error(error instanceof Error ? error.message : '更新失败,请重试')
  96. }
  97. })
  98. // 删除快递公司
  99. const deleteMutation = useMutation({
  100. mutationFn: async (id: number) => {
  101. const res = await expressCompanyClient[':id']['$delete']({
  102. param: { id: id.toString() }
  103. })
  104. if (res.status !== 204) throw new Error('删除快递公司失败')
  105. return res
  106. },
  107. onSuccess: () => {
  108. toast.success('快递公司删除成功')
  109. setDeleteDialogOpen(false)
  110. queryClient.invalidateQueries({ queryKey: ['express-companies'] })
  111. },
  112. onError: (error) => {
  113. toast.error(error instanceof Error ? error.message : '删除失败,请重试')
  114. }
  115. })
  116. // 业务逻辑函数
  117. const handleSearch = () => {
  118. setSearchParams(prev => ({ ...prev, page: 1 }))
  119. }
  120. const handleCreateCompany = () => {
  121. setIsCreateForm(true)
  122. setEditingCompany(null)
  123. createForm.reset()
  124. setIsModalOpen(true)
  125. }
  126. const handleEditCompany = (company: ExpressCompanyResponse) => {
  127. setIsCreateForm(false)
  128. setEditingCompany(company)
  129. updateForm.reset({
  130. name: company.name,
  131. code: company.code,
  132. state: company.state,
  133. sort: company.sort || undefined
  134. })
  135. setIsModalOpen(true)
  136. }
  137. const handleDeleteCompany = (id: number) => {
  138. setCompanyToDelete(id)
  139. setDeleteDialogOpen(true)
  140. }
  141. const handleCreateSubmit = (data: CreateRequest) => {
  142. createMutation.mutate(data)
  143. }
  144. const handleUpdateSubmit = (data: UpdateRequest) => {
  145. if (editingCompany) {
  146. updateMutation.mutate({ id: editingCompany.id, data })
  147. }
  148. }
  149. const confirmDelete = () => {
  150. if (companyToDelete) {
  151. deleteMutation.mutate(companyToDelete)
  152. }
  153. }
  154. // 渲染页面
  155. if (isLoading) {
  156. return (
  157. <div className="space-y-4">
  158. <div className="flex justify-between items-center">
  159. <h1 className="text-2xl font-bold">快递公司管理</h1>
  160. <Button disabled>
  161. <Plus className="mr-2 h-4 w-4" />
  162. 创建快递公司
  163. </Button>
  164. </div>
  165. <Card>
  166. <CardHeader>
  167. <Skeleton className="h-6 w-1/4" />
  168. </CardHeader>
  169. <CardContent>
  170. <div className="space-y-2">
  171. <Skeleton className="h-4 w-full" />
  172. <Skeleton className="h-4 w-full" />
  173. <Skeleton className="h-4 w-full" />
  174. </div>
  175. </CardContent>
  176. </Card>
  177. </div>
  178. )
  179. }
  180. return (
  181. <div className="space-y-4">
  182. {/* 页面标题区域 */}
  183. <div className="flex justify-between items-center">
  184. <h1 className="text-2xl font-bold">快递公司管理</h1>
  185. <Button onClick={handleCreateCompany}>
  186. <Plus className="mr-2 h-4 w-4" />
  187. 创建快递公司
  188. </Button>
  189. </div>
  190. {/* 搜索区域 */}
  191. <Card>
  192. <CardHeader>
  193. <CardTitle>快递公司列表</CardTitle>
  194. <CardDescription>管理系统中的快递公司信息</CardDescription>
  195. </CardHeader>
  196. <CardContent>
  197. <div className="mb-4">
  198. <form onSubmit={(e) => { e.preventDefault(); handleSearch() }} className="flex gap-2">
  199. <div className="relative flex-1 max-w-sm">
  200. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  201. <Input
  202. placeholder="搜索快递公司名称或编号..."
  203. value={searchParams.search}
  204. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  205. className="pl-8"
  206. />
  207. </div>
  208. <Button type="submit" variant="outline">
  209. 搜索
  210. </Button>
  211. </form>
  212. </div>
  213. {/* 数据表格 */}
  214. <div className="rounded-md border">
  215. <Table>
  216. <TableHeader>
  217. <TableRow>
  218. <TableHead>ID</TableHead>
  219. <TableHead>公司名称</TableHead>
  220. <TableHead>编号</TableHead>
  221. <TableHead>状态</TableHead>
  222. <TableHead>排序</TableHead>
  223. <TableHead>创建时间</TableHead>
  224. <TableHead className="text-right">操作</TableHead>
  225. </TableRow>
  226. </TableHeader>
  227. <TableBody>
  228. {data?.data.map((company) => (
  229. <TableRow key={company.id}>
  230. <TableCell>{company.id}</TableCell>
  231. <TableCell>{company.name}</TableCell>
  232. <TableCell>{company.code}</TableCell>
  233. <TableCell>
  234. <Badge variant={company.state === 1 ? 'default' : 'secondary'}>
  235. {company.state === 1 ? '启用' : '禁用'}
  236. </Badge>
  237. </TableCell>
  238. <TableCell>{company.sort || '-'}</TableCell>
  239. <TableCell>{new Date(company.createdAt).toLocaleDateString()}</TableCell>
  240. <TableCell className="text-right">
  241. <div className="flex justify-end gap-2">
  242. <Button
  243. variant="ghost"
  244. size="icon"
  245. onClick={() => handleEditCompany(company)}
  246. title="编辑"
  247. >
  248. <Edit className="h-4 w-4" />
  249. </Button>
  250. <Button
  251. variant="ghost"
  252. size="icon"
  253. onClick={() => handleDeleteCompany(company.id)}
  254. title="删除"
  255. >
  256. <Trash2 className="h-4 w-4" />
  257. </Button>
  258. </div>
  259. </TableCell>
  260. </TableRow>
  261. ))}
  262. </TableBody>
  263. </Table>
  264. </div>
  265. {data?.data.length === 0 && !isLoading && (
  266. <div className="text-center py-8">
  267. <p className="text-muted-foreground">暂无快递公司数据</p>
  268. </div>
  269. )}
  270. <DataTablePagination
  271. currentPage={searchParams.page}
  272. pageSize={searchParams.limit}
  273. totalCount={data?.pagination.total || 0}
  274. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  275. />
  276. </CardContent>
  277. </Card>
  278. {/* 创建/编辑模态框 */}
  279. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  280. <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
  281. <DialogHeader>
  282. <DialogTitle>{isCreateForm ? '创建快递公司' : '编辑快递公司'}</DialogTitle>
  283. <DialogDescription>
  284. {isCreateForm ? '创建一个新的快递公司' : '编辑现有快递公司信息'}
  285. </DialogDescription>
  286. </DialogHeader>
  287. {isCreateForm ? (
  288. <Form {...createForm}>
  289. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  290. <FormField
  291. control={createForm.control}
  292. name="name"
  293. render={({ field }) => (
  294. <FormItem>
  295. <FormLabel className="flex items-center">
  296. 公司名称 <span className="text-red-500 ml-1">*</span>
  297. </FormLabel>
  298. <FormControl>
  299. <Input placeholder="请输入快递公司名称" {...field} />
  300. </FormControl>
  301. <FormDescription>例如:顺丰速运、中通快递等</FormDescription>
  302. <FormMessage />
  303. </FormItem>
  304. )}
  305. />
  306. <FormField
  307. control={createForm.control}
  308. name="code"
  309. render={({ field }) => (
  310. <FormItem>
  311. <FormLabel className="flex items-center">
  312. 编号 <span className="text-red-500 ml-1">*</span>
  313. </FormLabel>
  314. <FormControl>
  315. <Input placeholder="请输入快递公司编号" {...field} />
  316. </FormControl>
  317. <FormDescription>例如:SF、ZTO等唯一标识</FormDescription>
  318. <FormMessage />
  319. </FormItem>
  320. )}
  321. />
  322. <FormField
  323. control={createForm.control}
  324. name="state"
  325. render={({ field }) => (
  326. <FormItem>
  327. <FormLabel>状态</FormLabel>
  328. <FormControl>
  329. <select
  330. className="w-full px-3 py-2 border rounded-md"
  331. value={field.value}
  332. onChange={(e) => field.onChange(parseInt(e.target.value))}
  333. >
  334. <option value={1}>启用</option>
  335. <option value={2}>禁用</option>
  336. </select>
  337. </FormControl>
  338. <FormDescription>选择快递公司的使用状态</FormDescription>
  339. <FormMessage />
  340. </FormItem>
  341. )}
  342. />
  343. <FormField
  344. control={createForm.control}
  345. name="sort"
  346. render={({ field }) => (
  347. <FormItem>
  348. <FormLabel>排序</FormLabel>
  349. <FormControl>
  350. <Input
  351. type="number"
  352. placeholder="请输入排序值"
  353. {...field}
  354. onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
  355. value={field.value || ''}
  356. />
  357. </FormControl>
  358. <FormDescription>数字越大优先级越高</FormDescription>
  359. <FormMessage />
  360. </FormItem>
  361. )}
  362. />
  363. <DialogFooter>
  364. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  365. 取消
  366. </Button>
  367. <Button type="submit" disabled={createMutation.isPending}>
  368. {createMutation.isPending ? '创建中...' : '创建'}
  369. </Button>
  370. </DialogFooter>
  371. </form>
  372. </Form>
  373. ) : (
  374. <Form {...updateForm}>
  375. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  376. <FormField
  377. control={updateForm.control}
  378. name="name"
  379. render={({ field }) => (
  380. <FormItem>
  381. <FormLabel className="flex items-center">
  382. 公司名称 <span className="text-red-500 ml-1">*</span>
  383. </FormLabel>
  384. <FormControl>
  385. <Input placeholder="请输入快递公司名称" {...field} />
  386. </FormControl>
  387. <FormDescription>例如:顺丰速运、中通快递等</FormDescription>
  388. <FormMessage />
  389. </FormItem>
  390. )}
  391. />
  392. <FormField
  393. control={updateForm.control}
  394. name="code"
  395. render={({ field }) => (
  396. <FormItem>
  397. <FormLabel className="flex items-center">
  398. 编号 <span className="text-red-500 ml-1">*</span>
  399. </FormLabel>
  400. <FormControl>
  401. <Input placeholder="请输入快递公司编号" {...field} />
  402. </FormControl>
  403. <FormDescription>例如:SF、ZTO等唯一标识</FormDescription>
  404. <FormMessage />
  405. </FormItem>
  406. )}
  407. />
  408. <FormField
  409. control={updateForm.control}
  410. name="state"
  411. render={({ field }) => (
  412. <FormItem>
  413. <FormLabel>状态</FormLabel>
  414. <FormControl>
  415. <select
  416. className="w-full px-3 py-2 border rounded-md"
  417. value={field.value}
  418. onChange={(e) => field.onChange(parseInt(e.target.value))}
  419. >
  420. <option value={1}>启用</option>
  421. <option value={2}>禁用</option>
  422. </select>
  423. </FormControl>
  424. <FormDescription>选择快递公司的使用状态</FormDescription>
  425. <FormMessage />
  426. </FormItem>
  427. )}
  428. />
  429. <FormField
  430. control={updateForm.control}
  431. name="sort"
  432. render={({ field }) => (
  433. <FormItem>
  434. <FormLabel>排序</FormLabel>
  435. <FormControl>
  436. <Input
  437. type="number"
  438. placeholder="请输入排序值"
  439. {...field}
  440. onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
  441. value={field.value || ''}
  442. />
  443. </FormControl>
  444. <FormDescription>数字越大优先级越高</FormDescription>
  445. <FormMessage />
  446. </FormItem>
  447. )}
  448. />
  449. <DialogFooter>
  450. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  451. 取消
  452. </Button>
  453. <Button type="submit" disabled={updateMutation.isPending}>
  454. {updateMutation.isPending ? '更新中...' : '更新'}
  455. </Button>
  456. </DialogFooter>
  457. </form>
  458. </Form>
  459. )}
  460. </DialogContent>
  461. </Dialog>
  462. {/* 删除确认对话框 */}
  463. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  464. <DialogContent>
  465. <DialogHeader>
  466. <DialogTitle>确认删除</DialogTitle>
  467. <DialogDescription>
  468. 确定要删除这个快递公司吗?此操作无法撤销。
  469. </DialogDescription>
  470. </DialogHeader>
  471. <DialogFooter>
  472. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  473. 取消
  474. </Button>
  475. <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
  476. {deleteMutation.isPending ? '删除中...' : '删除'}
  477. </Button>
  478. </DialogFooter>
  479. </DialogContent>
  480. </Dialog>
  481. </div>
  482. )
  483. }
  484. // 骨架屏组件
  485. const Skeleton = ({ className }: { className?: string }) => (
  486. <div className={`animate-pulse rounded-md bg-muted ${className}`} />
  487. )