74 lines
2.4 KiB
TypeScript
74 lines
2.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import pool from '@/lib/db'
|
|
|
|
// GET /api/drops/past - Get all sold-out drops
|
|
export async function GET() {
|
|
try {
|
|
// Get all drops
|
|
const [rows] = await pool.execute(
|
|
'SELECT * FROM drops ORDER BY created_at DESC'
|
|
)
|
|
const drops = rows as any[]
|
|
|
|
// Calculate fill from sales for each drop and filter sold-out ones
|
|
const soldOutDrops = []
|
|
|
|
for (const drop of drops) {
|
|
// Calculate fill from sales records
|
|
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 sold out (fill >= size)
|
|
if (fill >= drop.size) {
|
|
// Get the timestamp of the last sale to calculate "sold out in X hours"
|
|
const [lastSaleRows] = await pool.execute(
|
|
'SELECT created_at FROM sales WHERE drop_id = ? ORDER BY created_at DESC LIMIT 1',
|
|
[drop.id]
|
|
)
|
|
const lastSaleData = lastSaleRows as any[]
|
|
const lastSaleDate = lastSaleData[0]?.created_at || drop.created_at
|
|
|
|
// Calculate hours between drop creation and last sale
|
|
const dropDate = new Date(drop.created_at)
|
|
const soldOutDate = new Date(lastSaleDate)
|
|
const hoursDiff = Math.round(
|
|
(soldOutDate.getTime() - dropDate.getTime()) / (1000 * 60 * 60)
|
|
)
|
|
|
|
// Fetch images for this drop
|
|
const [imageRows] = await pool.execute(
|
|
'SELECT image_url FROM drop_images WHERE drop_id = ? ORDER BY display_order ASC LIMIT 4',
|
|
[drop.id]
|
|
)
|
|
const images = (imageRows as any[]).map((row: any) => row.image_url)
|
|
|
|
soldOutDrops.push({
|
|
...drop,
|
|
fill: fill,
|
|
soldOutInHours: hoursDiff,
|
|
images: images.length > 0 ? images : (drop.image_url ? [drop.image_url] : []), // Support legacy single image_url
|
|
})
|
|
}
|
|
}
|
|
|
|
return NextResponse.json(soldOutDrops)
|
|
} catch (error) {
|
|
console.error('Error fetching past drops:', error)
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch past drops' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|