Files
cbd420/app/api/drops/active/route.ts
2025-12-20 19:00:42 +01:00

52 lines
1.5 KiB
TypeScript

import { NextResponse } from 'next/server'
import pool from '@/lib/db'
// GET /api/drops/active - Get the earliest unfilled drop (not sold out)
export async function GET() {
try {
// Get all drops ordered by creation date
const [rows] = await pool.execute(
'SELECT * FROM drops ORDER BY created_at ASC'
)
const drops = rows as any[]
// Find the first drop that's not fully sold out
for (const drop of drops) {
// Calculate fill from sales records
// Sales are stored in grams, so we need to convert based on drop unit
const [salesRows] = await pool.execute(
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
[drop.id]
)
const salesData = salesRows as any[]
const totalFillInGrams = salesData[0]?.total_fill || 0
// Convert fill to drop's unit for comparison
let fill = totalFillInGrams
if (drop.unit === 'kg') {
fill = totalFillInGrams / 1000
}
// Check if drop is not fully sold out
if (fill < drop.size) {
// Return drop with calculated fill
return NextResponse.json({
...drop,
fill: fill,
})
}
}
// No active drops found
return NextResponse.json(null)
} catch (error) {
console.error('Error fetching active drop:', error)
return NextResponse.json(
{ error: 'Failed to fetch active drop' },
{ status: 500 }
)
}
}