import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; // GET /api/rankings - 获取排行榜数据 export async function GET() { try { // 上传榜 - 按素材数量排序(只统计未删除的素材) const contributorCounts = await prisma.material.groupBy({ by: ['userId'], where: { deletedAt: null, accessScope: 'general' }, _count: { id: true }, orderBy: { _count: { id: 'desc' } }, take: 10, }); const contributorUsers = await prisma.user.findMany({ where: { id: { in: contributorCounts.map((row) => row.userId) } }, select: { id: true, username: true }, }); const contributorNames = new Map(contributorUsers.map((user) => [user.id, user.username])); const contributors = contributorCounts.map((row) => ({ username: contributorNames.get(row.userId) || '未知用户', count: row._count.id, })); // 下载榜 - 按下载次数排序(只统计未删除的素材) let downloadRankings; try { downloadRankings = await prisma.material.groupBy({ by: ['userId'], where: { deletedAt: null, accessScope: 'general', } as any, _sum: { downloadCount: true, }, orderBy: { _sum: { downloadCount: 'desc', }, }, take: 10, }); } catch (e: any) { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { downloadRankings = await prisma.material.groupBy({ by: ['userId'], where: { accessScope: 'general' }, _sum: { downloadCount: true, }, orderBy: { _sum: { downloadCount: 'desc', }, }, take: 10, }); } else { throw e; } } const downloads = await Promise.all( downloadRankings.map(async (item) => { const user = await prisma.user.findUnique({ where: { id: item.userId }, select: { username: true }, }); return { username: user?.username || '未知用户', count: item._sum.downloadCount || 0, }; }) ); // 点赞榜 - 按点赞次数排序(只统计未删除的素材) let likeRankings; try { likeRankings = await prisma.material.groupBy({ by: ['userId'], where: { deletedAt: null, accessScope: 'general', } as any, _sum: { likeCount: true, }, orderBy: { _sum: { likeCount: 'desc', }, }, take: 10, }); } catch (e: any) { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { likeRankings = await prisma.material.groupBy({ by: ['userId'], where: { accessScope: 'general' }, _sum: { likeCount: true, }, orderBy: { _sum: { likeCount: 'desc', }, }, take: 10, }); } else { throw e; } } const likes = await Promise.all( likeRankings.map(async (item) => { const user = await prisma.user.findUnique({ where: { id: item.userId }, select: { username: true }, }); return { username: user?.username || '未知用户', count: item._sum.likeCount || 0, }; }) ); return NextResponse.json({ contributors, downloads, likes, }); } catch (error) { console.error('Error fetching rankings:', error); return NextResponse.json({ error: '获取排行榜失败' }, { status: 500 }); } }