feat: 支持配置微信用户已通关关卡
This commit is contained in:
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user