49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getDb } from '@/lib/db'
|
|
import { polls, creatorEarnings } from '@/lib/db/schema'
|
|
import { eq, and, sql } from 'drizzle-orm'
|
|
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const authHeader = req.headers.get('authorization')
|
|
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
// Find completed polls without earnings calculated
|
|
const completedPolls = await db.query.polls.findMany({
|
|
where: and(
|
|
eq(polls.status, 'completed'),
|
|
sql`NOT EXISTS (
|
|
SELECT 1 FROM creator_earnings
|
|
WHERE creator_earnings.poll_id = polls.id
|
|
)`
|
|
),
|
|
})
|
|
|
|
// Calculate 1% creator fee for each poll
|
|
for (const poll of completedPolls) {
|
|
const creatorFee = parseFloat(poll.totalPot) * 0.01
|
|
|
|
if (creatorFee > 0) {
|
|
await db.insert(creatorEarnings).values({
|
|
creatorFid: poll.creatorFid.toString(),
|
|
pollId: poll.id,
|
|
amount: creatorFee.toString(),
|
|
status: 'pending',
|
|
})
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
processed: completedPolls.length
|
|
})
|
|
} catch (error) {
|
|
console.error('Calculate earnings error:', error)
|
|
return NextResponse.json({ error: 'Failed to calculate earnings' }, { status: 500 })
|
|
}
|
|
}
|