| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678 |
- import React, { useState } from 'react';
- import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
- import { Plus, Search, Edit, Trash2, CreditCard } from 'lucide-react';
- import { format } from 'date-fns';
- import { zhCN } from 'date-fns/locale';
- import { useForm } from 'react-hook-form';
- import { zodResolver } from '@hookform/resolvers/zod';
- import { toast } from 'sonner';
- import { Button } from '@/client/components/ui/button';
- import { Input } from '@/client/components/ui/input';
- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
- import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
- import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
- import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
- import { Badge } from '@/client/components/ui/badge';
- import { Skeleton } from '@/client/components/ui/skeleton';
- import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
- import { userCardClient } from '@/client/api';
- import type { InferRequestType, InferResponseType } from 'hono/client';
- import { CreateUserCardDto, UpdateUserCardDto } from '@d8d/server/modules/user-cards/user-card.schema';
- import { UserSelector } from '@/client/admin/components/UserSelector';
- import { AgentSelector } from '@/client/admin/components/AgentSelector';
- type CreateRequest = InferRequestType<typeof userCardClient.$post>['json'];
- type UpdateRequest = InferRequestType<typeof userCardClient[':id']['$put']>['json'];
- type UserCardResponse = InferResponseType<typeof userCardClient.$get, 200>['data'][0];
- const createFormSchema = CreateUserCardDto;
- const updateFormSchema = UpdateUserCardDto;
- export const UserCardsPage = () => {
- const queryClient = useQueryClient();
- const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '' });
- const [isModalOpen, setIsModalOpen] = useState(false);
- const [isCreateForm, setIsCreateForm] = useState(true);
- const [editingCard, setEditingCard] = useState<UserCardResponse | null>(null);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const [cardToDelete, setCardToDelete] = useState<number | null>(null);
- // 表单实例
- const createForm = useForm<CreateRequest>({
- resolver: zodResolver(createFormSchema),
- defaultValues: {
- userId: 0,
- cardNo: '',
- password: '',
- balance: 0,
- state: 1,
- isDefault: 2
- }
- });
- const updateForm = useForm<UpdateRequest>({
- resolver: zodResolver(updateFormSchema),
- defaultValues: {}
- });
- // 数据查询
- const { data, isLoading, refetch } = useQuery({
- queryKey: ['userCards', searchParams],
- queryFn: async () => {
- const res = await userCardClient.$get({
- query: {
- page: searchParams.page,
- pageSize: searchParams.limit,
- keyword: searchParams.search
- }
- });
- if (res.status !== 200) throw new Error('获取用户卡列表失败');
- return await res.json();
- }
- });
- // 创建用户卡
- const createMutation = useMutation({
- mutationFn: async (data: CreateRequest) => {
- const res = await userCardClient.$post({ json: data });
- if (res.status !== 201) throw new Error('创建用户卡失败');
- return await res.json();
- },
- onSuccess: () => {
- toast.success('用户卡创建成功');
- setIsModalOpen(false);
- createForm.reset();
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '创建用户卡失败');
- }
- });
- // 更新用户卡
- const updateMutation = useMutation({
- mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
- const res = await userCardClient[':id']['$put']({
- param: { id: id.toString() },
- json: data
- });
- if (res.status !== 200) throw new Error('更新用户卡失败');
- return await res.json();
- },
- onSuccess: () => {
- toast.success('用户卡更新成功');
- setIsModalOpen(false);
- updateForm.reset();
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '更新用户卡失败');
- }
- });
- // 删除用户卡
- const deleteMutation = useMutation({
- mutationFn: async (id: number) => {
- const res = await userCardClient[':id']['$delete']({
- param: { id: id.toString() }
- });
- if (res.status !== 204) throw new Error('删除用户卡失败');
- return res;
- },
- onSuccess: () => {
- toast.success('用户卡删除成功');
- setDeleteDialogOpen(false);
- refetch();
- },
- onError: (error) => {
- toast.error(error.message || '删除用户卡失败');
- }
- });
- // 处理搜索
- const handleSearch = (e: React.FormEvent) => {
- e.preventDefault();
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 处理创建用户卡
- const handleCreateCard = () => {
- setIsCreateForm(true);
- setEditingCard(null);
- createForm.reset();
- setIsModalOpen(true);
- };
- // 处理编辑用户卡
- const handleEditCard = (card: UserCardResponse) => {
- setIsCreateForm(false);
- setEditingCard(card);
- updateForm.reset({
- userId: card.userId,
- agentId: card.agentId || undefined,
- cardNo: card.cardNo,
- sjtCardNo: card.sjtCardNo || undefined,
- password: card.password,
- authCode: card.authCode || undefined,
- state: card.state,
- balance: card.balance,
- isDefault: card.isDefault
- });
- setIsModalOpen(true);
- };
- // 处理删除用户卡
- const handleDeleteCard = (id: number) => {
- setCardToDelete(id);
- setDeleteDialogOpen(true);
- };
- // 确认删除
- const confirmDelete = () => {
- if (cardToDelete) {
- deleteMutation.mutate(cardToDelete);
- }
- };
- // 加载状态
- if (isLoading) {
- return (
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <Skeleton className="h-8 w-48" />
- <Skeleton className="h-10 w-32" />
- </div>
-
- <Card>
- <CardContent className="pt-6">
- <div className="space-y-3">
- {[...Array(5)].map((_, i) => (
- <div key={i} className="flex gap-4">
- <Skeleton className="h-10 flex-1" />
- <Skeleton className="h-10 flex-1" />
- <Skeleton className="h-10 flex-1" />
- <Skeleton className="h-10 w-20" />
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- </div>
- );
- }
- return (
- <div className="space-y-4">
- {/* 页面标题 */}
- <div className="flex justify-between items-center">
- <div>
- <h1 className="text-2xl font-bold">用户卡管理</h1>
- <p className="text-muted-foreground">管理用户卡和余额信息</p>
- </div>
- <Button onClick={handleCreateCard}>
- <Plus className="mr-2 h-4 w-4" />
- 创建用户卡
- </Button>
- </div>
- {/* 搜索区域 */}
- <Card>
- <CardHeader>
- <CardTitle>用户卡列表</CardTitle>
- <CardDescription>查看和管理所有用户卡</CardDescription>
- </CardHeader>
- <CardContent>
- <form onSubmit={handleSearch} className="flex gap-2">
- <div className="relative flex-1 max-w-sm">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="搜索卡号、盛京通卡号..."
- value={searchParams.search}
- onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
- className="pl-8"
- />
- </div>
- <Button type="submit" variant="outline">
- 搜索
- </Button>
- </form>
- </CardContent>
- </Card>
- {/* 数据表格 */}
- <Card>
- <CardContent className="p-0">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>ID</TableHead>
- <TableHead>用户</TableHead>
- <TableHead>卡号</TableHead>
- <TableHead>盛京通卡号</TableHead>
- <TableHead>代理商</TableHead>
- <TableHead>余额</TableHead>
- <TableHead>状态</TableHead>
- <TableHead>默认</TableHead>
- <TableHead>创建时间</TableHead>
- <TableHead className="text-right">操作</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {data?.data.map((card) => (
- <TableRow key={card.id}>
- <TableCell>{card.id}</TableCell>
- <TableCell>{card.user?.name || card.user?.username || '-'}</TableCell>
- <TableCell>{card.cardNo}</TableCell>
- <TableCell>{card.sjtCardNo || '-'}</TableCell>
- <TableCell>{card.agent?.name || '-'}</TableCell>
- <TableCell>¥{card.balance.toFixed(2)}</TableCell>
- <TableCell>
- <Badge variant={card.state === 1 ? 'default' : 'secondary'}>
- {card.state === 1 ? '绑定' : '解绑'}
- </Badge>
- </TableCell>
- <TableCell>
- <Badge variant={card.isDefault === 1 ? 'default' : 'secondary'}>
- {card.isDefault === 1 ? '是' : '否'}
- </Badge>
- </TableCell>
- <TableCell>
- {format(new Date(card.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
- </TableCell>
- <TableCell className="text-right">
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleEditCard(card)}
- >
- <Edit className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleDeleteCard(card.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
-
- {data?.data.length === 0 && (
- <div className="text-center py-8">
- <p className="text-muted-foreground">暂无用户卡数据</p>
- </div>
- )}
- </CardContent>
- </Card>
- {/* 分页 */}
- {data && data.data.length > 0 && (
- <DataTablePagination
- currentPage={searchParams.page}
- pageSize={searchParams.limit}
- totalCount={data.pagination.total || 0}
- onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
- />
- )}
- {/* 创建/编辑模态框 */}
- <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
- <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
- <DialogHeader>
- <DialogTitle>{isCreateForm ? '创建用户卡' : '编辑用户卡'}</DialogTitle>
- <DialogDescription>
- {isCreateForm ? '创建一个新的用户卡' : '编辑现有用户卡信息'}
- </DialogDescription>
- </DialogHeader>
- {isCreateForm ? (
- <Form {...createForm}>
- <form onSubmit={createForm.handleSubmit((data) => createMutation.mutate(data))} className="space-y-4">
- <FormField
- control={createForm.control}
- name="userId"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 用户 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <UserSelector
- value={field.value}
- onChange={field.onChange}
- placeholder="选择用户"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="cardNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 卡号 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <Input placeholder="请输入卡号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 密码 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <Input type="password" placeholder="请输入密码" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="agentId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>代理商</FormLabel>
- <FormControl>
- <AgentSelector
- value={field.value || undefined}
- onChange={field.onChange}
- placeholder="选择代理商"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="sjtCardNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel>盛京通卡号</FormLabel>
- <FormControl>
- <Input placeholder="请输入盛京通卡号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="balance"
- render={({ field }) => (
- <FormItem>
- <FormLabel>初始余额</FormLabel>
- <FormControl>
- <Input
- type="number"
- step="0.01"
- placeholder="0.00"
- {...field}
- onChange={(e) => field.onChange(parseFloat(e.target.value))}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="state"
- render={({ field }) => (
- <FormItem>
- <FormLabel>状态</FormLabel>
- <FormControl>
- <select
- {...field}
- className="w-full px-3 py-2 border rounded-md"
- onChange={(e) => field.onChange(parseInt(e.target.value))}
- >
- <option value={1}>绑定</option>
- <option value={2}>解绑</option>
- </select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="isDefault"
- render={({ field }) => (
- <FormItem>
- <FormLabel>是否默认</FormLabel>
- <FormControl>
- <select
- {...field}
- className="w-full px-3 py-2 border rounded-md"
- onChange={(e) => field.onChange(parseInt(e.target.value))}
- >
- <option value={1}>是</option>
- <option value={2}>否</option>
- </select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit" disabled={createMutation.isPending}>
- {createMutation.isPending ? '创建中...' : '创建'}
- </Button>
- </DialogFooter>
- </form>
- </Form>
- ) : (
- <Form {...updateForm}>
- <form onSubmit={updateForm.handleSubmit((data) => updateMutation.mutate({ id: editingCard!.id, data }))} className="space-y-4">
- <FormField
- control={updateForm.control}
- name="userId"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 用户 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <UserSelector
- value={field.value || editingCard?.userId || 0}
- onChange={field.onChange}
- placeholder="选择用户"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="cardNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 卡号 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <Input placeholder="请输入卡号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel className="flex items-center">
- 密码 <span className="text-red-500 ml-1">*</span>
- </FormLabel>
- <FormControl>
- <Input type="password" placeholder="请输入密码" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="agentId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>代理商</FormLabel>
- <FormControl>
- <AgentSelector
- value={field.value || editingCard?.agentId || undefined}
- onChange={field.onChange}
- placeholder="选择代理商"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="sjtCardNo"
- render={({ field }) => (
- <FormItem>
- <FormLabel>盛京通卡号</FormLabel>
- <FormControl>
- <Input placeholder="请输入盛京通卡号" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="balance"
- render={({ field }) => (
- <FormItem>
- <FormLabel>余额</FormLabel>
- <FormControl>
- <Input
- type="number"
- step="0.01"
- placeholder="0.00"
- {...field}
- onChange={(e) => field.onChange(parseFloat(e.target.value))}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="state"
- render={({ field }) => (
- <FormItem>
- <FormLabel>状态</FormLabel>
- <FormControl>
- <select
- {...field}
- className="w-full px-3 py-2 border rounded-md"
- onChange={(e) => field.onChange(parseInt(e.target.value))}
- >
- <option value={1}>绑定</option>
- <option value={2}>解绑</option>
- </select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="isDefault"
- render={({ field }) => (
- <FormItem>
- <FormLabel>是否默认</FormLabel>
- <FormControl>
- <select
- {...field}
- className="w-full px-3 py-2 border rounded-md"
- onChange={(e) => field.onChange(parseInt(e.target.value))}
- >
- <option value={1}>是</option>
- <option value={2}>否</option>
- </select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit" disabled={updateMutation.isPending}>
- {updateMutation.isPending ? '更新中...' : '更新'}
- </Button>
- </DialogFooter>
- </form>
- </Form>
- )}
- </DialogContent>
- </Dialog>
- {/* 删除确认对话框 */}
- <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>确认删除</DialogTitle>
- <DialogDescription>
- 确定要删除这张用户卡吗?此操作将同时删除相关的余额记录。
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
- 取消
- </Button>
- <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
- {deleteMutation.isPending ? '删除中...' : '删除'}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
- };
|