| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723 |
- import React, { useState, useMemo, useCallback } from 'react';
- import { useQuery } from '@tanstack/react-query';
- import { format } from 'date-fns';
- import { Plus, Search, Edit, Trash2, Filter, X } from 'lucide-react';
- import { tenantClient } from '@/api/tenantClient';
- import type { InferRequestType, InferResponseType } from 'hono/client';
- import { Button, Input, Card, CardContent, CardDescription, CardHeader, CardTitle, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, Badge, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, Skeleton, Switch, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Popover, PopoverContent, PopoverTrigger, Calendar } from '@d8d/shared-ui-components';
- import { DataTablePagination } from '@/components/DataTablePagination';
- import { useForm } from 'react-hook-form';
- import { zodResolver } from '@hookform/resolvers/zod';
- import { toast } from 'sonner';
- import { CreateTenantDto, UpdateTenantDto } from '@d8d/tenant-module-mt/schemas';
- import { cn } from '@/utils/cn';
- import { formatTenantStatus } from '@/utils/formatTenantStatus';
- // 使用RPC方式提取类型
- type CreateTenantRequest = InferRequestType<typeof tenantClient.index.$post>['json'];
- type UpdateTenantRequest = InferRequestType<typeof tenantClient[':id']['$put']>['json'];
- type TenantResponse = InferResponseType<typeof tenantClient.index.$get, 200>['data'][0];
- // 直接使用后端定义的 schema
- const createTenantFormSchema = CreateTenantDto;
- const updateTenantFormSchema = UpdateTenantDto;
- type CreateTenantFormData = CreateTenantRequest;
- type UpdateTenantFormData = UpdateTenantRequest;
- export const TenantsPage = () => {
- const [searchParams, setSearchParams] = useState({
- page: 1,
- limit: 10,
- keyword: ''
- });
- const [filters, setFilters] = useState({
- status: undefined as number | undefined,
- createdAt: undefined as { gte?: string; lte?: string } | undefined
- });
- const [showFilters, setShowFilters] = useState(false);
- const [isModalOpen, setIsModalOpen] = useState(false);
- const [editingTenant, setEditingTenant] = useState<TenantResponse | null>(null);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const [tenantToDelete, setTenantToDelete] = useState<number | null>(null);
- const [isCreateForm, setIsCreateForm] = useState(true);
- const createForm = useForm<CreateTenantFormData>({
- resolver: zodResolver(createTenantFormSchema),
- defaultValues: {
- name: '',
- code: '',
- phone: null,
- contactName: null,
- status: 1,
- config: null,
- rsaPublicKey: null,
- aesKey: null,
- },
- });
- const updateForm = useForm<UpdateTenantFormData>({
- resolver: zodResolver(updateTenantFormSchema),
- defaultValues: {
- name: undefined,
- code: undefined,
- phone: null,
- contactName: null,
- status: undefined,
- config: null,
- rsaPublicKey: null,
- aesKey: null,
- },
- });
- const { data: tenantsData, isLoading, refetch } = useQuery({
- queryKey: ['tenants', searchParams, filters],
- queryFn: async () => {
- const filterParams: Record<string, unknown> = {};
- if (filters.status !== undefined) {
- filterParams.status = filters.status;
- }
- if (filters.createdAt) {
- filterParams.createdAt = filters.createdAt;
- }
- const res = await tenantClient.index.$get({
- query: {
- page: searchParams.page,
- pageSize: searchParams.limit,
- keyword: searchParams.keyword,
- filters: Object.keys(filterParams).length > 0 ? JSON.stringify(filterParams) : undefined
- }
- });
- if (res.status !== 200) {
- throw new Error('获取租户列表失败');
- }
- return await res.json();
- }
- });
- const tenants = tenantsData?.data || [];
- const totalCount = tenantsData?.pagination?.total || 0;
- // 防抖搜索函数
- const debounce = (func: Function, delay: number) => {
- let timeoutId: NodeJS.Timeout;
- return (...args: any[]) => {
- clearTimeout(timeoutId);
- timeoutId = setTimeout(() => func(...args), delay);
- };
- };
- // 使用useCallback包装防抖搜索
- const debouncedSearch = useCallback(
- debounce((keyword: string) => {
- setSearchParams(prev => ({ ...prev, keyword, page: 1 }));
- }, 300),
- []
- );
- // 处理搜索输入变化
- const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const keyword = e.target.value;
- setSearchParams(prev => ({ ...prev, keyword }));
- debouncedSearch(keyword);
- };
- // 处理搜索表单提交
- const handleSearch = (e: React.FormEvent) => {
- e.preventDefault();
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 处理分页
- const handlePageChange = (page: number, limit: number) => {
- setSearchParams(prev => ({ ...prev, page, limit }));
- };
- // 处理过滤条件变化
- const handleFilterChange = (newFilters: Partial<typeof filters>) => {
- setFilters(prev => ({ ...prev, ...newFilters }));
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 重置所有过滤条件
- const resetFilters = () => {
- setFilters({
- status: undefined,
- createdAt: undefined
- });
- setSearchParams(prev => ({ ...prev, page: 1 }));
- };
- // 检查是否有活跃的过滤条件
- const hasActiveFilters = useMemo(() => {
- return filters.status !== undefined ||
- filters.createdAt !== undefined;
- }, [filters]);
- // 打开创建租户对话框
- const handleCreateTenant = () => {
- setEditingTenant(null);
- setIsCreateForm(true);
- createForm.reset({
- name: '',
- code: '',
- phone: null,
- contactName: null,
- status: 1,
- config: null,
- rsaPublicKey: null,
- aesKey: null,
- });
- setIsModalOpen(true);
- };
- // 打开编辑租户对话框
- const handleEditTenant = (tenant: TenantResponse) => {
- setEditingTenant(tenant);
- setIsCreateForm(false);
- updateForm.reset({
- name: tenant.name,
- code: tenant.code,
- phone: tenant.phone,
- contactName: tenant.contactName,
- status: tenant.status,
- config: tenant.config,
- rsaPublicKey: tenant.rsaPublicKey,
- aesKey: tenant.aesKey,
- });
- setIsModalOpen(true);
- };
- // 处理创建表单提交
- const handleCreateSubmit = async (data: CreateTenantFormData) => {
- try {
- const res = await tenantClient.index.$post({
- json: data
- });
- if (res.status !== 201) {
- throw new Error('创建租户失败');
- }
- toast.success('租户创建成功');
- setIsModalOpen(false);
- refetch();
- } catch {
- toast.error('创建失败,请重试');
- }
- };
- // 处理更新表单提交
- const handleUpdateSubmit = async (data: UpdateTenantFormData) => {
- if (!editingTenant) return;
- try {
- const res = await tenantClient[':id']['$put']({
- param: { id: editingTenant.id },
- json: data
- });
- if (res.status !== 200) {
- throw new Error('更新租户失败');
- }
- toast.success('租户更新成功');
- setIsModalOpen(false);
- refetch();
- } catch {
- toast.error('更新失败,请重试');
- }
- };
- // 处理删除租户
- const handleDeleteTenant = (id: number) => {
- setTenantToDelete(id);
- setDeleteDialogOpen(true);
- };
- const confirmDelete = async () => {
- if (!tenantToDelete) return;
- try {
- const res = await tenantClient[':id']['$delete']({
- param: { id: tenantToDelete }
- });
- if (res.status !== 204) {
- throw new Error('删除租户失败');
- }
- toast.success('租户删除成功');
- refetch();
- } catch {
- toast.error('删除失败,请重试');
- } finally {
- setDeleteDialogOpen(false);
- setTenantToDelete(null);
- }
- };
- // 渲染表格部分的骨架屏
- const renderTableSkeleton = () => (
- <div className="space-y-2">
- {Array.from({ length: 5 }).map((_, index) => (
- <div key={index} className="flex space-x-4">
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 flex-1" />
- <Skeleton className="h-4 w-16" />
- </div>
- ))}
- </div>
- );
- return (
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <h1 className="text-2xl font-bold">租户管理</h1>
- <Button onClick={handleCreateTenant}>
- <Plus className="mr-2 h-4 w-4" />
- 创建租户
- </Button>
- </div>
- <Card>
- <CardHeader>
- <CardTitle>租户列表</CardTitle>
- <CardDescription>
- 管理系统中的所有租户,共 {totalCount} 个租户
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="mb-4 space-y-4">
- <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.keyword}
- onChange={handleSearchChange}
- className="pl-8"
- />
- </div>
- <Button type="submit" variant="outline">
- 搜索
- </Button>
- <Button
- type="button"
- variant="outline"
- onClick={() => setShowFilters(!showFilters)}
- className="flex items-center gap-2"
- >
- <Filter className="h-4 w-4" />
- 高级筛选
- {hasActiveFilters && (
- <Badge variant="secondary" className="ml-1">
- {Object.values(filters).filter(v =>
- v !== undefined &&
- (!Array.isArray(v) || v.length > 0)
- ).length}
- </Badge>
- )}
- </Button>
- {hasActiveFilters && (
- <Button
- type="button"
- variant="ghost"
- onClick={resetFilters}
- className="flex items-center gap-2"
- >
- <X className="h-4 w-4" />
- 重置
- </Button>
- )}
- </form>
- {showFilters && (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg bg-muted/50">
- {/* 状态筛选 */}
- <div className="space-y-2">
- <label className="text-sm font-medium">租户状态</label>
- <Select
- value={filters.status === undefined ? 'all' : filters.status.toString()}
- onValueChange={(value) =>
- handleFilterChange({
- status: value === 'all' ? undefined : parseInt(value)
- })
- }
- >
- <SelectTrigger>
- <SelectValue placeholder="选择状态" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">全部状态</SelectItem>
- <SelectItem value="1">启用</SelectItem>
- <SelectItem value="2">禁用</SelectItem>
- </SelectContent>
- </Select>
- </div>
- {/* 创建时间筛选 */}
- <div className="space-y-2">
- <label className="text-sm font-medium">创建时间</label>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- className={cn(
- "w-full justify-start text-left font-normal",
- !filters.createdAt && "text-muted-foreground"
- )}
- >
- {filters.createdAt ?
- `${filters.createdAt.gte || ''} 至 ${filters.createdAt.lte || ''}` :
- '选择日期范围'
- }
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-auto p-0" align="start">
- <Calendar
- mode="range"
- selected={{
- from: filters.createdAt?.gte ? new Date(filters.createdAt.gte) : undefined,
- to: filters.createdAt?.lte ? new Date(filters.createdAt.lte) : undefined
- }}
- onSelect={(range) => {
- handleFilterChange({
- createdAt: range?.from && range?.to ? {
- gte: format(range.from, 'yyyy-MM-dd'),
- lte: format(range.to, 'yyyy-MM-dd')
- } : undefined
- });
- }}
- initialFocus
- />
- </PopoverContent>
- </Popover>
- </div>
- </div>
- )}
- {/* 过滤条件标签 */}
- {hasActiveFilters && (
- <div className="flex flex-wrap gap-2">
- {filters.status !== undefined && (
- <Badge variant="secondary" className="flex items-center gap-1">
- 状态: {filters.status === 1 ? '启用' : '禁用'}
- <X
- className="h-3 w-3 cursor-pointer"
- onClick={() => handleFilterChange({ status: undefined })}
- />
- </Badge>
- )}
- {filters.createdAt && (
- <Badge variant="secondary" className="flex items-center gap-1">
- 创建时间: {filters.createdAt.gte || ''} 至 {filters.createdAt.lte || ''}
- <X
- className="h-3 w-3 cursor-pointer"
- onClick={() => handleFilterChange({ createdAt: undefined })}
- />
- </Badge>
- )}
- </div>
- )}
- </div>
- <div className="rounded-md border">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>租户名称</TableHead>
- <TableHead>租户代码</TableHead>
- <TableHead>联系人</TableHead>
- <TableHead>联系电话</TableHead>
- <TableHead>状态</TableHead>
- <TableHead>创建时间</TableHead>
- <TableHead className="text-right">操作</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {isLoading ? (
- // 显示表格骨架屏
- <TableRow>
- <TableCell colSpan={7} className="p-4">
- {renderTableSkeleton()}
- </TableCell>
- </TableRow>
- ) : (
- // 显示实际租户数据
- tenants.map((tenant) => {
- const statusInfo = formatTenantStatus(tenant.status);
- return (
- <TableRow key={tenant.id}>
- <TableCell className="font-medium">{tenant.name || '-'}</TableCell>
- <TableCell>{tenant.code}</TableCell>
- <TableCell>{tenant.contactName || '-'}</TableCell>
- <TableCell>{tenant.phone || '-'}</TableCell>
- <TableCell>
- <Badge variant={statusInfo.variant}>
- {statusInfo.label}
- </Badge>
- </TableCell>
- <TableCell>
- {format(new Date(tenant.createdAt), 'yyyy-MM-dd HH:mm')}
- </TableCell>
- <TableCell className="text-right">
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleEditTenant(tenant)}
- >
- <Edit className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={() => handleDeleteTenant(tenant.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- </TableCell>
- </TableRow>
- );
- })
- )}
- </TableBody>
- </Table>
- </div>
- <DataTablePagination
- currentPage={searchParams.page}
- totalCount={totalCount}
- pageSize={searchParams.limit}
- onPageChange={handlePageChange}
- />
- </CardContent>
- </Card>
- {/* 创建/编辑租户对话框 */}
- <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
- <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
- <DialogHeader>
- <DialogTitle>
- {editingTenant ? '编辑租户' : '创建租户'}
- </DialogTitle>
- <DialogDescription>
- {editingTenant ? '编辑现有租户信息' : '创建一个新的租户'}
- </DialogDescription>
- </DialogHeader>
- {isCreateForm ? (
- <Form {...createForm}>
- <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
- <FormField
- control={createForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>租户名称</FormLabel>
- <FormControl>
- <Input placeholder="请输入租户名称" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="code"
- 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="contactName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>联系人姓名</FormLabel>
- <FormControl>
- <Input placeholder="请输入联系人姓名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="phone"
- render={({ field }) => (
- <FormItem>
- <FormLabel>联系电话</FormLabel>
- <FormControl>
- <Input placeholder="请输入联系电话" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={createForm.control}
- name="status"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
- <div className="space-y-0.5">
- <FormLabel className="text-base">租户状态</FormLabel>
- <FormDescription>
- 禁用后租户将无法使用系统
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value === 1}
- onCheckedChange={(checked) => field.onChange(checked ? 1 : 2)}
- />
- </FormControl>
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit">
- 创建租户
- </Button>
- </DialogFooter>
- </form>
- </Form>
- ) : (
- <Form {...updateForm}>
- <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
- <FormField
- control={updateForm.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>租户名称</FormLabel>
- <FormControl>
- <Input placeholder="请输入租户名称" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="code"
- 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="contactName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>联系人姓名</FormLabel>
- <FormControl>
- <Input placeholder="请输入联系人姓名" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="phone"
- render={({ field }) => (
- <FormItem>
- <FormLabel>联系电话</FormLabel>
- <FormControl>
- <Input placeholder="请输入联系电话" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={updateForm.control}
- name="status"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
- <div className="space-y-0.5">
- <FormLabel className="text-base">租户状态</FormLabel>
- <FormDescription>
- 禁用后租户将无法使用系统
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value === 1}
- onCheckedChange={(checked) => field.onChange(checked ? 1 : 2)}
- />
- </FormControl>
- </FormItem>
- )}
- />
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
- 取消
- </Button>
- <Button type="submit">
- 更新租户
- </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}>
- 删除
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
- };
|