feat: 支持微信用户列表展示
This commit is contained in:
195
app/(dashboard)/wx-users/page.tsx
Normal file
195
app/(dashboard)/wx-users/page.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Header } from '@/components/layout/header'
|
||||
import { WxUserDetailDialog } from '@/components/wx-users/wx-user-detail-dialog'
|
||||
import { Spinner } from '@/components/ui/spinner'
|
||||
import { WxUser, WxUserWithProgress } from '@/types'
|
||||
import { apiFetch } from '@/lib/api'
|
||||
import { Search } from 'lucide-react'
|
||||
|
||||
interface UsersResponse {
|
||||
users: WxUser[]
|
||||
meta: { total: number; page: number; limit: number; totalPages: number }
|
||||
}
|
||||
|
||||
export default function WxUsersPage() {
|
||||
const [search, setSearch] = useState('')
|
||||
const [selectedUser, setSelectedUser] = useState<WxUser | null>(null)
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false)
|
||||
|
||||
const { data, isLoading, error } = useQuery<UsersResponse>({
|
||||
queryKey: ['wx-users', search],
|
||||
queryFn: async () => {
|
||||
const res = await apiFetch(`/api/wx-users?search=${encodeURIComponent(search)}`)
|
||||
if (!res.ok) throw new Error('Failed to fetch wx users')
|
||||
return res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: userDetails } = useQuery<WxUserWithProgress>({
|
||||
queryKey: ['wx-users', selectedUser?.id],
|
||||
queryFn: async () => {
|
||||
const res = await apiFetch(`/api/wx-users/${selectedUser?.id}`)
|
||||
if (!res.ok) throw new Error('Failed to fetch wx user details')
|
||||
return res.json()
|
||||
},
|
||||
enabled: !!selectedUser && isDialogOpen,
|
||||
})
|
||||
|
||||
const handleUserClick = (user: WxUser) => {
|
||||
setSelectedUser(user)
|
||||
setIsDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleDialogOpenChange = (open: boolean) => {
|
||||
setIsDialogOpen(open)
|
||||
if (!open) {
|
||||
setSelectedUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (date: Date | string) => {
|
||||
return new Date(date).toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="h-screen flex flex-col">
|
||||
<Header />
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Spinner size="lg" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="h-screen flex flex-col">
|
||||
<Header />
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-red-600">加载失败</p>
|
||||
<Button className="mt-4" onClick={() => window.location.reload()}>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-screen flex flex-col">
|
||||
<Header />
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">小程序账户</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
共 {data?.meta?.total || 0} 个账户
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-6 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="搜索昵称或 OpenID..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
用户
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
OpenID
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
积分
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
注册时间
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{data?.users?.map((user) => (
|
||||
<tr
|
||||
key={user.id}
|
||||
className="hover:bg-gray-50 cursor-pointer"
|
||||
onClick={() => handleUserClick(user)}
|
||||
>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="flex items-center">
|
||||
{user.avatarUrl ? (
|
||||
<img
|
||||
src={user.avatarUrl}
|
||||
alt={user.nickname || 'User'}
|
||||
className="h-10 w-10 rounded-full object-cover mr-3"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center mr-3 text-gray-600 font-medium">
|
||||
{user.nickname?.[0]?.toUpperCase() || 'U'}
|
||||
</div>
|
||||
)}
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{user.nickname || '匿名用户'}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className="text-sm text-gray-500 font-mono text-xs">
|
||||
{user.openid}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
|
||||
{user.points}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{formatDate(user.createdAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{data?.users?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-6 py-12 text-center text-gray-500">
|
||||
暂无账户数据
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<WxUserDetailDialog
|
||||
open={isDialogOpen}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
user={userDetails}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
55
app/api/wx-users/[id]/route.ts
Normal file
55
app/api/wx-users/[id]/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { auth } from '@/lib/auth'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
// GET /api/wx-users/[id] - Get single wx user with level progress
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await auth.api.getSession({
|
||||
headers: request.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id } = await params
|
||||
|
||||
const user = await prisma.wxUser.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
levelProgress: {
|
||||
orderBy: { completedAt: 'desc' },
|
||||
include: {
|
||||
level: {
|
||||
select: {
|
||||
id: true,
|
||||
answer: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'User not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json(user)
|
||||
} catch (error) {
|
||||
console.error('Error fetching wx user:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch wx user' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
68
app/api/wx-users/route.ts
Normal file
68
app/api/wx-users/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { auth } from '@/lib/auth'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
// GET /api/wx-users - Get all wx users with optional search and pagination
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth.api.getSession({
|
||||
headers: request.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const search = searchParams.get('search') || ''
|
||||
const page = parseInt(searchParams.get('page') || '1', 10)
|
||||
const limit = parseInt(searchParams.get('limit') || '20', 10)
|
||||
const skip = (page - 1) * limit
|
||||
|
||||
const where = search
|
||||
? {
|
||||
OR: [
|
||||
{ nickname: { contains: search } },
|
||||
{ openid: { contains: search } },
|
||||
],
|
||||
}
|
||||
: {}
|
||||
|
||||
const [users, total] = await Promise.all([
|
||||
prisma.wxUser.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
openid: true,
|
||||
nickname: true,
|
||||
avatarUrl: true,
|
||||
points: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.wxUser.count({ where }),
|
||||
])
|
||||
|
||||
return NextResponse.json({
|
||||
users,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching wx users:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch wx users' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user