first commit
This commit is contained in:
65
app/api/matches/[id]/stats/route.ts
Normal file
65
app/api/matches/[id]/stats/route.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { calculatePoints } from "@/lib/points";
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session || (session.user as any).role !== "ADMIN")
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const stats: Array<{
|
||||
playerId: string;
|
||||
goals: number;
|
||||
assists: number;
|
||||
yellowCards: number;
|
||||
redCards: number;
|
||||
minutesPlayed: number;
|
||||
cleanSheet: boolean;
|
||||
}> = await req.json();
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const stat of stats) {
|
||||
const player = await db.player.findUnique({ where: { id: stat.playerId } });
|
||||
if (!player) continue;
|
||||
|
||||
const points = calculatePoints({ position: player.position, ...stat });
|
||||
|
||||
const record = await db.playerMatchStat.upsert({
|
||||
where: { playerId_matchId: { playerId: stat.playerId, matchId: params.id } },
|
||||
update: { ...stat, points },
|
||||
create: { ...stat, matchId: params.id, points },
|
||||
});
|
||||
|
||||
// آپدیت امتیاز کل بازیکن
|
||||
const totalPoints = await db.playerMatchStat.aggregate({
|
||||
where: { playerId: stat.playerId },
|
||||
_sum: { points: true },
|
||||
});
|
||||
await db.player.update({
|
||||
where: { id: stat.playerId },
|
||||
data: { totalPoints: totalPoints._sum.points ?? 0 },
|
||||
});
|
||||
|
||||
results.push(record);
|
||||
}
|
||||
|
||||
// آپدیت امتیاز تیمهای فانتزی
|
||||
await recalcTeamPoints();
|
||||
|
||||
return NextResponse.json(results);
|
||||
}
|
||||
|
||||
async function recalcTeamPoints() {
|
||||
const teams = await db.team.findMany({ include: { players: { include: { player: true } } } });
|
||||
for (const team of teams) {
|
||||
let total = 0;
|
||||
for (const tp of team.players) {
|
||||
const multiplier = tp.isCaptain ? 2 : 1;
|
||||
total += tp.player.totalPoints * multiplier;
|
||||
}
|
||||
await db.team.update({ where: { id: team.id }, data: { totalPoints: total } });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user