DeliveryAddresses.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. import React, { useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { format } from 'date-fns';
  4. import { zhCN } from 'date-fns/locale';
  5. import { toast } from 'sonner';
  6. import { Plus, Search, Edit, Trash2, MapPin } from 'lucide-react';
  7. import { useForm } from 'react-hook-form';
  8. import { zodResolver } from '@hookform/resolvers/zod';
  9. import type { InferRequestType, InferResponseType } from 'hono/client';
  10. import { deliveryAddressClient } from '@/client/api';
  11. import { CreateDeliveryAddressDto, UpdateDeliveryAddressDto } from '@/server/modules/delivery-address/delivery-address.schema';
  12. import { Button } from '@/client/components/ui/button';
  13. import { Input } from '@/client/components/ui/input';
  14. import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
  15. import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
  16. import { Badge } from '@/client/components/ui/badge';
  17. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  18. import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
  19. import { Switch } from '@/client/components/ui/switch';
  20. import { Skeleton } from '@/client/components/ui/skeleton';
  21. import { DataTablePagination } from '@/client/admin-shadcn/components/DataTablePagination';
  22. import { UserSelector } from '@/client/admin-shadcn/components/UserSelector';
  23. // 类型定义
  24. type DeliveryAddressResponse = InferResponseType<typeof deliveryAddressClient.$get, 200>['data'][0];
  25. type CreateRequest = InferRequestType<typeof deliveryAddressClient.$post>['json'];
  26. type UpdateRequest = InferRequestType<typeof deliveryAddressClient[':id']['$put']>['json'];
  27. // 表单schema
  28. const createFormSchema = CreateDeliveryAddressDto;
  29. const updateFormSchema = UpdateDeliveryAddressDto;
  30. export const DeliveryAddressesPage = () => {
  31. const queryClient = useQueryClient();
  32. // 状态管理
  33. const [searchParams, setSearchParams] = useState({
  34. page: 1,
  35. limit: 10,
  36. search: '',
  37. userId: undefined as number | undefined,
  38. });
  39. const [isModalOpen, setIsModalOpen] = useState(false);
  40. const [editingAddress, setEditingAddress] = useState<DeliveryAddressResponse | null>(null);
  41. const [isCreateForm, setIsCreateForm] = useState(true);
  42. const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  43. const [addressToDelete, setAddressToDelete] = useState<number | null>(null);
  44. // 表单实例
  45. const createForm = useForm<CreateRequest>({
  46. resolver: zodResolver(createFormSchema),
  47. defaultValues: {
  48. userId: 0,
  49. name: '',
  50. phone: '',
  51. address: '',
  52. receiverProvince: 0,
  53. receiverCity: 0,
  54. receiverDistrict: 0,
  55. receiverTown: 0,
  56. isDefault: 0,
  57. },
  58. });
  59. const updateForm = useForm<UpdateRequest>({
  60. resolver: zodResolver(updateFormSchema),
  61. });
  62. // 数据查询
  63. const { data, isLoading, refetch } = useQuery({
  64. queryKey: ['delivery-addresses', searchParams],
  65. queryFn: async () => {
  66. const res = await deliveryAddressClient.$get({
  67. query: {
  68. page: searchParams.page,
  69. pageSize: searchParams.limit,
  70. keyword: searchParams.search,
  71. ...(searchParams.userId && { userId: searchParams.userId }),
  72. }
  73. });
  74. if (res.status !== 200) throw new Error('获取收货地址列表失败');
  75. return await res.json();
  76. }
  77. });
  78. // 创建地址
  79. const createMutation = useMutation({
  80. mutationFn: async (data: CreateRequest) => {
  81. const res = await deliveryAddressClient.$post({ json: data });
  82. if (res.status !== 201) throw new Error('创建失败');
  83. return await res.json();
  84. },
  85. onSuccess: () => {
  86. toast.success('收货地址创建成功');
  87. setIsModalOpen(false);
  88. refetch();
  89. createForm.reset();
  90. },
  91. onError: (error) => {
  92. toast.error(error.message || '创建失败');
  93. }
  94. });
  95. // 更新地址
  96. const updateMutation = useMutation({
  97. mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
  98. const res = await deliveryAddressClient[':id']['$put']({
  99. param: { id: id.toString() },
  100. json: data,
  101. });
  102. if (res.status !== 200) throw new Error('更新失败');
  103. return await res.json();
  104. },
  105. onSuccess: () => {
  106. toast.success('收货地址更新成功');
  107. setIsModalOpen(false);
  108. refetch();
  109. },
  110. onError: (error) => {
  111. toast.error(error.message || '更新失败');
  112. }
  113. });
  114. // 删除地址
  115. const deleteMutation = useMutation({
  116. mutationFn: async (id: number) => {
  117. const res = await deliveryAddressClient[':id']['$delete']({
  118. param: { id: id.toString() },
  119. });
  120. if (res.status !== 204) throw new Error('删除失败');
  121. },
  122. onSuccess: () => {
  123. toast.success('收货地址删除成功');
  124. setDeleteDialogOpen(false);
  125. refetch();
  126. },
  127. onError: (error) => {
  128. toast.error(error.message || '删除失败');
  129. }
  130. });
  131. // 业务逻辑函数
  132. const handleSearch = () => {
  133. setSearchParams(prev => ({ ...prev, page: 1 }));
  134. };
  135. const handleCreateAddress = () => {
  136. setIsCreateForm(true);
  137. setEditingAddress(null);
  138. createForm.reset();
  139. setIsModalOpen(true);
  140. };
  141. const handleEditAddress = (address: DeliveryAddressResponse) => {
  142. setIsCreateForm(false);
  143. setEditingAddress(address);
  144. updateForm.reset({
  145. name: address.name,
  146. phone: address.phone,
  147. address: address.address,
  148. receiverProvince: address.receiverProvince,
  149. receiverCity: address.receiverCity,
  150. receiverDistrict: address.receiverDistrict,
  151. receiverTown: address.receiverTown,
  152. isDefault: address.isDefault,
  153. });
  154. setIsModalOpen(true);
  155. };
  156. const handleDeleteAddress = (id: number) => {
  157. setAddressToDelete(id);
  158. setDeleteDialogOpen(true);
  159. };
  160. const confirmDelete = () => {
  161. if (addressToDelete) {
  162. deleteMutation.mutate(addressToDelete);
  163. }
  164. };
  165. const handleCreateSubmit = (data: CreateRequest) => {
  166. createMutation.mutate(data);
  167. };
  168. const handleUpdateSubmit = (data: UpdateRequest) => {
  169. if (editingAddress) {
  170. updateMutation.mutate({ id: editingAddress.id, data });
  171. }
  172. };
  173. // 状态显示
  174. const getStatusBadge = (status: number) => {
  175. switch (status) {
  176. case 1:
  177. return <Badge variant="default">正常</Badge>;
  178. case 2:
  179. return <Badge variant="secondary">禁用</Badge>;
  180. case 3:
  181. return <Badge variant="destructive">删除</Badge>;
  182. default:
  183. return <Badge variant="outline">未知</Badge>;
  184. }
  185. };
  186. const getIsDefaultBadge = (isDefault: number) => {
  187. return isDefault === 1 ? (
  188. <Badge variant="default">默认</Badge>
  189. ) : (
  190. <Badge variant="outline">非默认</Badge>
  191. );
  192. };
  193. // 加载状态
  194. if (isLoading) {
  195. return (
  196. <div className="space-y-4">
  197. <div className="flex justify-between items-center">
  198. <Skeleton className="h-8 w-48" />
  199. <Skeleton className="h-10 w-32" />
  200. </div>
  201. <Card>
  202. <CardContent className="pt-6">
  203. <div className="space-y-3">
  204. {[...Array(5)].map((_, i) => (
  205. <div key={i} className="flex gap-4">
  206. <Skeleton className="h-10 flex-1" />
  207. <Skeleton className="h-10 flex-1" />
  208. <Skeleton className="h-10 flex-1" />
  209. <Skeleton className="h-10 w-20" />
  210. </div>
  211. ))}
  212. </div>
  213. </CardContent>
  214. </Card>
  215. </div>
  216. );
  217. }
  218. return (
  219. <div className="space-y-4">
  220. {/* 页面标题 */}
  221. <div className="flex justify-between items-center">
  222. <div>
  223. <h1 className="text-2xl font-bold">用户收货地址</h1>
  224. <p className="text-sm text-muted-foreground">管理用户的收货地址信息</p>
  225. </div>
  226. <Button onClick={handleCreateAddress}>
  227. <Plus className="mr-2 h-4 w-4" />
  228. 创建收货地址
  229. </Button>
  230. </div>
  231. {/* 搜索区域 */}
  232. <Card>
  233. <CardHeader>
  234. <CardTitle>搜索筛选</CardTitle>
  235. <CardDescription>根据条件筛选收货地址</CardDescription>
  236. </CardHeader>
  237. <CardContent>
  238. <div className="flex gap-4">
  239. <div className="flex-1">
  240. <div className="relative">
  241. <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
  242. <Input
  243. placeholder="搜索姓名、手机号、地址..."
  244. value={searchParams.search}
  245. onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
  246. className="pl-8"
  247. />
  248. </div>
  249. </div>
  250. <div className="w-64">
  251. <UserSelector
  252. value={searchParams.userId}
  253. onChange={(value) => setSearchParams(prev => ({ ...prev, userId: value }))}
  254. placeholder="选择用户"
  255. />
  256. </div>
  257. <Button onClick={handleSearch}>搜索</Button>
  258. </div>
  259. </CardContent>
  260. </Card>
  261. {/* 数据表格 */}
  262. <Card>
  263. <CardHeader>
  264. <CardTitle>收货地址列表</CardTitle>
  265. <CardDescription>
  266. 共 {data?.pagination.total || 0} 条记录
  267. </CardDescription>
  268. </CardHeader>
  269. <CardContent>
  270. <div className="rounded-md border">
  271. <Table>
  272. <TableHeader>
  273. <TableRow>
  274. <TableHead>ID</TableHead>
  275. <TableHead>用户</TableHead>
  276. <TableHead>收货人</TableHead>
  277. <TableHead>手机号</TableHead>
  278. <TableHead>地址</TableHead>
  279. <TableHead>状态</TableHead>
  280. <TableHead>默认</TableHead>
  281. <TableHead>创建时间</TableHead>
  282. <TableHead className="text-right">操作</TableHead>
  283. </TableRow>
  284. </TableHeader>
  285. <TableBody>
  286. {data?.data.map((address) => (
  287. <TableRow key={address.id}>
  288. <TableCell>{address.id}</TableCell>
  289. <TableCell>{address.user?.username || '-'}</TableCell>
  290. <TableCell>{address.name}</TableCell>
  291. <TableCell>{address.phone}</TableCell>
  292. <TableCell className="max-w-xs truncate" title={address.address}>
  293. {address.address}
  294. </TableCell>
  295. <TableCell>{getStatusBadge(address.state)}</TableCell>
  296. <TableCell>{getIsDefaultBadge(address.isDefault)}</TableCell>
  297. <TableCell>
  298. {format(new Date(address.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
  299. </TableCell>
  300. <TableCell className="text-right">
  301. <div className="flex justify-end gap-2">
  302. <Button
  303. variant="ghost"
  304. size="icon"
  305. onClick={() => handleEditAddress(address)}
  306. >
  307. <Edit className="h-4 w-4" />
  308. </Button>
  309. <Button
  310. variant="ghost"
  311. size="icon"
  312. onClick={() => handleDeleteAddress(address.id)}
  313. >
  314. <Trash2 className="h-4 w-4" />
  315. </Button>
  316. </div>
  317. </TableCell>
  318. </TableRow>
  319. ))}
  320. </TableBody>
  321. </Table>
  322. </div>
  323. {data?.data.length === 0 && !isLoading && (
  324. <div className="text-center py-8">
  325. <MapPin className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
  326. <p className="text-muted-foreground">暂无收货地址数据</p>
  327. </div>
  328. )}
  329. <DataTablePagination
  330. currentPage={searchParams.page}
  331. pageSize={searchParams.limit}
  332. totalCount={data?.pagination.total || 0}
  333. onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
  334. />
  335. </CardContent>
  336. </Card>
  337. {/* 创建/编辑模态框 */}
  338. <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
  339. <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
  340. <DialogHeader>
  341. <DialogTitle>
  342. {isCreateForm ? '创建收货地址' : '编辑收货地址'}
  343. </DialogTitle>
  344. <DialogDescription>
  345. {isCreateForm ? '创建一个新的收货地址' : '编辑现有收货地址信息'}
  346. </DialogDescription>
  347. </DialogHeader>
  348. {isCreateForm ? (
  349. <Form {...createForm}>
  350. <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
  351. <FormField
  352. control={createForm.control}
  353. name="userId"
  354. render={({ field }) => (
  355. <FormItem>
  356. <FormLabel>用户<span className="text-red-500 ml-1">*</span></FormLabel>
  357. <FormControl>
  358. <UserSelector
  359. value={field.value}
  360. onChange={field.onChange}
  361. placeholder="选择用户"
  362. />
  363. </FormControl>
  364. <FormMessage />
  365. </FormItem>
  366. )}
  367. />
  368. <div className="grid grid-cols-2 gap-4">
  369. <FormField
  370. control={createForm.control}
  371. name="name"
  372. render={({ field }) => (
  373. <FormItem>
  374. <FormLabel>收货人姓名<span className="text-red-500 ml-1">*</span></FormLabel>
  375. <FormControl>
  376. <Input placeholder="请输入收货人姓名" {...field} />
  377. </FormControl>
  378. <FormMessage />
  379. </FormItem>
  380. )}
  381. />
  382. <FormField
  383. control={createForm.control}
  384. name="phone"
  385. render={({ field }) => (
  386. <FormItem>
  387. <FormLabel>手机号<span className="text-red-500 ml-1">*</span></FormLabel>
  388. <FormControl>
  389. <Input placeholder="请输入手机号" {...field} />
  390. </FormControl>
  391. <FormMessage />
  392. </FormItem>
  393. )}
  394. />
  395. </div>
  396. <FormField
  397. control={createForm.control}
  398. name="address"
  399. render={({ field }) => (
  400. <FormItem>
  401. <FormLabel>详细地址<span className="text-red-500 ml-1">*</span></FormLabel>
  402. <FormControl>
  403. <Input placeholder="请输入详细地址" {...field} />
  404. </FormControl>
  405. <FormMessage />
  406. </FormItem>
  407. )}
  408. />
  409. <div className="grid grid-cols-4 gap-4">
  410. <FormField
  411. control={createForm.control}
  412. name="receiverProvince"
  413. render={({ field }) => (
  414. <FormItem>
  415. <FormLabel>省份ID</FormLabel>
  416. <FormControl>
  417. <Input type="number" placeholder="省份ID" {...field} />
  418. </FormControl>
  419. <FormMessage />
  420. </FormItem>
  421. )}
  422. />
  423. <FormField
  424. control={createForm.control}
  425. name="receiverCity"
  426. render={({ field }) => (
  427. <FormItem>
  428. <FormLabel>城市ID</FormLabel>
  429. <FormControl>
  430. <Input type="number" placeholder="城市ID" {...field} />
  431. </FormControl>
  432. <FormMessage />
  433. </FormItem>
  434. )}
  435. />
  436. <FormField
  437. control={createForm.control}
  438. name="receiverDistrict"
  439. render={({ field }) => (
  440. <FormItem>
  441. <FormLabel>区县ID</FormLabel>
  442. <FormControl>
  443. <Input type="number" placeholder="区县ID" {...field} />
  444. </FormControl>
  445. <FormMessage />
  446. </FormItem>
  447. )}
  448. />
  449. <FormField
  450. control={createForm.control}
  451. name="receiverTown"
  452. render={({ field }) => (
  453. <FormItem>
  454. <FormLabel>街道ID</FormLabel>
  455. <FormControl>
  456. <Input type="number" placeholder="街道ID" {...field} />
  457. </FormControl>
  458. <FormMessage />
  459. </FormItem>
  460. )}
  461. />
  462. </div>
  463. <FormField
  464. control={createForm.control}
  465. name="isDefault"
  466. render={({ field }) => (
  467. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  468. <div className="space-y-0.5">
  469. <FormLabel className="text-base">设为默认地址</FormLabel>
  470. <FormDescription>将此地址设为用户的默认收货地址</FormDescription>
  471. </div>
  472. <FormControl>
  473. <Switch
  474. checked={field.value === 1}
  475. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  476. />
  477. </FormControl>
  478. </FormItem>
  479. )}
  480. />
  481. <DialogFooter>
  482. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  483. 取消
  484. </Button>
  485. <Button type="submit" disabled={createMutation.isPending}>
  486. 创建
  487. </Button>
  488. </DialogFooter>
  489. </form>
  490. </Form>
  491. ) : (
  492. <Form {...updateForm}>
  493. <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
  494. <FormField
  495. control={updateForm.control}
  496. name="name"
  497. render={({ field }) => (
  498. <FormItem>
  499. <FormLabel>收货人姓名<span className="text-red-500 ml-1">*</span></FormLabel>
  500. <FormControl>
  501. <Input placeholder="请输入收货人姓名" {...field} />
  502. </FormControl>
  503. <FormMessage />
  504. </FormItem>
  505. )}
  506. />
  507. <FormField
  508. control={updateForm.control}
  509. name="phone"
  510. render={({ field }) => (
  511. <FormItem>
  512. <FormLabel>手机号<span className="text-red-500 ml-1">*</span></FormLabel>
  513. <FormControl>
  514. <Input placeholder="请输入手机号" {...field} />
  515. </FormControl>
  516. <FormMessage />
  517. </FormItem>
  518. )}
  519. />
  520. <FormField
  521. control={updateForm.control}
  522. name="address"
  523. render={({ field }) => (
  524. <FormItem>
  525. <FormLabel>详细地址<span className="text-red-500 ml-1">*</span></FormLabel>
  526. <FormControl>
  527. <Input placeholder="请输入详细地址" {...field} />
  528. </FormControl>
  529. <FormMessage />
  530. </FormItem>
  531. )}
  532. />
  533. <div className="grid grid-cols-4 gap-4">
  534. <FormField
  535. control={updateForm.control}
  536. name="receiverProvince"
  537. render={({ field }) => (
  538. <FormItem>
  539. <FormLabel>省份ID</FormLabel>
  540. <FormControl>
  541. <Input type="number" placeholder="省份ID" {...field} />
  542. </FormControl>
  543. <FormMessage />
  544. </FormItem>
  545. )}
  546. />
  547. <FormField
  548. control={updateForm.control}
  549. name="receiverCity"
  550. render={({ field }) => (
  551. <FormItem>
  552. <FormLabel>城市ID</FormLabel>
  553. <FormControl>
  554. <Input type="number" placeholder="城市ID" {...field} />
  555. </FormControl>
  556. <FormMessage />
  557. </FormItem>
  558. )}
  559. />
  560. <FormField
  561. control={updateForm.control}
  562. name="receiverDistrict"
  563. render={({ field }) => (
  564. <FormItem>
  565. <FormLabel>区县ID</FormLabel>
  566. <FormControl>
  567. <Input type="number" placeholder="区县ID" {...field} />
  568. </FormControl>
  569. <FormMessage />
  570. </FormItem>
  571. )}
  572. />
  573. <FormField
  574. control={updateForm.control}
  575. name="receiverTown"
  576. render={({ field }) => (
  577. <FormItem>
  578. <FormLabel>街道ID</FormLabel>
  579. <FormControl>
  580. <Input type="number" placeholder="街道ID" {...field} />
  581. </FormControl>
  582. <FormMessage />
  583. </FormItem>
  584. )}
  585. />
  586. </div>
  587. <FormField
  588. control={updateForm.control}
  589. name="isDefault"
  590. render={({ field }) => (
  591. <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  592. <div className="space-y-0.5">
  593. <FormLabel className="text-base">设为默认地址</FormLabel>
  594. <FormDescription>将此地址设为用户的默认收货地址</FormDescription>
  595. </div>
  596. <FormControl>
  597. <Switch
  598. checked={field.value === 1}
  599. onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
  600. />
  601. </FormControl>
  602. </FormItem>
  603. )}
  604. />
  605. <DialogFooter>
  606. <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
  607. 取消
  608. </Button>
  609. <Button type="submit" disabled={updateMutation.isPending}>
  610. 更新
  611. </Button>
  612. </DialogFooter>
  613. </form>
  614. </Form>
  615. )}
  616. </DialogContent>
  617. </Dialog>
  618. {/* 删除确认对话框 */}
  619. <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
  620. <DialogContent>
  621. <DialogHeader>
  622. <DialogTitle>确认删除</DialogTitle>
  623. <DialogDescription>
  624. 确定要删除这个收货地址吗?此操作无法撤销。
  625. </DialogDescription>
  626. </DialogHeader>
  627. <DialogFooter>
  628. <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
  629. 取消
  630. </Button>
  631. <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
  632. 删除
  633. </Button>
  634. </DialogFooter>
  635. </DialogContent>
  636. </Dialog>
  637. </div>
  638. );
  639. };