93 lines
2.6 KiB
TypeScript
93 lines
2.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import pool from '@/lib/db'
|
|
|
|
// GET /api/drops - Get all drops
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
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
|
|
const dropsWithFill = await Promise.all(
|
|
drops.map(async (drop) => {
|
|
// 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
|
|
}
|
|
|
|
return {
|
|
...drop,
|
|
fill: fill,
|
|
}
|
|
})
|
|
)
|
|
|
|
return NextResponse.json(dropsWithFill)
|
|
} catch (error) {
|
|
console.error('Error fetching drops:', error)
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch drops' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// POST /api/drops - Create a new drop
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json()
|
|
const { item, size, unit = 'g', ppu, imageUrl } = body
|
|
|
|
// Validate required fields
|
|
if (!item || !size || !ppu) {
|
|
return NextResponse.json(
|
|
{ error: 'Missing required fields: item, size, ppu' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Insert new drop
|
|
// Note: If imageUrl column doesn't exist in database, add it with:
|
|
// ALTER TABLE drops ADD COLUMN image_url VARCHAR(255) DEFAULT NULL AFTER unit;
|
|
// Note: fill is no longer stored, it's calculated from sales
|
|
const [result] = await pool.execute(
|
|
'INSERT INTO drops (item, size, unit, ppu, image_url) VALUES (?, ?, ?, ?, ?)',
|
|
[item, size, unit, ppu, imageUrl || null]
|
|
)
|
|
|
|
const insertId = (result as any).insertId
|
|
|
|
// Fetch the created drop
|
|
const [rows] = await pool.execute('SELECT * FROM drops WHERE id = ?', [
|
|
insertId,
|
|
])
|
|
|
|
const drop = rows[0] as any
|
|
|
|
// Return drop with calculated fill (will be 0 for new drop)
|
|
return NextResponse.json({
|
|
...drop,
|
|
fill: 0,
|
|
}, { status: 201 })
|
|
} catch (error) {
|
|
console.error('Error creating drop:', error)
|
|
return NextResponse.json(
|
|
{ error: 'Failed to create drop' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|