feat: 支持配置微信用户已通关关卡

This commit is contained in:
richarjiang
2026-04-19 14:28:36 +08:00
parent 6e19bfa661
commit f3f27def2b
19 changed files with 7095 additions and 545 deletions

5
.claude/settings.json Normal file
View File

@@ -0,0 +1,5 @@
{
"enabledPlugins": {
"code-simplifier@claude-plugins-official": true
}
}

View File

@@ -1,10 +1,10 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Header } from '@/components/layout/header'
import { LevelList } from '@/components/levels/level-list'
import { LevelTable } from '@/components/levels/level-table'
import { LevelDialog } from '@/components/levels/level-dialog'
import { Spinner } from '@/components/ui/spinner'
import { Level, LevelFormData } from '@/types'
@@ -83,25 +83,6 @@ export default function LevelsPage() {
},
})
// Reorder mutation
const reorderMutation = useMutation({
mutationFn: async (orders: { id: string; sortOrder: number }[]) => {
const res = await apiFetch('/api/levels/reorder', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orders }),
})
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Failed to reorder levels')
}
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['levels'] })
},
})
const handleOpenCreate = () => {
setEditingLevel(null)
setIsDialogOpen(true)
@@ -130,13 +111,6 @@ export default function LevelsPage() {
}
}
const handleReorder = useCallback(
(orders: { id: string; sortOrder: number }[]) => {
reorderMutation.mutate(orders)
},
[reorderMutation]
)
if (isLoading) {
return (
<div className="h-screen flex items-center justify-center">
@@ -165,7 +139,7 @@ export default function LevelsPage() {
<div className="h-screen flex flex-col">
<Header />
<div className="flex-1 overflow-auto p-6">
<div className="max-w-4xl mx-auto">
<div>
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold"></h1>
@@ -179,11 +153,11 @@ export default function LevelsPage() {
</Button>
</div>
<LevelList
<LevelTable
levels={levels || []}
onReorder={handleReorder}
onEdit={handleOpenEdit}
onDelete={handleDelete}
deleteConfirmId={deleteConfirmId}
/>
</div>
</div>

View File

@@ -1,64 +1,127 @@
'use client'
import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import Image from 'next/image'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Header } from '@/components/layout/header'
import { Spinner } from '@/components/ui/spinner'
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 { WxUser, WxUserDetailResponse } from '@/types'
import { Search } from 'lucide-react'
interface UsersResponse {
users: WxUser[]
meta: { total: number; page: number; limit: number; totalPages: number }
meta: { total: number }
}
export default function WxUsersPage() {
const queryClient = useQueryClient()
const [search, setSearch] = useState('')
const [selectedUser, setSelectedUser] = useState<WxUser | null>(null)
const [isDialogOpen, setIsDialogOpen] = useState(false)
const queryClient = useQueryClient()
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')
if (!res.ok) {
const payload = await res.json().catch(() => null)
throw new Error(payload?.error || 'Failed to fetch wx users')
}
return res.json()
},
})
const { data: userDetails } = useQuery<WxUserWithProgress>({
queryKey: ['wx-users', selectedUser?.id],
const { data: userDetails, isLoading: isDetailLoading } = useQuery<WxUserDetailResponse>({
queryKey: ['wx-user-detail', 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')
if (!res.ok) {
const payload = await res.json().catch(() => null)
throw new Error(payload?.error || 'Failed to fetch wx user details')
}
return res.json()
},
enabled: !!selectedUser && isDialogOpen,
})
const handleUserClick = (user: WxUser) => {
const syncProgressMutation = useMutation({
mutationFn: async ({ userId, levelIds }: { userId: string; levelIds: string[] }) => {
const res = await apiFetch('/api/wx-users/level-progress', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId, levelIds }),
})
if (!res.ok) {
const payload = await res.json().catch(() => null)
throw new Error(payload?.error || 'Failed to update level progress')
}
return res.json()
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['wx-users'] }),
queryClient.invalidateQueries({ queryKey: ['wx-user-detail', selectedUser?.id] }),
])
},
})
const clearProgressMutation = useMutation({
mutationFn: async (userId: string) => {
const res = await apiFetch('/api/wx-users/level-progress', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId }),
})
if (!res.ok) {
const payload = await res.json().catch(() => null)
throw new Error(payload?.error || 'Failed to clear level progress')
}
return res.json()
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['wx-users'] }),
queryClient.invalidateQueries({ queryKey: ['wx-user-detail', selectedUser?.id] }),
])
},
})
const handleOpenDetail = (user: WxUser) => {
setSelectedUser(user)
setIsDialogOpen(true)
}
const handleDialogOpenChange = (open: boolean) => {
const handleDialogChange = (open: boolean) => {
setIsDialogOpen(open)
if (!open) {
setSelectedUser(null)
}
}
const handleDeleted = () => {
queryClient.invalidateQueries({ queryKey: ['wx-users'] })
const handleSaveProgress = async (levelIds: string[]) => {
if (!selectedUser) return
await syncProgressMutation.mutateAsync({ userId: selectedUser.id, levelIds })
}
const handleClearAll = async () => {
if (!selectedUser) return
await clearProgressMutation.mutateAsync(selectedUser.id)
}
const formatDate = (date: Date | string) => {
return new Date(date).toLocaleDateString('zh-CN', {
return new Date(date).toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
@@ -84,8 +147,8 @@ export default function WxUsersPage() {
<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()}>
<p className="text-red-600">{error.message || '加载失败'}</p>
<Button className="mt-4" onClick={() => queryClient.invalidateQueries({ queryKey: ['wx-users'] })}>
</Button>
</div>
@@ -97,90 +160,99 @@ export default function WxUsersPage() {
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 className="flex-1 overflow-auto bg-slate-50 p-6">
<div className="mx-auto max-w-7xl">
<div className="mb-6 flex items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold"></h1>
<p className="text-gray-500 mt-1">
{data?.meta?.total || 0}
<h1 className="text-2xl font-bold text-slate-900"></h1>
<p className="mt-1 text-slate-500">
{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" />
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<Input
type="text"
placeholder="搜索昵称或 OpenID..."
placeholder="搜索昵称或 OpenID"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
className="border-slate-200 bg-white 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">
<div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
<table className="min-w-full divide-y divide-slate-200">
<thead className="bg-slate-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
<th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
<th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
OpenID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
<th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
<th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
</th>
<th className="px-6 py-3 text-right text-xs font-semibold uppercase tracking-wider text-slate-500">
</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">
<tbody className="divide-y divide-slate-200 bg-white">
{data?.users.map((user) => (
<tr key={user.id} className="hover:bg-slate-50">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
{user.avatarUrl ? (
<img
src={user.avatarUrl}
alt={user.nickname || 'User'}
className="h-10 w-10 rounded-full object-cover mr-3"
/>
<div className="relative h-10 w-10 overflow-hidden rounded-full bg-slate-100">
<Image
src={user.avatarUrl}
alt={user.nickname || 'User'}
fill
sizes="40px"
className="object-cover"
/>
</div>
) : (
<div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center mr-3 text-gray-600 font-medium">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-slate-200 font-medium text-slate-600">
{user.nickname?.[0]?.toUpperCase() || 'U'}
</div>
)}
<span className="text-sm font-medium text-gray-900">
{user.nickname || '匿名用户'}
</span>
<div className="min-w-0">
<div className="truncate font-medium text-slate-900">
{user.nickname || '匿名用户'}
</div>
<div className="text-sm text-slate-500"> {user.stamina}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="text-sm text-gray-500 font-mono text-xs">
{user.openid}
<td className="px-6 py-4 align-top">
<code className="text-xs text-slate-500">{user.openid}</code>
</td>
<td className="px-6 py-4 align-top">
<span className="inline-flex rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-medium text-emerald-700">
{user.completedLevelCount}
</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">
<td className="px-6 py-4 align-top text-sm text-slate-500">
{formatDate(user.createdAt)}
</td>
<td className="px-6 py-4 text-right align-top">
<Button size="sm" variant="outline" onClick={() => handleOpenDetail(user)}>
</Button>
</td>
</tr>
))}
{data?.users?.length === 0 && (
{data?.users.length === 0 && (
<tr>
<td colSpan={4} className="px-6 py-12 text-center text-gray-500">
<td colSpan={5} className="px-6 py-16 text-center text-sm text-slate-500">
</td>
</tr>
)}
@@ -190,11 +262,21 @@ export default function WxUsersPage() {
</div>
</div>
{isDialogOpen && selectedUser && isDetailLoading && !userDetails ? (
<div className="pointer-events-none fixed inset-0 z-40 flex items-center justify-center bg-black/20">
<div className="rounded-full bg-white p-4 shadow-lg">
<Spinner size="lg" />
</div>
</div>
) : null}
<WxUserDetailDialog
open={isDialogOpen}
onOpenChange={handleDialogOpenChange}
onOpenChange={handleDialogChange}
user={userDetails}
onDeleted={handleDeleted}
isSaving={syncProgressMutation.isPending || clearProgressMutation.isPending}
onSave={handleSaveProgress}
onClearAll={handleClearAll}
/>
</div>
)

View File

@@ -2,6 +2,8 @@ import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { getTempKey, getBucketConfig } from '@/lib/cos'
export const dynamic = 'force-dynamic'
// GET /api/cos/temp-key - Get temporary COS upload credentials
export async function GET(request: NextRequest) {
try {

View File

@@ -40,11 +40,11 @@ export async function POST(request: NextRequest) {
}
const body = await request.json()
const { imageUrl, answer, hint1, hint2, hint3 } = body
const { image1Url, image1Description, image2Url, image2Description, answer, punchline, hint1, hint2, hint3 } = body
if (!imageUrl || !answer) {
if (!image1Url || !image2Url || !answer) {
return NextResponse.json(
{ error: 'imageUrl and answer are required' },
{ error: 'image1Url, image2Url and answer are required' },
{ status: 400 }
)
}
@@ -59,8 +59,12 @@ export async function POST(request: NextRequest) {
const level = await prisma.level.create({
data: {
id: uuidv4(),
imageUrl,
image1Url,
image1Description: image1Description || null,
image2Url,
image2Description: image2Description || null,
answer,
punchline: punchline || null,
hint1: hint1 || null,
hint2: hint2 || null,
hint3: hint3 || null,
@@ -90,7 +94,7 @@ export async function PUT(request: NextRequest) {
}
const body = await request.json()
const { id, imageUrl, answer, hint1, hint2, hint3 } = body
const { id, image1Url, image1Description, image2Url, image2Description, answer, punchline, hint1, hint2, hint3 } = body
if (!id) {
return NextResponse.json({ error: 'id is required' }, { status: 400 })
@@ -99,8 +103,12 @@ export async function PUT(request: NextRequest) {
const level = await prisma.level.update({
where: { id },
data: {
imageUrl,
image1Url,
image1Description: image1Description || null,
image2Url,
image2Description: image2Description || null,
answer,
punchline: punchline || null,
hint1: hint1 || null,
hint2: hint2 || null,
hint3: hint3 || null,

View File

@@ -4,7 +4,7 @@ import { auth } from '@/lib/auth'
export const dynamic = 'force-dynamic'
// GET /api/wx-users/[id] - Get single wx user with level progress
// GET /api/wx-users/[id] - Get a wx user and all levels with completion state
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
@@ -22,14 +22,32 @@ export async function GET(
const user = await prisma.wxUser.findUnique({
where: { id },
include: {
select: {
id: true,
openid: true,
sessionKey: true,
nickname: true,
avatarUrl: true,
stamina: true,
staminaUpdatedAt: true,
createdAt: true,
updatedAt: true,
levelProgress: {
orderBy: { completedAt: 'desc' },
include: {
orderBy: [
{ level: { sortOrder: 'asc' } },
{ completedAt: 'desc' },
],
select: {
id: true,
userId: true,
levelId: true,
completedAt: true,
timeSpent: true,
level: {
select: {
id: true,
answer: true,
sortOrder: true,
},
},
},
@@ -38,13 +56,46 @@ export async function GET(
})
if (!user) {
return NextResponse.json(
{ error: 'User not found' },
{ status: 404 }
)
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
return NextResponse.json(user)
const levels = await prisma.level.findMany({
orderBy: { sortOrder: 'asc' },
select: {
id: true,
answer: true,
sortOrder: true,
},
})
const progressByLevelId = new Map(
user.levelProgress.map((progress) => [progress.levelId, progress])
)
return NextResponse.json({
id: user.id,
openid: user.openid,
sessionKey: user.sessionKey,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
stamina: user.stamina,
staminaUpdatedAt: user.staminaUpdatedAt,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
completedLevelCount: user.levelProgress.length,
assignedLevels: levels.map((level) => {
const progress = progressByLevelId.get(level.id)
return {
id: level.id,
answer: level.answer,
sortOrder: level.sortOrder,
completed: Boolean(progress),
progressId: progress?.id || null,
completedAt: progress?.completedAt || null,
}
}),
})
} catch (error) {
console.error('Error fetching wx user:', error)
return NextResponse.json(

View File

@@ -1,13 +1,12 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { v4 as uuidv4 } from 'uuid'
export const dynamic = 'force-dynamic'
// DELETE /api/wx-users/level-progress - Batch delete level progress
export async function DELETE(
request: NextRequest,
) {
// PUT /api/wx-users/level-progress - Replace a user's completed levels
export async function PUT(request: NextRequest) {
try {
const session = await auth.api.getSession({
headers: request.headers,
@@ -17,28 +16,101 @@ export async function DELETE(
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { ids } = await request.json()
const body = await request.json()
const { userId, levelIds } = body
if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string')) {
if (typeof userId !== 'string' || !userId) {
return NextResponse.json({ error: 'userId is required' }, { status: 400 })
}
if (!Array.isArray(levelIds) || !levelIds.every((id) => typeof id === 'string')) {
return NextResponse.json(
{ error: 'ids must be a non-empty array of strings' },
{ error: 'levelIds must be an array of strings' },
{ status: 400 }
)
}
const result = await prisma.wxUserLevelProgress.deleteMany({
where: {
id: {
in: ids,
},
},
const uniqueLevelIds = Array.from(new Set(levelIds))
const [user, levels] = await Promise.all([
prisma.wxUser.findUnique({
where: { id: userId },
select: { id: true },
}),
prisma.level.findMany({
where: { id: { in: uniqueLevelIds } },
select: { id: true },
}),
])
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
if (levels.length !== uniqueLevelIds.length) {
return NextResponse.json(
{ error: 'Some levels do not exist' },
{ status: 400 }
)
}
await prisma.$transaction(async (tx) => {
await tx.wxUserLevelProgress.deleteMany({
where: { userId },
})
if (uniqueLevelIds.length > 0) {
await tx.wxUserLevelProgress.createMany({
data: uniqueLevelIds.map((levelId) => ({
id: uuidv4(),
userId,
levelId,
timeSpent: 0,
})),
})
}
})
return NextResponse.json({ deleted: result.count })
return NextResponse.json({
success: true,
completedLevelCount: uniqueLevelIds.length,
})
} catch (error) {
console.error('Error deleting level progress:', error)
console.error('Error updating level progress:', error)
return NextResponse.json(
{ error: 'Failed to delete level progress' },
{ error: 'Failed to update level progress' },
{ status: 500 }
)
}
}
// DELETE /api/wx-users/level-progress - Clear all completed levels for a user
export async function DELETE(request: NextRequest) {
try {
const session = await auth.api.getSession({
headers: request.headers,
})
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await request.json()
const { userId } = body
if (typeof userId !== 'string' || !userId) {
return NextResponse.json({ error: 'userId is required' }, { status: 400 })
}
const result = await prisma.wxUserLevelProgress.deleteMany({
where: { userId },
})
return NextResponse.json({ success: true, deleted: result.count })
} catch (error) {
console.error('Error clearing level progress:', error)
return NextResponse.json(
{ error: 'Failed to clear level progress' },
{ status: 500 }
)
}

View File

@@ -4,7 +4,7 @@ import { auth } from '@/lib/auth'
export const dynamic = 'force-dynamic'
// GET /api/wx-users - Get all wx users with optional search and pagination
// GET /api/wx-users - Get all wx users with optional search and completion counts
export async function GET(request: NextRequest) {
try {
const session = await auth.api.getSession({
@@ -17,9 +17,6 @@ export async function GET(request: NextRequest) {
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
? {
@@ -30,32 +27,42 @@ export async function GET(request: NextRequest) {
}
: {}
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,
const users = await prisma.wxUser.findMany({
where,
orderBy: { createdAt: 'desc' },
select: {
id: true,
openid: true,
sessionKey: true,
nickname: true,
avatarUrl: true,
stamina: true,
staminaUpdatedAt: true,
createdAt: true,
updatedAt: true,
_count: {
select: {
levelProgress: true,
},
},
}),
prisma.wxUser.count({ where }),
])
},
})
return NextResponse.json({
users,
users: users.map((user) => ({
id: user.id,
openid: user.openid,
sessionKey: user.sessionKey,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
stamina: user.stamina,
staminaUpdatedAt: user.staminaUpdatedAt,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
completedLevelCount: user._count.levelProgress,
})),
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
total: users.length,
},
})
} catch (error) {

View File

@@ -1,78 +0,0 @@
'use client'
import { Level } from '@/types'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { GripVertical, Pencil, Trash2 } from 'lucide-react'
import Image from 'next/image'
interface LevelCardProps {
level: Level
onEdit: (level: Level) => void
onDelete: (id: string) => void
isDragging?: boolean
}
export function LevelCard({ level, onEdit, onDelete, isDragging }: LevelCardProps) {
return (
<Card
className={`cursor-grab transition-shadow ${
isDragging ? 'shadow-lg opacity-90' : 'hover:shadow-md'
}`}
>
<CardContent className="p-4">
<div className="flex items-start gap-4">
<div className="flex items-center justify-center w-8 h-8 rounded bg-gray-100 text-gray-500 cursor-grab">
<GripVertical className="h-4 w-4" />
</div>
<div className="relative w-20 h-20 rounded-md overflow-hidden bg-gray-100 flex-shrink-0">
{level.imageUrl ? (
<Image
src={level.imageUrl}
alt="关卡图片"
fill
className="object-cover"
sizes="80px"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
</div>
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-lg truncate">{level.answer}</p>
<div className="mt-1 space-y-0.5">
{level.hint1 && (
<p className="text-sm text-gray-500 truncate">1: {level.hint1}</p>
)}
{level.hint2 && (
<p className="text-sm text-gray-500 truncate">2: {level.hint2}</p>
)}
{level.hint3 && (
<p className="text-sm text-gray-500 truncate">3: {level.hint3}</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={() => onEdit(level)}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
onClick={() => onDelete(level.id)}
className="text-red-600 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,156 @@
'use client'
import { ColumnDef } from '@tanstack/react-table'
import { Level } from '@/types'
import { Button } from '@/components/ui/button'
import { Pencil, Trash2 } from 'lucide-react'
import Image from 'next/image'
interface ColumnCallbacks {
onEdit: (level: Level) => void
onDelete: (id: string) => void
deleteConfirmId: string | null
}
export function createColumns({
onEdit,
onDelete,
deleteConfirmId,
}: ColumnCallbacks): ColumnDef<Level>[] {
return [
{
accessorKey: 'sortOrder',
header: '序号',
cell: ({ row }) => (
<span className="text-muted-foreground">{row.original.sortOrder + 1}</span>
),
size: 60,
},
{
id: 'images',
header: '图片',
cell: ({ row }) => {
const { image1Url, image2Url } = row.original
return (
<div className="flex gap-1.5">
<div className="relative w-12 h-12 rounded overflow-hidden bg-gray-100 flex-shrink-0">
{image1Url ? (
<Image
src={image1Url}
alt="图片1"
fill
className="object-cover"
sizes="48px"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400 text-[10px]">
</div>
)}
</div>
<div className="relative w-12 h-12 rounded overflow-hidden bg-gray-100 flex-shrink-0">
{image2Url ? (
<Image
src={image2Url}
alt="图片2"
fill
className="object-cover"
sizes="48px"
/>
) : (
<div className="w-full h-full flex items-center justify-center text-gray-400 text-[10px]">
</div>
)}
</div>
</div>
)
},
size: 120,
},
{
accessorKey: 'answer',
header: '答案',
cell: ({ row }) => (
<span className="font-medium">{row.original.answer}</span>
),
},
{
accessorKey: 'punchline',
header: '谐音梗',
cell: ({ row }) => {
const punchline = row.original.punchline
return punchline ? (
<span className="text-orange-600">{punchline}</span>
) : (
<span className="text-muted-foreground"></span>
)
},
},
{
id: 'hints',
header: '提示',
cell: ({ row }) => {
const { hint1, hint2, hint3 } = row.original
const hints = [hint1, hint2, hint3].filter(Boolean)
return hints.length > 0 ? (
<span className="text-sm text-muted-foreground truncate max-w-[200px] block">
{hints.join('、')}
</span>
) : (
<span className="text-muted-foreground"></span>
)
},
},
{
accessorKey: 'createdAt',
header: '创建时间',
cell: ({ row }) => {
const date = new Date(row.original.createdAt)
return (
<span className="text-sm text-muted-foreground whitespace-nowrap">
{date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})}
</span>
)
},
size: 120,
},
{
id: 'actions',
header: '操作',
cell: ({ row }) => {
const level = row.original
const isConfirming = deleteConfirmId === level.id
return (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() => onEdit(level)}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button
variant="outline"
size="icon"
className={`h-8 w-8 ${
isConfirming
? 'bg-red-600 text-white hover:bg-red-700 border-red-600'
: 'text-red-600 hover:text-red-700 hover:bg-red-50'
}`}
onClick={() => onDelete(level.id)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
)
},
size: 100,
},
]
}

View File

@@ -1,10 +1,9 @@
'use client'
import { useState, useRef, useEffect } from 'react'
import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Dialog,
DialogContent,
@@ -16,7 +15,6 @@ import {
import { Spinner } from '@/components/ui/spinner'
import { Level, LevelFormData } from '@/types'
import { ImageUploader } from './image-uploader'
import { Upload } from 'lucide-react'
interface LevelDialogProps {
open: boolean
@@ -26,8 +24,12 @@ interface LevelDialogProps {
}
const defaultFormData: LevelFormData = {
imageUrl: '',
image1Url: '',
image1Description: '',
image2Url: '',
image2Description: '',
answer: '',
punchline: '',
hint1: '',
hint2: '',
hint3: '',
@@ -37,15 +39,18 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
const [formData, setFormData] = useState<LevelFormData>(defaultFormData)
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState('')
const fileInputRef = useRef<HTMLInputElement>(null)
// Reset form when dialog opens/closes or level changes
useEffect(() => {
if (open) {
if (level) {
setFormData({
imageUrl: level.imageUrl,
image1Url: level.image1Url,
image1Description: level.image1Description || '',
image2Url: level.image2Url,
image2Description: level.image2Description || '',
answer: level.answer,
punchline: level.punchline || '',
hint1: level.hint1 || '',
hint2: level.hint2 || '',
hint3: level.hint3 || '',
@@ -57,16 +62,25 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
}
}, [open, level])
const handleImageUpload = (url: string) => {
setFormData((prev) => ({ ...prev, imageUrl: url }))
const handleImage1Upload = (url: string) => {
setFormData((prev) => ({ ...prev, image1Url: url }))
}
const handleImage2Upload = (url: string) => {
setFormData((prev) => ({ ...prev, image2Url: url }))
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
if (!formData.imageUrl) {
setError('请上传关卡图片')
if (!formData.image1Url) {
setError('请上传图片1')
return
}
if (!formData.image2Url) {
setError('请上传图片2')
return
}
@@ -75,6 +89,11 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
return
}
if (formData.answer.trim().length > 4) {
setError('答案最多4个字')
return
}
setIsLoading(true)
try {
await onSubmit(formData)
@@ -88,7 +107,7 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{level ? '编辑关卡' : '添加关卡'}</DialogTitle>
<DialogDescription>
@@ -102,12 +121,39 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
</div>
)}
<div className="space-y-2">
<Label> *</Label>
<ImageUploader
value={formData.imageUrl}
onChange={handleImageUpload}
/>
{/* 双图上传区域 */}
<div className="grid grid-cols-2 gap-4">
{/* 图片1 */}
<div className="space-y-2">
<Label>1 *</Label>
<ImageUploader
value={formData.image1Url}
onChange={handleImage1Upload}
/>
<Input
value={formData.image1Description}
onChange={(e) =>
setFormData((prev) => ({ ...prev, image1Description: e.target.value }))
}
placeholder="图片1描述 (可选)"
/>
</div>
{/* 图片2 */}
<div className="space-y-2">
<Label>2 *</Label>
<ImageUploader
value={formData.image2Url}
onChange={handleImage2Upload}
/>
<Input
value={formData.image2Description}
onChange={(e) =>
setFormData((prev) => ({ ...prev, image2Description: e.target.value }))
}
placeholder="图片2描述 (可选)"
/>
</div>
</div>
<div className="space-y-2">
@@ -118,9 +164,25 @@ export function LevelDialog({ open, onOpenChange, level, onSubmit }: LevelDialog
onChange={(e) =>
setFormData((prev) => ({ ...prev, answer: e.target.value }))
}
placeholder="请输入答案"
placeholder="请输入答案最多4个字"
maxLength={4}
required
/>
<p className="text-xs text-muted-foreground text-right">
{formData.answer.length}/4
</p>
</div>
<div className="space-y-2">
<Label htmlFor="punchline"> ()</Label>
<Input
id="punchline"
value={formData.punchline}
onChange={(e) =>
setFormData((prev) => ({ ...prev, punchline: e.target.value }))
}
placeholder="请输入谐音梗说明"
/>
</div>
<div className="space-y-2">

View File

@@ -1,134 +0,0 @@
'use client'
import { useState, useCallback } from 'react'
import { Level } from '@/types'
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from '@dnd-kit/core'
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { LevelCard } from './level-card'
interface SortableLevelCardProps {
level: Level
onEdit: (level: Level) => void
onDelete: (id: string) => void
}
function SortableLevelCard({ level, onEdit, onDelete }: SortableLevelCardProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: level.id })
const style = {
transform: CSS.Transform.toString(transform),
transition,
}
return (
<div ref={setNodeRef} style={style} {...attributes} {...listeners}>
<LevelCard
level={level}
onEdit={onEdit}
onDelete={onDelete}
isDragging={isDragging}
/>
</div>
)
}
interface LevelListProps {
levels: Level[]
onReorder: (orders: { id: string; sortOrder: number }[]) => void
onEdit: (level: Level) => void
onDelete: (id: string) => void
}
export function LevelList({ levels, onReorder, onEdit, onDelete }: LevelListProps) {
const [items, setItems] = useState<Level[]>(levels)
// Update items when levels prop changes
if (JSON.stringify(items.map(i => i.id)) !== JSON.stringify(levels.map(l => l.id))) {
setItems(levels)
}
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
}),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
)
const handleDragEnd = useCallback(
(event: DragEndEvent) => {
const { active, over } = event
if (over && active.id !== over.id) {
const oldIndex = items.findIndex((item) => item.id === active.id)
const newIndex = items.findIndex((item) => item.id === over.id)
const newItems = arrayMove(items, oldIndex, newIndex)
setItems(newItems)
// Notify parent of new order
const orders = newItems.map((item, index) => ({
id: item.id,
sortOrder: index,
}))
onReorder(orders)
}
},
[items, onReorder]
)
if (items.length === 0) {
return (
<div className="text-center py-12 text-gray-500">
<p></p>
<p className="text-sm mt-2">&ldquo;&rdquo;</p>
</div>
)
}
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={items} strategy={verticalListSortingStrategy}>
<div className="space-y-3">
{items.map((level) => (
<SortableLevelCard
key={level.id}
level={level}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</div>
</SortableContext>
</DndContext>
)
}

View File

@@ -0,0 +1,171 @@
'use client'
import { useMemo } from 'react'
import {
useReactTable,
getCoreRowModel,
getPaginationRowModel,
flexRender,
} from '@tanstack/react-table'
import { Level } from '@/types'
import { createColumns } from './level-columns'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react'
interface LevelTableProps {
levels: Level[]
onEdit: (level: Level) => void
onDelete: (id: string) => void
deleteConfirmId: string | null
}
export function LevelTable({
levels,
onEdit,
onDelete,
deleteConfirmId,
}: LevelTableProps) {
const columns = useMemo(
() => createColumns({ onEdit, onDelete, deleteConfirmId }),
[onEdit, onDelete, deleteConfirmId]
)
const table = useReactTable({
data: levels,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
initialState: {
pagination: {
pageSize: 10,
},
},
})
if (levels.length === 0) {
return (
<div className="text-center py-12 text-gray-500">
<p></p>
<p className="text-sm mt-2">
&ldquo;&rdquo;
</p>
</div>
)
}
return (
<div className="space-y-4">
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
{/* 分页控制栏 */}
<div className="flex items-center justify-between px-2">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span></span>
<select
className="h-8 rounded-md border border-input bg-background px-2 text-sm"
value={table.getState().pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value))
}}
>
{[10, 20, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
{pageSize}
</option>
))}
</select>
<span></span>
</div>
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
{table.getState().pagination.pageIndex + 1} /{' '}
{table.getPageCount()} {levels.length}
</span>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
)
}

117
components/ui/table.tsx Normal file
View File

@@ -0,0 +1,117 @@
import * as React from 'react'
import { cn } from '@/lib/utils'
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
))
Table.displayName = 'Table'
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
))
TableHeader.displayName = 'TableHeader'
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
))
TableBody.displayName = 'TableBody'
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
'border-t bg-muted/50 font-medium [&>tr]:last:border-b-0',
className
)}
{...props}
/>
))
TableFooter.displayName = 'TableFooter'
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
className
)}
{...props}
/>
))
TableRow.displayName = 'TableRow'
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
className
)}
{...props}
/>
))
TableHead.displayName = 'TableHead'
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
{...props}
/>
))
TableCell.displayName = 'TableCell'
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
))
TableCaption.displayName = 'TableCaption'
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -1,194 +1,298 @@
'use client'
import { useState, useEffect } from 'react'
import { useEffect, useMemo, useState } from 'react'
import Image from 'next/image'
import { WxUserWithProgress } from '@/types'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { WxUserDetailResponse } from '@/types'
interface WxUserDetailDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
user: WxUserWithProgress | null | undefined
onDeleted?: () => void
user: WxUserDetailResponse | null | undefined
isSaving?: boolean
onSave: (levelIds: string[]) => Promise<void>
onClearAll: () => Promise<void>
}
export function WxUserDetailDialog({
open,
onOpenChange,
user,
onDeleted,
isSaving = false,
onSave,
onClearAll,
}: WxUserDetailDialogProps) {
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [isDeleting, setIsDeleting] = useState(false)
const [selectedLevelIds, setSelectedLevelIds] = useState<Set<string>>(new Set())
const [keyword, setKeyword] = useState('')
useEffect(() => {
if (!open) {
setSelectedIds(new Set())
if (!open || !user) {
setSelectedLevelIds(new Set())
setKeyword('')
return
}
}, [open])
setSelectedLevelIds(
new Set(
user.assignedLevels
.filter((level) => level.completed)
.map((level) => level.id)
)
)
}, [open, user])
const filteredLevels = useMemo(() => {
if (!user) return []
const search = keyword.trim().toLowerCase()
if (!search) return user.assignedLevels
return user.assignedLevels.filter((level) => {
return (
String(level.sortOrder).includes(search) ||
level.answer.toLowerCase().includes(search) ||
level.id.toLowerCase().includes(search)
)
})
}, [keyword, user])
const selectedCount = selectedLevelIds.size
const totalLevels = user?.assignedLevels.length || 0
const completedCount = user?.assignedLevels.filter((level) => level.completed).length || 0
const hasChanges = useMemo(() => {
if (!user) return false
const original = new Set(
user.assignedLevels.filter((level) => level.completed).map((level) => level.id)
)
if (original.size !== selectedLevelIds.size) return true
for (const id of Array.from(selectedLevelIds)) {
if (!original.has(id)) return true
}
return false
}, [selectedLevelIds, user])
if (!user) return null
const handleSelectAll = (checked: boolean) => {
const toggleLevel = (levelId: string, checked: boolean) => {
const next = new Set(selectedLevelIds)
if (checked) {
setSelectedIds(new Set(user.levelProgress.map((p) => p.id)))
next.add(levelId)
} else {
setSelectedIds(new Set())
next.delete(levelId)
}
setSelectedLevelIds(next)
}
const handleSelectOne = (id: string, checked: boolean) => {
const newSelected = new Set(selectedIds)
if (checked) {
newSelected.add(id)
} else {
newSelected.delete(id)
const handleSelectAllVisible = () => {
const next = new Set(selectedLevelIds)
for (const level of filteredLevels) {
next.add(level.id)
}
setSelectedIds(newSelected)
setSelectedLevelIds(next)
}
const handleBatchDelete = async () => {
if (selectedIds.size === 0) return
const handleClearVisible = () => {
const next = new Set(selectedLevelIds)
setIsDeleting(true)
try {
const res = await fetch('/api/wx-users/level-progress', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: Array.from(selectedIds) }),
})
if (res.ok) {
setSelectedIds(new Set())
onDeleted?.()
}
} finally {
setIsDeleting(false)
for (const level of filteredLevels) {
next.delete(level.id)
}
setSelectedLevelIds(next)
}
const allSelected =
user.levelProgress.length > 0 &&
selectedIds.size === user.levelProgress.length
const handleSave = async () => {
await onSave(Array.from(selectedLevelIds))
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<DialogContent className="max-w-5xl h-[85vh] overflow-hidden p-0">
<div className="grid h-full md:grid-cols-[320px_1fr]">
<div className="border-b bg-slate-50 p-6 md:border-b-0 md:border-r">
<DialogHeader className="text-left">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex items-center gap-4">
<div className="w-16 h-16 flex-shrink-0 relative">
{user.avatarUrl ? (
<Image
src={user.avatarUrl}
alt={user.nickname || 'User'}
fill
className="rounded-full object-cover"
/>
) : (
<div className="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center text-xl font-medium text-gray-600">
{user.nickname?.[0]?.toUpperCase() || 'U'}
<div className="mt-6 space-y-5">
<div className="flex items-center gap-4">
<div className="relative h-16 w-16 overflow-hidden rounded-full bg-slate-200">
{user.avatarUrl ? (
<Image
src={user.avatarUrl}
alt={user.nickname || 'User'}
fill
sizes="64px"
className="object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xl font-semibold text-slate-600">
{user.nickname?.[0]?.toUpperCase() || 'U'}
</div>
)}
</div>
)}
</div>
<div>
<h2 className="text-xl font-semibold text-gray-900">
{user.nickname || '匿名用户'}
</h2>
<p className="text-sm text-gray-500 mt-1">
{new Date(user.createdAt).toLocaleDateString('zh-CN')}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="bg-gray-50 rounded-lg p-4">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1"></p>
<p className="text-2xl font-bold text-orange-600">{user.points}</p>
</div>
<div className="bg-gray-50 rounded-lg p-4">
<p className="text-xs text-gray-500 uppercase tracking-wider mb-1"></p>
<p className="text-2xl font-bold text-green-600">{user.levelProgress.length}</p>
</div>
</div>
<div>
<p className="text-xs text-gray-500 uppercase tracking-wider mb-2">OpenID</p>
<code className="block bg-gray-100 text-gray-800 text-xs p-3 rounded-lg break-all">
{user.openid}
</code>
</div>
{user.levelProgress.length > 0 && (
<div>
<div className="flex items-center justify-between mb-2">
<p className="text-xs text-gray-500 uppercase tracking-wider"></p>
{selectedIds.size > 0 && (
<Button
variant="destructive"
size="sm"
onClick={handleBatchDelete}
disabled={isDeleting}
>
{isDeleting ? '删除中...' : `删除已选 (${selectedIds.size})`}
</Button>
)}
<div className="min-w-0">
<h2 className="truncate text-xl font-semibold text-slate-900">
{user.nickname || '匿名用户'}
</h2>
<p className="mt-1 text-sm text-slate-500">
{new Date(user.createdAt).toLocaleString('zh-CN')}
</p>
</div>
</div>
<div className="border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b">
<div className="grid grid-cols-2 gap-3">
<div className="rounded-xl border bg-white p-4">
<p className="text-xs uppercase tracking-wide text-slate-500"></p>
<p className="mt-2 text-2xl font-semibold text-emerald-600">{completedCount}</p>
</div>
<div className="rounded-xl border bg-white p-4">
<p className="text-xs uppercase tracking-wide text-slate-500"></p>
<p className="mt-2 text-2xl font-semibold text-sky-600">{selectedCount}</p>
</div>
</div>
<div className="space-y-3 rounded-xl border bg-white p-4">
<div>
<p className="text-xs uppercase tracking-wide text-slate-500">OpenID</p>
<code className="mt-2 block break-all rounded-md bg-slate-100 p-3 text-xs text-slate-700">
{user.openid}
</code>
</div>
<div className="grid grid-cols-2 gap-3 text-sm text-slate-600">
<div>
<p className="text-xs uppercase tracking-wide text-slate-500"></p>
<p className="mt-1 font-medium text-slate-900">{user.stamina}</p>
</div>
<div>
<p className="text-xs uppercase tracking-wide text-slate-500"></p>
<p className="mt-1 font-medium text-slate-900">{totalLevels}</p>
</div>
</div>
</div>
<div className="space-y-2">
<Button
className="w-full"
onClick={handleSave}
disabled={isSaving || !hasChanges}
>
{isSaving ? '保存中...' : '保存通关配置'}
</Button>
<Button
variant="outline"
className="w-full"
onClick={onClearAll}
disabled={isSaving || completedCount === 0}
>
</Button>
</div>
</div>
</div>
<div className="flex min-h-0 flex-col p-6">
<div className="flex flex-col gap-3 border-b pb-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 className="text-base font-semibold text-slate-900"></h3>
<p className="text-sm text-slate-500"></p>
</div>
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
placeholder="搜索关卡序号、答案或 ID"
className="sm:max-w-xs"
/>
</div>
<div className="flex items-center gap-2 py-4">
<Button variant="outline" size="sm" onClick={handleSelectAllVisible} disabled={filteredLevels.length === 0 || isSaving}>
</Button>
<Button variant="outline" size="sm" onClick={handleClearVisible} disabled={filteredLevels.length === 0 || isSaving}>
</Button>
</div>
<div className="min-h-0 flex-1 overflow-auto rounded-xl border">
{filteredLevels.length === 0 ? (
<div className="flex h-full items-center justify-center p-8 text-sm text-slate-500">
</div>
) : (
<table className="min-w-full divide-y divide-slate-200 text-sm">
<thead className="sticky top-0 bg-slate-50">
<tr>
<th className="w-10 px-3 py-2 text-left">
<input
type="checkbox"
checked={allSelected}
onChange={(e) => handleSelectAll(e.target.checked)}
className="rounded border-gray-300"
/>
</th>
<th className="px-3 py-2 text-left text-xs text-gray-500 uppercase">ID</th>
<th className="px-3 py-2 text-left text-xs text-gray-500 uppercase"></th>
<th className="px-3 py-2 text-left text-xs text-gray-500 uppercase"></th>
<th className="w-14 px-4 py-3 text-left font-medium text-slate-500"></th>
<th className="w-24 px-4 py-3 text-left font-medium text-slate-500"></th>
<th className="px-4 py-3 text-left font-medium text-slate-500"></th>
<th className="px-4 py-3 text-left font-medium text-slate-500"></th>
<th className="px-4 py-3 text-left font-medium text-slate-500"></th>
</tr>
</thead>
<tbody className="divide-y">
{user.levelProgress.map((progress) => (
<tr key={progress.id} className="hover:bg-gray-50">
<td className="px-3 py-2">
<input
type="checkbox"
checked={selectedIds.has(progress.id)}
onChange={(e) => handleSelectOne(progress.id, e.target.checked)}
className="rounded border-gray-300"
/>
</td>
<td className="px-3 py-2 font-mono text-xs text-gray-400">
{progress.levelId}
</td>
<td className="px-3 py-2 font-medium text-gray-900">
{progress.level?.answer || '-'}
</td>
<td className="px-3 py-2 text-gray-500">
{new Date(progress.completedAt).toLocaleDateString('zh-CN')}
</td>
</tr>
))}
<tbody className="divide-y divide-slate-100 bg-white">
{filteredLevels.map((level) => {
const checked = selectedLevelIds.has(level.id)
return (
<tr key={level.id} className={checked ? 'bg-emerald-50/60' : ''}>
<td className="px-4 py-3 align-top">
<input
type="checkbox"
checked={checked}
onChange={(e) => toggleLevel(level.id, e.target.checked)}
disabled={isSaving}
className="h-4 w-4 rounded border-slate-300"
/>
</td>
<td className="px-4 py-3 align-top font-mono text-slate-500">
#{level.sortOrder}
</td>
<td className="px-4 py-3 align-top">
<div className="font-medium text-slate-900">{level.answer}</div>
<div className="mt-1 font-mono text-xs text-slate-400">{level.id}</div>
</td>
<td className="px-4 py-3 align-top">
<span
className={checked
? 'inline-flex rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-medium text-emerald-700'
: 'inline-flex rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-500'}
>
{checked ? '已通关' : '未通关'}
</span>
</td>
<td className="px-4 py-3 align-top text-slate-500">
{level.completedAt
? new Date(level.completedAt).toLocaleString('zh-CN')
: '-'}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>

View File

@@ -24,6 +24,7 @@
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-query": "^5.69.0",
"@tanstack/react-table": "^8.21.3",
"bcryptjs": "^3.0.2",
"better-auth": "^1.2.7",
"class-variance-authority": "^0.7.1",

5919
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -12,15 +12,19 @@ datasource db {
}
model Level {
id String @id @default(uuid())
imageUrl String @map("image_url")
answer String
hint1 String?
hint2 String?
hint3 String?
sortOrder Int @default(0) @map("sort_order")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(uuid())
image1Url String @map("image1_url") @db.VarChar(500)
image1Description String? @map("image1_description") @db.VarChar(500)
image2Url String @map("image2_url") @db.VarChar(500)
image2Description String? @map("image2_description") @db.VarChar(500)
answer String
punchline String? @db.VarChar(500)
hint1 String?
hint2 String?
hint3 String?
sortOrder Int @default(0) @map("sort_order")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
userProgress WxUserLevelProgress[]
@@ -89,14 +93,15 @@ model Verification {
}
model WxUser {
id String @id @default(uuid())
openid String @unique
sessionKey String? @map("session_key")
nickname String?
avatarUrl String? @map("avatar_url")
points Int @default(10)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(uuid())
openid String @unique
sessionKey String? @map("session_key")
nickname String?
avatarUrl String? @map("avatar_url")
stamina Int @default(50)
staminaUpdatedAt DateTime? @map("stamina_updated_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
levelProgress WxUserLevelProgress[]
@@ -108,6 +113,7 @@ model WxUserLevelProgress {
userId String @map("user_id")
levelId String @map("level_id")
completedAt DateTime @default(now()) @map("completed_at")
timeSpent Int @default(0) @map("time_spent")
user WxUser @relation(fields: [userId], references: [id], onDelete: Cascade)
level Level @relation(fields: [levelId], references: [id])

View File

@@ -1,7 +1,11 @@
export interface Level {
id: string
imageUrl: string
image1Url: string
image1Description: string | null
image2Url: string
image2Description: string | null
answer: string
punchline: string | null
hint1: string | null
hint2: string | null
hint3: string | null
@@ -11,8 +15,12 @@ export interface Level {
}
export interface LevelFormData {
imageUrl: string
image1Url: string
image1Description?: string
image2Url: string
image2Description?: string
answer: string
punchline?: string
hint1?: string
hint2?: string
hint3?: string
@@ -44,9 +52,11 @@ export interface WxUser {
sessionKey: string | null
nickname: string | null
avatarUrl: string | null
points: number
stamina: number
staminaUpdatedAt: Date | null
createdAt: Date
updatedAt: Date
completedLevelCount: number
}
export interface WxUserLevelProgress {
@@ -54,12 +64,27 @@ export interface WxUserLevelProgress {
userId: string
levelId: string
completedAt: Date
timeSpent: number
level?: {
id: string
answer: string
sortOrder: number
}
}
export interface WxUserWithProgress extends WxUser {
levelProgress: WxUserLevelProgress[]
}
export interface WxUserAssignableLevel {
id: string
answer: string
sortOrder: number
completed: boolean
progressId: string | null
completedAt: Date | null
}
export interface WxUserDetailResponse extends WxUser {
assignedLevels: WxUserAssignableLevel[]
}