sync
This commit is contained in:
194
app/api/buyers/[id]/route.ts
Normal file
194
app/api/buyers/[id]/route.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import bcrypt from 'bcrypt'
|
||||
|
||||
// GET /api/buyers/[id] - Get a specific buyer
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid buyer ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const [rows] = await pool.execute(
|
||||
'SELECT id, username, email, created_at FROM buyers WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
|
||||
const buyers = rows as any[]
|
||||
if (buyers.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Buyer not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json(buyers[0])
|
||||
} catch (error) {
|
||||
console.error('Error fetching buyer:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch buyer' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/buyers/[id] - Update a buyer
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid buyer ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { username, email, password } = body
|
||||
|
||||
// Check if buyer exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM buyers WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Buyer not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Build update query dynamically based on provided fields
|
||||
const updates: string[] = []
|
||||
const values: any[] = []
|
||||
|
||||
if (username !== undefined) {
|
||||
// Check if username already exists (excluding current buyer)
|
||||
const [usernameCheck] = await pool.execute(
|
||||
'SELECT id FROM buyers WHERE username = ? AND id != ?',
|
||||
[username, id]
|
||||
)
|
||||
if ((usernameCheck as any[]).length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Username already exists' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('username = ?')
|
||||
values.push(username)
|
||||
}
|
||||
|
||||
if (email !== undefined) {
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailRegex.test(email)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid email format' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
// Check if email already exists (excluding current buyer)
|
||||
const [emailCheck] = await pool.execute(
|
||||
'SELECT id FROM buyers WHERE email = ? AND id != ?',
|
||||
[email, id]
|
||||
)
|
||||
if ((emailCheck as any[]).length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Email already exists' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('email = ?')
|
||||
values.push(email)
|
||||
}
|
||||
|
||||
if (password !== undefined) {
|
||||
if (password.length < 6) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Password must be at least 6 characters' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const hashedPassword = await bcrypt.hash(password, 10)
|
||||
updates.push('password = ?')
|
||||
values.push(hashedPassword)
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No fields to update' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
values.push(id)
|
||||
const query = `UPDATE buyers SET ${updates.join(', ')} WHERE id = ?`
|
||||
await pool.execute(query, values)
|
||||
|
||||
// Fetch updated buyer
|
||||
const [rows] = await pool.execute(
|
||||
'SELECT id, username, email, created_at FROM buyers WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
|
||||
return NextResponse.json((rows as any[])[0])
|
||||
} catch (error) {
|
||||
console.error('Error updating buyer:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update buyer' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/buyers/[id] - Delete a buyer
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid buyer ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check if buyer exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM buyers WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Buyer not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Delete buyer (cascade will handle related sales)
|
||||
await pool.execute('DELETE FROM buyers WHERE id = ?', [id])
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error deleting buyer:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to delete buyer' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
19
app/api/buyers/route.ts
Normal file
19
app/api/buyers/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/buyers - Get all buyers
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const [rows] = await pool.execute(
|
||||
'SELECT id, username, email, created_at FROM buyers ORDER BY created_at DESC'
|
||||
)
|
||||
return NextResponse.json(rows)
|
||||
} catch (error) {
|
||||
console.error('Error fetching buyers:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch buyers' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/drops/active - Get the earliest unfilled drop (not sold out)
|
||||
// GET /api/drops/active - Get the earliest unfilled drop (not sold out) that has started
|
||||
export async function GET() {
|
||||
try {
|
||||
// Get all drops ordered by creation date
|
||||
const now = new Date()
|
||||
|
||||
// Get all drops ordered by start_time (or created_at if start_time is null)
|
||||
const [rows] = await pool.execute(
|
||||
'SELECT * FROM drops ORDER BY created_at ASC'
|
||||
'SELECT * FROM drops ORDER BY COALESCE(start_time, created_at) ASC'
|
||||
)
|
||||
|
||||
const drops = rows as any[]
|
||||
|
||||
// Find the first drop that's not fully sold out
|
||||
// Find the first drop that's not fully sold out and has started
|
||||
for (const drop of drops) {
|
||||
// Check if drop has started (start_time is in the past or null)
|
||||
const startTime = drop.start_time ? new Date(drop.start_time) : new Date(drop.created_at)
|
||||
if (startTime > now) {
|
||||
// Drop hasn't started yet - return it with a flag indicating it's upcoming
|
||||
// Calculate fill (will be 0 for upcoming drops)
|
||||
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
|
||||
|
||||
let fill = totalFillInGrams
|
||||
if (drop.unit === 'kg') {
|
||||
fill = totalFillInGrams / 1000
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
...drop,
|
||||
fill: fill,
|
||||
is_upcoming: true,
|
||||
start_time: drop.start_time || drop.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
// Calculate fill from sales records
|
||||
// Sales are stored in grams, so we need to convert based on drop unit
|
||||
const [salesRows] = await pool.execute(
|
||||
@@ -34,6 +61,8 @@ export async function GET() {
|
||||
return NextResponse.json({
|
||||
...drop,
|
||||
fill: fill,
|
||||
is_upcoming: false,
|
||||
start_time: drop.start_time || drop.created_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export async function GET(request: NextRequest) {
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { item, size, unit = 'g', ppu, imageUrl } = body
|
||||
const { item, size, unit = 'g', ppu, imageUrl, startTime } = body
|
||||
|
||||
// Validate required fields
|
||||
if (!item || !size || !ppu) {
|
||||
@@ -63,8 +63,8 @@ export async function POST(request: NextRequest) {
|
||||
// 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]
|
||||
'INSERT INTO drops (item, size, unit, ppu, image_url, start_time) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[item, size, unit, ppu, imageUrl || null, startTime || null]
|
||||
)
|
||||
|
||||
const insertId = (result as any).insertId
|
||||
|
||||
@@ -71,11 +71,13 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Calculate price
|
||||
// ppu is stored as integer where 1000 = $1.00, so divide by 1000 to get actual price
|
||||
const pricePerUnit = drop.ppu / 1000
|
||||
let priceAmount = 0
|
||||
if (drop.unit === 'kg') {
|
||||
priceAmount = (size / 1000) * drop.ppu
|
||||
priceAmount = (size / 1000) * pricePerUnit
|
||||
} else {
|
||||
priceAmount = size * drop.ppu
|
||||
priceAmount = size * pricePerUnit
|
||||
}
|
||||
|
||||
// Round to 2 decimal places
|
||||
|
||||
219
app/api/sales/[id]/route.ts
Normal file
219
app/api/sales/[id]/route.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/sales/[id] - Get a specific sale
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid sale ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT
|
||||
s.id,
|
||||
s.drop_id,
|
||||
s.buyer_id,
|
||||
s.size,
|
||||
s.payment_id,
|
||||
s.created_at,
|
||||
d.item as drop_item,
|
||||
d.unit as drop_unit,
|
||||
d.ppu as drop_ppu,
|
||||
b.username as buyer_username,
|
||||
b.email as buyer_email
|
||||
FROM sales s
|
||||
LEFT JOIN drops d ON s.drop_id = d.id
|
||||
LEFT JOIN buyers b ON s.buyer_id = b.id
|
||||
WHERE s.id = ?`,
|
||||
[id]
|
||||
)
|
||||
|
||||
const sales = rows as any[]
|
||||
if (sales.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Sale not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json(sales[0])
|
||||
} catch (error) {
|
||||
console.error('Error fetching sale:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch sale' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/sales/[id] - Update a sale
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid sale ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { drop_id, buyer_id, size, payment_id } = body
|
||||
|
||||
// Check if sale exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM sales WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Sale not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Build update query dynamically
|
||||
const updates: string[] = []
|
||||
const values: any[] = []
|
||||
|
||||
if (drop_id !== undefined) {
|
||||
// Verify drop exists
|
||||
const [dropCheck] = await pool.execute(
|
||||
'SELECT id FROM drops WHERE id = ?',
|
||||
[drop_id]
|
||||
)
|
||||
if ((dropCheck as any[]).length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Drop not found' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('drop_id = ?')
|
||||
values.push(drop_id)
|
||||
}
|
||||
|
||||
if (buyer_id !== undefined) {
|
||||
// Verify buyer exists
|
||||
const [buyerCheck] = await pool.execute(
|
||||
'SELECT id FROM buyers WHERE id = ?',
|
||||
[buyer_id]
|
||||
)
|
||||
if ((buyerCheck as any[]).length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Buyer not found' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('buyer_id = ?')
|
||||
values.push(buyer_id)
|
||||
}
|
||||
|
||||
if (size !== undefined) {
|
||||
if (size <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Size must be greater than 0' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('size = ?')
|
||||
values.push(size)
|
||||
}
|
||||
|
||||
if (payment_id !== undefined) {
|
||||
updates.push('payment_id = ?')
|
||||
values.push(payment_id)
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No fields to update' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
values.push(id)
|
||||
const query = `UPDATE sales SET ${updates.join(', ')} WHERE id = ?`
|
||||
await pool.execute(query, values)
|
||||
|
||||
// Fetch updated sale
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT
|
||||
s.id,
|
||||
s.drop_id,
|
||||
s.buyer_id,
|
||||
s.size,
|
||||
s.payment_id,
|
||||
s.created_at,
|
||||
d.item as drop_item,
|
||||
d.unit as drop_unit,
|
||||
d.ppu as drop_ppu,
|
||||
b.username as buyer_username,
|
||||
b.email as buyer_email
|
||||
FROM sales s
|
||||
LEFT JOIN drops d ON s.drop_id = d.id
|
||||
LEFT JOIN buyers b ON s.buyer_id = b.id
|
||||
WHERE s.id = ?`,
|
||||
[id]
|
||||
)
|
||||
|
||||
return NextResponse.json((rows as any[])[0])
|
||||
} catch (error) {
|
||||
console.error('Error updating sale:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update sale' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/sales/[id] - Delete a sale
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const id = parseInt(params.id, 10)
|
||||
if (isNaN(id)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid sale ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check if sale exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM sales WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Sale not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Delete sale
|
||||
await pool.execute('DELETE FROM sales WHERE id = ?', [id])
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error deleting sale:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to delete sale' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
34
app/api/sales/list/route.ts
Normal file
34
app/api/sales/list/route.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/sales/list - Get all sales with related data
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT
|
||||
s.id,
|
||||
s.drop_id,
|
||||
s.buyer_id,
|
||||
s.size,
|
||||
s.payment_id,
|
||||
s.created_at,
|
||||
d.item as drop_item,
|
||||
d.unit as drop_unit,
|
||||
d.ppu as drop_ppu,
|
||||
b.username as buyer_username,
|
||||
b.email as buyer_email
|
||||
FROM sales s
|
||||
LEFT JOIN drops d ON s.drop_id = d.id
|
||||
LEFT JOIN buyers b ON s.buyer_id = b.id
|
||||
ORDER BY s.created_at DESC`
|
||||
)
|
||||
return NextResponse.json(rows)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sales:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch sales' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user