133 lines
4.2 KiB
TypeScript
133 lines
4.2 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getDb } from '@/lib/db';
|
|
import { polls, pollOptions, votes, referrals, userStats } from '@/lib/db/schema';
|
|
import { eq, sql } from 'drizzle-orm';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
const body = await request.json();
|
|
const { pollId, optionId, userFid, userAddress, amount, txHash } = body as {
|
|
pollId: string
|
|
optionId: string
|
|
userFid: string
|
|
userAddress: string
|
|
amount: string
|
|
txHash: string
|
|
};
|
|
|
|
if (!pollId || !optionId || !userFid || !userAddress || !amount || !txHash) {
|
|
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
|
}
|
|
|
|
// Check if poll exists and is active
|
|
const poll = await db.query.polls.findFirst({
|
|
where: eq(polls.id, pollId),
|
|
});
|
|
|
|
if (!poll || poll.status !== 'active') {
|
|
return NextResponse.json({ error: 'Poll not found or not active' }, { status: 404 });
|
|
}
|
|
|
|
// Check if user already voted
|
|
const existingVote = await db.query.votes.findFirst({
|
|
where: (votes, { and, eq }) => and(eq(votes.pollId, pollId), eq(votes.userFid, userFid)),
|
|
});
|
|
|
|
if (existingVote) {
|
|
return NextResponse.json({ error: 'User already voted' }, { status: 400 });
|
|
}
|
|
|
|
// Insert vote
|
|
await db.insert(votes).values({
|
|
id: uuidv4(),
|
|
pollId,
|
|
userFid,
|
|
userAddress,
|
|
optionId,
|
|
amount,
|
|
txHash,
|
|
timestamp: Date.now(),
|
|
});
|
|
|
|
// Update option vote count
|
|
await db
|
|
.update(pollOptions)
|
|
.set({
|
|
votes: sql`${pollOptions.votes} + 1`,
|
|
totalAmount: sql`${pollOptions.totalAmount} + ${amount}`,
|
|
})
|
|
.where(eq(pollOptions.id, optionId));
|
|
|
|
// Update poll total pot
|
|
await db
|
|
.update(polls)
|
|
.set({
|
|
totalPot: sql`${polls.totalPot} + ${amount}`,
|
|
})
|
|
.where(eq(polls.id, pollId));
|
|
|
|
// Update user stats
|
|
await db.insert(userStats).values({
|
|
userFid,
|
|
totalVotes: 1,
|
|
totalSpent: amount,
|
|
lastVoteDate: new Date(),
|
|
}).onConflictDoUpdate({
|
|
target: userStats.userFid,
|
|
set: {
|
|
totalVotes: sql`${userStats.totalVotes} + 1`,
|
|
totalSpent: sql`${userStats.totalSpent} + ${amount}`,
|
|
lastVoteDate: new Date(),
|
|
updatedAt: new Date(),
|
|
},
|
|
});
|
|
|
|
// Complete referral if exists
|
|
const referral = await db.query.referrals.findFirst({
|
|
where: eq(referrals.referredFid, userFid),
|
|
});
|
|
|
|
if (referral && referral.status === 'pending') {
|
|
await db.update(referrals)
|
|
.set({
|
|
status: 'completed',
|
|
completedAt: new Date(),
|
|
})
|
|
.where(eq(referrals.id, referral.id));
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (e) {
|
|
console.error('Error voting:', e);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const { searchParams } = new URL(request.url);
|
|
const pollId = searchParams.get('pollId');
|
|
const userFid = searchParams.get('userFid');
|
|
|
|
if (!pollId || !userFid) {
|
|
return NextResponse.json({ error: 'Missing pollId or userFid' }, { status: 400 });
|
|
}
|
|
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
const vote = await db.query.votes.findFirst({
|
|
where: (votes, { and, eq }) => and(eq(votes.pollId, pollId), eq(votes.userFid, userFid)),
|
|
});
|
|
|
|
if (!vote) {
|
|
return NextResponse.json(null);
|
|
}
|
|
|
|
return NextResponse.json(vote);
|
|
} catch (e) {
|
|
console.error('Error fetching vote:', e);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|