This commit is contained in:
root
2025-12-21 17:36:44 +01:00
parent bb1c5b43d6
commit 8a0835c564
15 changed files with 1124 additions and 193 deletions

View File

@@ -11,6 +11,7 @@ interface Drop {
unit: string
ppu: number
image_url: string | null
images?: string[]
created_at: string
start_time: string | null
}
@@ -47,8 +48,9 @@ export default function DropsManagementPage() {
imageUrl: '',
startTime: '',
})
const [imageFile, setImageFile] = useState<File | null>(null)
const [imagePreview, setImagePreview] = useState<string>('')
const [imageFiles, setImageFiles] = useState<File[]>([])
const [imagePreviews, setImagePreviews] = useState<string[]>([])
const [existingImages, setExistingImages] = useState<string[]>([])
const [uploadingImage, setUploadingImage] = useState(false)
useEffect(() => {
@@ -82,7 +84,7 @@ export default function DropsManagementPage() {
}
}
const handleEdit = (drop: Drop) => {
const handleEdit = async (drop: Drop) => {
setEditingDrop(drop)
setFormData({
item: drop.item,
@@ -92,12 +94,64 @@ export default function DropsManagementPage() {
imageUrl: drop.image_url || '',
startTime: drop.start_time ? new Date(drop.start_time).toISOString().slice(0, 16) : '',
})
// Fetch existing images for this drop
try {
const response = await fetch(`/api/drops/images?drop_id=${drop.id}`)
if (response.ok) {
const data = await response.json()
const imageUrls = data.map((img: any) => img.image_url)
setExistingImages(imageUrls)
} else {
setExistingImages(drop.image_url ? [drop.image_url] : [])
}
} catch (error) {
console.error('Error fetching drop images:', error)
setExistingImages(drop.image_url ? [drop.image_url] : [])
}
// Clear file selections
setImageFiles([])
setImagePreviews([])
}
const handleSave = async () => {
if (!editingDrop) return
try {
setUploadingImage(true)
const imageUrls: string[] = [...existingImages]
// Upload new image files
for (const file of imageFiles) {
const uploadFormData = new FormData()
uploadFormData.append('file', file)
const uploadResponse = await fetch('/api/upload', {
method: 'POST',
body: uploadFormData,
})
if (uploadResponse.ok) {
const uploadData = await uploadResponse.json()
imageUrls.push(uploadData.url)
} else {
const error = await uploadResponse.json()
alert(`Image upload failed: ${error.error}`)
setUploadingImage(false)
return
}
}
// Add URL if provided
if (formData.imageUrl) {
imageUrls.push(formData.imageUrl)
}
// Limit to 4 images total
const finalImageUrls = imageUrls.slice(0, 4)
// Update drop basic info
const response = await fetch(`/api/drops/${editingDrop.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
@@ -106,22 +160,48 @@ export default function DropsManagementPage() {
size: parseInt(formData.size),
unit: formData.unit,
ppu: parseInt(formData.ppu),
imageUrl: formData.imageUrl || null,
imageUrl: finalImageUrls[0] || null, // Keep first image for legacy support
startTime: formData.startTime || null,
}),
})
if (response.ok) {
alert('Drop updated successfully')
setEditingDrop(null)
fetchDrops()
} else {
if (!response.ok) {
const error = await response.json()
alert(`Error: ${error.error}`)
setUploadingImage(false)
return
}
// Save images (always save, even if empty array to clear all images)
const imagesResponse = await fetch('/api/drops/images', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
drop_id: editingDrop.id,
image_urls: finalImageUrls,
}),
})
if (!imagesResponse.ok) {
const error = await imagesResponse.json()
alert(`Error saving images: ${error.error}`)
setUploadingImage(false)
return
}
alert('Drop updated successfully')
setEditingDrop(null)
setImageFiles([])
setImagePreviews([])
setExistingImages([])
// Clean up preview URLs
imagePreviews.forEach(url => URL.revokeObjectURL(url))
fetchDrops()
} catch (error) {
console.error('Error updating drop:', error)
alert('Failed to update drop')
} finally {
setUploadingImage(false)
}
}
@@ -149,26 +229,63 @@ export default function DropsManagementPage() {
}
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
setImageFile(file)
setImagePreview(URL.createObjectURL(file))
// Clear the imageUrl field when a file is selected
setFormData({ ...formData, imageUrl: '' })
const files = Array.from(e.target.files || [])
if (files.length > 0) {
// Calculate how many more images we can add (max 4 total)
const currentTotal = existingImages.length + imagePreviews.length
const remainingSlots = Math.max(0, 4 - currentTotal)
if (remainingSlots === 0) {
alert('Maximum of 4 images allowed. Please remove some images first.')
// Clear the file input
e.target.value = ''
return
}
// Limit to remaining slots
const limitedFiles = files.slice(0, remainingSlots)
setImageFiles([...imageFiles, ...limitedFiles])
// Create previews for new files
const newPreviews = limitedFiles.map(file => URL.createObjectURL(file))
setImagePreviews([...imagePreviews, ...newPreviews])
// Clear the file input
e.target.value = ''
}
}
const removeImage = (index: number) => {
const newFiles = imageFiles.filter((_, i) => i !== index)
const newPreviews = imagePreviews.filter((_, i) => i !== index)
setImageFiles(newFiles)
setImagePreviews(newPreviews)
// Revoke the URL to free memory
URL.revokeObjectURL(imagePreviews[index])
}
const removeExistingImage = (index: number) => {
const newImages = existingImages.filter((_, i) => i !== index)
setExistingImages(newImages)
}
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
try {
let imageUrl = formData.imageUrl || null
setUploadingImage(true)
const imageUrls: string[] = []
// Upload image file if provided
if (imageFile) {
setUploadingImage(true)
// Add URL if provided
if (formData.imageUrl) {
imageUrls.push(formData.imageUrl)
}
// Upload image files
for (const file of imageFiles) {
const uploadFormData = new FormData()
uploadFormData.append('file', imageFile)
uploadFormData.append('file', file)
const uploadResponse = await fetch('/api/upload', {
method: 'POST',
@@ -183,10 +300,13 @@ export default function DropsManagementPage() {
}
const uploadData = await uploadResponse.json()
imageUrl = uploadData.url
setUploadingImage(false)
imageUrls.push(uploadData.url)
}
// Limit to 4 images
const finalImageUrls = imageUrls.slice(0, 4)
// Create drop
const response = await fetch('/api/drops', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -195,32 +315,56 @@ export default function DropsManagementPage() {
size: parseInt(formData.size),
unit: formData.unit,
ppu: parseInt(formData.ppu),
imageUrl: imageUrl,
imageUrl: finalImageUrls[0] || null, // Keep first image for legacy support
startTime: formData.startTime || null,
}),
})
if (response.ok) {
alert('Drop created successfully')
setFormData({
item: '',
size: '',
unit: 'g',
ppu: '',
imageUrl: '',
startTime: '',
})
setImageFile(null)
setImagePreview('')
// Clear file input
const fileInput = document.getElementById('imageFile') as HTMLInputElement
if (fileInput) fileInput.value = ''
setCreatingDrop(false)
fetchDrops()
} else {
if (!response.ok) {
const error = await response.json()
alert(`Error: ${error.error}`)
setUploadingImage(false)
return
}
const dropData = await response.json()
const dropId = dropData.id
// Save multiple images if we have more than one
if (finalImageUrls.length > 0) {
const imagesResponse = await fetch('/api/drops/images', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
drop_id: dropId,
image_urls: finalImageUrls,
}),
})
if (!imagesResponse.ok) {
const error = await imagesResponse.json()
alert(`Drop created but failed to save images: ${error.error}`)
}
}
alert('Drop created successfully')
setFormData({
item: '',
size: '',
unit: 'g',
ppu: '',
imageUrl: '',
startTime: '',
})
setImageFiles([])
setImagePreviews([])
// Clean up preview URLs
imagePreviews.forEach(url => URL.revokeObjectURL(url))
// Clear file input
const fileInput = document.getElementById('imageFiles') as HTMLInputElement
if (fileInput) fileInput.value = ''
setCreatingDrop(false)
fetchDrops()
} catch (error) {
console.error('Error creating drop:', error)
alert('Failed to create drop')
@@ -296,9 +440,11 @@ export default function DropsManagementPage() {
imageUrl: '',
startTime: '',
})
setImageFile(null)
setImagePreview('')
const fileInput = document.getElementById('imageFile') as HTMLInputElement
setImageFiles([])
setImagePreviews([])
setExistingImages([])
imagePreviews.forEach(url => URL.revokeObjectURL(url))
const fileInput = document.getElementById('imageFiles') as HTMLInputElement
if (fileInput) fileInput.value = ''
}
}}
@@ -403,12 +549,15 @@ export default function DropsManagementPage() {
/>
</div>
<div style={{ gridColumn: '1 / -1' }}>
<label style={{ display: 'block', marginBottom: '8px' }}>Product Image</label>
<label style={{ display: 'block', marginBottom: '8px' }}>
Product Images (up to 4)
</label>
<input
type="file"
id="imageFile"
id="imageFiles"
accept="image/jpeg,image/jpg,image/png,image/webp"
onChange={handleImageChange}
multiple
style={{
width: '100%',
padding: '8px',
@@ -419,38 +568,96 @@ export default function DropsManagementPage() {
cursor: 'pointer'
}}
/>
{imagePreview && (
<div style={{ marginTop: '12px' }}>
<img
src={imagePreview}
alt="Preview"
style={{
maxWidth: '200px',
maxHeight: '200px',
borderRadius: '8px',
objectFit: 'cover'
}}
/>
{(imagePreviews.length > 0 || existingImages.length > 0) && (
<div style={{
marginTop: '12px',
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
gap: '12px'
}}>
{existingImages.map((imgUrl, index) => (
<div key={`existing-${index}`} style={{ position: 'relative' }}>
<img
src={imgUrl}
alt={`Existing ${index + 1}`}
style={{
width: '100%',
height: '150px',
borderRadius: '8px',
objectFit: 'cover',
border: '1px solid var(--border)'
}}
/>
<button
type="button"
onClick={() => removeExistingImage(index)}
style={{
position: 'absolute',
top: '4px',
right: '4px',
background: 'rgba(220, 38, 38, 0.9)',
color: '#fff',
border: 'none',
borderRadius: '4px',
width: '24px',
height: '24px',
cursor: 'pointer',
fontSize: '16px',
lineHeight: '1'
}}
>
×
</button>
</div>
))}
{imagePreviews.map((preview, index) => (
<div key={`preview-${index}`} style={{ position: 'relative' }}>
<img
src={preview}
alt={`Preview ${index + 1}`}
style={{
width: '100%',
height: '150px',
borderRadius: '8px',
objectFit: 'cover',
border: '1px solid var(--border)'
}}
/>
<button
type="button"
onClick={() => removeImage(index)}
style={{
position: 'absolute',
top: '4px',
right: '4px',
background: 'rgba(220, 38, 38, 0.9)',
color: '#fff',
border: 'none',
borderRadius: '4px',
width: '24px',
height: '24px',
cursor: 'pointer',
fontSize: '16px',
lineHeight: '1'
}}
>
×
</button>
</div>
))}
</div>
)}
<p style={{ marginTop: '8px', fontSize: '12px', color: 'var(--muted)' }}>
Max file size: 5MB. Allowed formats: JPEG, PNG, WebP
Max 4 images. Max file size: 5MB each. Allowed formats: JPEG, PNG, WebP
</p>
<p style={{ marginTop: '4px', fontSize: '12px', color: 'var(--muted)' }}>
Or enter an image URL:
Or enter an image URL (will be added to uploaded images):
</p>
<input
type="text"
value={formData.imageUrl}
onChange={(e) => {
setFormData({ ...formData, imageUrl: e.target.value })
// Clear file selection when URL is entered
if (e.target.value) {
setImageFile(null)
setImagePreview('')
const fileInput = document.getElementById('imageFile') as HTMLInputElement
if (fileInput) fileInput.value = ''
}
}}
placeholder="https://example.com/image.jpg"
style={{
@@ -574,22 +781,6 @@ export default function DropsManagementPage() {
}}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '8px' }}>Image URL</label>
<input
type="text"
value={formData.imageUrl}
onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
style={{
width: '100%',
padding: '8px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)'
}}
/>
</div>
<div>
<label style={{ display: 'block', marginBottom: '8px' }}>Start Time</label>
<input
@@ -607,16 +798,147 @@ export default function DropsManagementPage() {
/>
</div>
</div>
<div style={{ gridColumn: '1 / -1', marginTop: '16px' }}>
<label style={{ display: 'block', marginBottom: '8px' }}>
Product Images (up to 4)
</label>
<input
type="file"
id="imageFilesEdit"
accept="image/jpeg,image/jpg,image/png,image/webp"
onChange={handleImageChange}
multiple
style={{
width: '100%',
padding: '8px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)',
cursor: 'pointer'
}}
/>
{(imagePreviews.length > 0 || existingImages.length > 0) && (
<div style={{
marginTop: '12px',
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
gap: '12px'
}}>
{existingImages.map((imgUrl, index) => (
<div key={`existing-${index}`} style={{ position: 'relative' }}>
<img
src={imgUrl}
alt={`Existing ${index + 1}`}
style={{
width: '100%',
height: '150px',
borderRadius: '8px',
objectFit: 'cover',
border: '1px solid var(--border)'
}}
/>
<button
type="button"
onClick={() => removeExistingImage(index)}
style={{
position: 'absolute',
top: '4px',
right: '4px',
background: 'rgba(220, 38, 38, 0.9)',
color: '#fff',
border: 'none',
borderRadius: '4px',
width: '24px',
height: '24px',
cursor: 'pointer',
fontSize: '16px',
lineHeight: '1'
}}
>
×
</button>
</div>
))}
{imagePreviews.map((preview, index) => (
<div key={`preview-${index}`} style={{ position: 'relative' }}>
<img
src={preview}
alt={`Preview ${index + 1}`}
style={{
width: '100%',
height: '150px',
borderRadius: '8px',
objectFit: 'cover',
border: '1px solid var(--border)'
}}
/>
<button
type="button"
onClick={() => removeImage(index)}
style={{
position: 'absolute',
top: '4px',
right: '4px',
background: 'rgba(220, 38, 38, 0.9)',
color: '#fff',
border: 'none',
borderRadius: '4px',
width: '24px',
height: '24px',
cursor: 'pointer',
fontSize: '16px',
lineHeight: '1'
}}
>
×
</button>
</div>
))}
</div>
)}
<p style={{ marginTop: '8px', fontSize: '12px', color: 'var(--muted)' }}>
Max 4 images. Max file size: 5MB each. Allowed formats: JPEG, PNG, WebP
</p>
<p style={{ marginTop: '4px', fontSize: '12px', color: 'var(--muted)' }}>
Or enter an image URL (will be added to uploaded images):
</p>
<input
type="text"
value={formData.imageUrl}
onChange={(e) => {
setFormData({ ...formData, imageUrl: e.target.value })
}}
placeholder="https://example.com/image.jpg"
style={{
width: '100%',
padding: '8px',
borderRadius: '8px',
border: '1px solid var(--border)',
background: 'var(--bg-soft)',
color: 'var(--text)',
marginTop: '8px'
}}
/>
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<button
onClick={handleSave}
className="cta"
disabled={uploadingImage}
style={{ padding: '8px 16px', fontSize: '14px' }}
>
Save
{uploadingImage ? 'Uploading images...' : 'Save'}
</button>
<button
onClick={() => setEditingDrop(null)}
onClick={() => {
setEditingDrop(null)
setImageFiles([])
setImagePreviews([])
setExistingImages([])
// Clean up preview URLs
imagePreviews.forEach(url => URL.revokeObjectURL(url))
}}
style={{
padding: '8px 16px',
fontSize: '14px',
@@ -652,18 +974,49 @@ export default function DropsManagementPage() {
{drop.unit === 'kg' ? drop.fill.toFixed(2) : Math.round(drop.fill)}{drop.unit} of {drop.size}{drop.unit} reserved
</p>
{drop.image_url && (
<img
src={drop.image_url}
alt={drop.item}
style={{
maxWidth: '200px',
maxHeight: '200px',
marginTop: '12px',
borderRadius: '8px'
}}
/>
)}
{/* Display all images */}
{(() => {
const images = drop.images && drop.images.length > 0
? drop.images
: (drop.image_url ? [drop.image_url] : [])
if (images.length === 0) return null
return (
<div style={{ marginTop: '12px' }}>
<div style={{
display: 'grid',
gridTemplateColumns: images.length > 1 ? 'repeat(auto-fit, minmax(150px, 1fr))' : '1fr',
gap: '8px',
maxWidth: images.length === 1 ? '200px' : '100%'
}}>
{images.slice(0, 4).map((imgUrl, index) => (
<img
key={index}
src={imgUrl}
alt={`${drop.item} - Image ${index + 1}`}
style={{
width: '100%',
height: '150px',
objectFit: 'cover',
borderRadius: '8px',
border: '1px solid var(--border)'
}}
/>
))}
</div>
{images.length > 4 && (
<p style={{
marginTop: '8px',
fontSize: '12px',
color: 'var(--muted)'
}}>
+{images.length - 4} more image{images.length - 4 > 1 ? 's' : ''}
</p>
)}
</div>
)
})()}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<button

View File

@@ -51,6 +51,13 @@ export async function GET() {
}
const totalFill = salesFill + pendingFill
// 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)
console.log(`Returning upcoming drop ${drop.id} (${drop.item}): fill=${totalFill}, size=${drop.size}, starts at ${startTime.toISOString()}`)
return NextResponse.json({
...drop,
@@ -59,6 +66,7 @@ export async function GET() {
pending_fill: pendingFill,
is_upcoming: true,
start_time: drop.start_time || drop.created_at,
images: images.length > 0 ? images : (drop.image_url ? [drop.image_url] : []), // Support legacy single image_url
})
}
@@ -118,6 +126,14 @@ export async function GET() {
if (remaining > epsilon) {
// Ensure pending_fill is explicitly 0 if no pending orders
const finalPendingFill = Number(pendingFill) || 0
// 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)
console.log(`Returning active drop ${drop.id} with fill ${fillNum} < size ${dropSize}, pending_fill=${finalPendingFill} (raw: ${pendingFill})`)
return NextResponse.json({
...drop,
@@ -126,6 +142,7 @@ export async function GET() {
pending_fill: finalPendingFill, // Items on hold (explicitly 0 if no pending orders)
is_upcoming: false,
start_time: drop.start_time || drop.created_at,
images: images.length > 0 ? images : (drop.image_url ? [drop.image_url] : []), // Support legacy single image_url
})
} else {
console.log(`Drop ${drop.id} is sold out: fill=${fillNum} >= size=${dropSize} (remaining=${remaining})`)

View File

@@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
// GET /api/drops/images?drop_id=X - Get all images for a drop
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const dropId = searchParams.get('drop_id')
if (!dropId) {
return NextResponse.json(
{ error: 'drop_id parameter is required' },
{ status: 400 }
)
}
const [rows] = await pool.execute(
'SELECT id, image_url, display_order FROM drop_images WHERE drop_id = ? ORDER BY display_order ASC LIMIT 4',
[dropId]
)
return NextResponse.json(rows)
} catch (error) {
console.error('Error fetching drop images:', error)
return NextResponse.json(
{ error: 'Failed to fetch drop images' },
{ status: 500 }
)
}
}
// POST /api/drops/images - Add images to a drop
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { drop_id, image_urls } = body
if (!drop_id || !image_urls || !Array.isArray(image_urls)) {
return NextResponse.json(
{ error: 'drop_id and image_urls array are required' },
{ status: 400 }
)
}
if (image_urls.length > 4) {
return NextResponse.json(
{ error: 'Maximum 4 images allowed per drop' },
{ status: 400 }
)
}
// Delete existing images for this drop
await pool.execute('DELETE FROM drop_images WHERE drop_id = ?', [drop_id])
// Insert new images
for (let i = 0; i < image_urls.length; i++) {
await pool.execute(
'INSERT INTO drop_images (drop_id, image_url, display_order) VALUES (?, ?, ?)',
[drop_id, image_urls[i], i]
)
}
return NextResponse.json({ success: true })
} catch (error) {
console.error('Error saving drop images:', error)
return NextResponse.json(
{ error: 'Failed to save drop images' },
{ status: 500 }
)
}
}

View File

@@ -45,10 +45,18 @@ export async function GET() {
(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
})
}
}

View File

@@ -9,7 +9,7 @@ export async function GET(request: NextRequest) {
)
const drops = rows as any[]
// Calculate fill from sales for each drop
// Calculate fill from sales for each drop and fetch images
const dropsWithFill = await Promise.all(
drops.map(async (drop) => {
// Calculate fill from sales records
@@ -27,9 +27,17 @@ export async function GET(request: NextRequest) {
fill = totalFillInGrams / 1000
}
// Fetch images for this drop
const [imageRows] = await pool.execute(
'SELECT image_url FROM drop_images WHERE drop_id = ? ORDER BY display_order ASC',
[drop.id]
)
const images = (imageRows as any[]).map((row) => row.image_url)
return {
...drop,
fill: fill,
images: images.length > 0 ? images : (drop.image_url ? [drop.image_url] : []),
}
})
)

View File

@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import pool from '@/lib/db'
import { getNowPaymentsConfig } from '@/lib/nowpayments'
import { ALLOWED_PAYMENT_CURRENCIES, isAllowedCurrency } from '@/lib/payment-currencies'
// POST /api/payments/create-invoice - Create a NOWPayments payment
// Note: Endpoint name kept as "create-invoice" for backward compatibility
@@ -32,6 +33,15 @@ export async function POST(request: NextRequest) {
)
}
// Validate pay_currency against allowed list
const normalizedPayCurrency = pay_currency ? String(pay_currency).trim().toLowerCase() : null
if (normalizedPayCurrency && !isAllowedCurrency(normalizedPayCurrency)) {
return NextResponse.json(
{ error: `Invalid payment currency. Allowed currencies: ${ALLOWED_PAYMENT_CURRENCIES.join(', ').toUpperCase()}` },
{ status: 400 }
)
}
// Verify buyer_data_id exists and belongs to the buyer
const [buyerDataRows] = await pool.execute(
'SELECT id FROM buyer_data WHERE id = ? AND buyer_id = ?',
@@ -154,8 +164,9 @@ export async function POST(request: NextRequest) {
// Create NOWPayments payment
// Note: Payment API requires pay_currency (crypto currency)
// Use currency from request, or fall back to env/default
const payCurrency = pay_currency || process.env.NOWPAYMENTS_PAY_CURRENCY || 'btc'
// Use currency from request (already validated), or fall back to env/default (must be in allowed list)
const defaultCurrency = process.env.NOWPAYMENTS_PAY_CURRENCY?.toLowerCase() || 'btc'
const payCurrency = normalizedPayCurrency || (isAllowedCurrency(defaultCurrency) ? defaultCurrency : 'btc')
// Optional: Use fixed rate for 20 minutes (prevents rate changes during checkout)
// If is_fixed_rate is true, payment expires after 20 minutes if not paid

View File

@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server'
import { getNowPaymentsConfig } from '@/lib/nowpayments'
import { ALLOWED_PAYMENT_CURRENCIES } from '@/lib/payment-currencies'
// GET /api/payments/currencies - Get available payment currencies from NOWPayments
export async function GET() {
@@ -27,10 +28,27 @@ export async function GET() {
}
const data = await response.json()
// Filter currencies to only include the selected list
const currencies = (data.currencies || []).filter((c: any) => {
let currencyCode: string | null = null
// Handle object format (when fixed_rate=true)
if (typeof c === 'object' && c !== null && c.currency) {
currencyCode = String(c.currency).trim().toLowerCase()
}
// Handle string format (when fixed_rate=false)
else if (typeof c === 'string') {
currencyCode = c.trim().toLowerCase()
}
// Check if currency is in the allowed list
return currencyCode && ALLOWED_PAYMENT_CURRENCIES.includes(currencyCode as any)
})
// Return the currencies array
// Return the filtered currencies array
return NextResponse.json({
currencies: data.currencies || [],
currencies: currencies,
})
} catch (error) {
console.error('Error fetching currencies:', error)

View File

@@ -13,6 +13,7 @@ interface DropData {
unit: string
ppu: number
image_url: string | null
images?: string[] // Array of image URLs (up to 4)
created_at: string
start_time: string | null
is_upcoming?: boolean
@@ -30,6 +31,8 @@ export default function Drop() {
const [drop, setDrop] = useState<DropData | null>(null)
const [loading, setLoading] = useState(true)
const [selectedSize, setSelectedSize] = useState(50)
const [customQuantity, setCustomQuantity] = useState<string>('')
const [quantityError, setQuantityError] = useState<string>('')
const [selectedCurrency, setSelectedCurrency] = useState<string>('btc')
const [availableCurrencies, setAvailableCurrencies] = useState<string[]>([])
const [loadingCurrencies, setLoadingCurrencies] = useState(false)
@@ -48,11 +51,19 @@ export default function Drop() {
const [checkingAuth, setCheckingAuth] = useState(true)
const [isWholesaleUnlocked, setIsWholesaleUnlocked] = useState(false)
const [showUnlockModal, setShowUnlockModal] = useState(false)
const [selectedImageIndex, setSelectedImageIndex] = useState(0)
useEffect(() => {
fetchActiveDrop()
checkAuth()
checkWholesaleStatus()
// Poll active drop every 30 seconds
const interval = setInterval(() => {
fetchActiveDrop()
}, 30000) // 30 seconds
return () => clearInterval(interval)
}, [])
const checkWholesaleStatus = async () => {
@@ -122,7 +133,10 @@ export default function Drop() {
const fetchActiveDrop = async () => {
try {
const response = await fetch('/api/drops/active')
const response = await fetch('/api/drops/active', {
// Add cache control to prevent stale data
cache: 'no-store',
})
if (response.ok) {
const data = await response.json()
// Handle both null response and actual drop data
@@ -169,6 +183,71 @@ export default function Drop() {
return sizes.filter((size) => size <= remainingInGrams)
}
const getRemainingInGrams = () => {
if (!drop) return 0
if (drop.unit === 'kg') {
return (drop.size - drop.fill) * 1000
}
return drop.size - drop.fill
}
const getMinimumGrams = () => {
if (!drop) return 0
// Minimum price is 5 CHF
// Calculate minimum grams needed for 5 CHF
const pricePerGram = drop.ppu / 1000
// Use the higher price (standard) to ensure minimum is met
return Math.ceil(5 / pricePerGram)
}
const handleCustomQuantityChange = (value: string) => {
setCustomQuantity(value)
setQuantityError('')
// Clear selected preset size when custom input is used
if (value.trim() !== '') {
const numValue = parseInt(value, 10)
if (!isNaN(numValue) && numValue > 0) {
setSelectedSize(numValue)
}
}
}
const validateCustomQuantity = () => {
if (!drop || !customQuantity.trim()) {
setQuantityError('')
return true
}
const numValue = parseInt(customQuantity, 10)
const remaining = getRemainingInGrams()
const minimum = getMinimumGrams()
if (isNaN(numValue) || numValue <= 0) {
setQuantityError('Please enter a valid number')
return false
}
if (numValue < minimum) {
setQuantityError(`Minimum ${minimum}g required (5 CHF minimum)`)
return false
}
if (numValue > remaining) {
setQuantityError(`Maximum ${remaining}g available`)
return false
}
setQuantityError('')
return true
}
const handleQuantityButtonClick = (size: number) => {
setSelectedSize(size)
setCustomQuantity('')
setQuantityError('')
}
const fetchAvailableCurrencies = async () => {
setLoadingCurrencies(true)
try {
@@ -233,6 +312,11 @@ export default function Drop() {
}
const handleJoinDrop = () => {
// Validate custom quantity if entered
if (customQuantity && !validateCustomQuantity()) {
return
}
// Check if user is logged in
if (!user) {
setShowAuthModal(true)
@@ -357,6 +441,18 @@ export default function Drop() {
return selectedSize * priceToUse
}
const calculateStandardPrice = () => {
if (!drop) return 0
const pricePerGram = drop.ppu / 1000
return selectedSize * pricePerGram
}
const calculateWholesalePrice = () => {
if (!drop) return 0
const pricePerGram = drop.ppu / 1000
return selectedSize * pricePerGram * 0.76
}
const getTimeUntilStart = () => {
if (!drop || !drop.is_upcoming || !drop.start_time) return null
@@ -379,6 +475,22 @@ export default function Drop() {
}
}
// Get images array (prioritize new images array, fallback to legacy image_url)
// Must be defined before early returns to maintain hook order
const images = drop?.images && drop.images.length > 0
? drop.images
: (drop?.image_url ? [drop.image_url] : [])
// Reset selected image index when images change
// Must be called before early returns to maintain hook order
useEffect(() => {
if (images.length > 0 && selectedImageIndex >= images.length) {
setSelectedImageIndex(0)
} else if (images.length === 0) {
setSelectedImageIndex(0)
}
}, [images, selectedImageIndex])
if (loading) {
return (
<div className="drop">
@@ -416,14 +528,66 @@ export default function Drop() {
return (
<div className="drop">
{drop.image_url ? (
<Image
src={drop.image_url}
alt={drop.item}
width={420}
height={420}
style={{ width: '100%', height: 'auto', borderRadius: '16px', objectFit: 'cover' }}
/>
{images.length > 0 ? (
<div>
{/* Main large image */}
<div style={{ marginBottom: '12px' }}>
<Image
src={images[selectedImageIndex]}
alt={`${drop.item} - Image ${selectedImageIndex + 1}`}
width={420}
height={420}
style={{
width: '100%',
height: 'auto',
borderRadius: '16px',
objectFit: 'cover',
aspectRatio: '1 / 1'
}}
/>
</div>
{/* Thumbnails */}
{images.length > 1 && (
<div style={{
display: 'grid',
gridTemplateColumns: `repeat(${Math.min(images.length, 4)}, 1fr)`,
gap: '8px'
}}>
{images.slice(0, 4).map((imgUrl, index) => (
<button
key={index}
onClick={() => setSelectedImageIndex(index)}
style={{
padding: 0,
border: selectedImageIndex === index
? '2px solid var(--accent)'
: '2px solid transparent',
borderRadius: '8px',
background: 'transparent',
cursor: 'pointer',
overflow: 'hidden',
aspectRatio: '1 / 1'
}}
>
<Image
src={imgUrl}
alt={`${drop.item} - Thumbnail ${index + 1}`}
width={100}
height={100}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
opacity: selectedImageIndex === index ? 1 : 0.7,
transition: 'opacity 0.2s'
}}
/>
</button>
))}
</div>
)}
</div>
) : (
<div
style={{
@@ -506,18 +670,74 @@ export default function Drop() {
</>
)}
{!isUpcoming && hasRemaining && availableSizes.length > 0 && (
{!isUpcoming && hasRemaining && (
<>
<div className="options">
{availableSizes.map((size) => (
<button
key={size}
className={selectedSize === size ? 'active' : ''}
onClick={() => setSelectedSize(size)}
>
{size}g
</button>
))}
<div style={{ display: 'flex', gap: '12px', alignItems: 'flex-start', flexWrap: 'wrap' }}>
{availableSizes.length > 0 && (
<div className="options" style={{ flex: '1', minWidth: '200px' }}>
{availableSizes.map((size) => (
<button
key={size}
className={selectedSize === size && !customQuantity ? 'active' : ''}
onClick={() => handleQuantityButtonClick(size)}
>
{size}g
</button>
))}
</div>
)}
<div style={{ flex: availableSizes.length > 0 ? '1' : '100%', minWidth: '150px' }}>
<input
type="number"
value={customQuantity}
onChange={(e) => handleCustomQuantityChange(e.target.value)}
onBlur={validateCustomQuantity}
placeholder="Custom (g)"
min={getMinimumGrams()}
max={getRemainingInGrams()}
style={{
width: '100%',
padding: '14px',
borderRadius: '12px',
border: `1px solid ${quantityError ? '#dc2626' : 'var(--border)'}`,
background: 'var(--bg-soft)',
color: 'var(--text)',
fontSize: '14px',
}}
/>
{quantityError && (
<div style={{ marginTop: '6px', fontSize: '12px', color: '#dc2626' }}>
{quantityError}
</div>
)}
{!quantityError && customQuantity && (
<div style={{ marginTop: '6px', fontSize: '12px', color: 'var(--muted)' }}>
Min: {getMinimumGrams()}g · Max: {getRemainingInGrams()}g
</div>
)}
</div>
</div>
<div style={{ marginTop: '24px', marginBottom: '16px' }}>
{isWholesaleUnlocked ? (
<>
<div style={{ fontSize: '18px', fontWeight: 500, marginBottom: '8px' }}>
Total: {calculatePrice().toFixed(2)} CHF
</div>
<div style={{ fontSize: '14px', color: 'var(--muted)' }}>
Standard total: {calculateStandardPrice().toFixed(2)} CHF
</div>
</>
) : (
<>
<div style={{ fontSize: '18px', fontWeight: 500, marginBottom: '8px' }}>
Total: {calculateStandardPrice().toFixed(2)} CHF
</div>
<div style={{ fontSize: '14px', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: '6px' }}>
Wholesale total: {calculateWholesalePrice().toFixed(2)} CHF 🔒
</div>
</>
)}
</div>
<button className="cta" onClick={handleJoinDrop}>
@@ -841,10 +1061,28 @@ export default function Drop() {
onClick={(e) => e.stopPropagation()}
>
<h2 style={{ marginTop: 0, marginBottom: '20px', color: '#0a7931' }}>
Payment Confirmed!
Payment confirmed
</h2>
<p style={{ marginBottom: '24px', color: 'var(--muted)' }}>
Your payment has been successfully processed. Your order is confirmed and will be included in the drop.
<p style={{ marginBottom: '16px', color: 'var(--text)' }}>
Your order has been successfully processed and is now reserved in this drop.
</p>
<div style={{ marginBottom: '24px' }}>
<p style={{ marginBottom: '12px', fontWeight: '600', color: 'var(--text)' }}>
What happens next:
</p>
<ul style={{
margin: 0,
paddingLeft: '20px',
color: 'var(--muted)',
lineHeight: '1.8'
}}>
<li>Your order will be processed within 24 hours</li>
<li>Shipped via express delivery</li>
<li>You'll receive a shipping confirmation and tracking link by email</li>
</ul>
</div>
<p style={{ marginBottom: '24px', color: 'var(--muted)', fontStyle: 'italic' }}>
Thank you for being part of the collective.
</p>
<div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
<button

View File

@@ -13,6 +13,7 @@ export default function Nav() {
const [user, setUser] = useState<User | null>(null)
const [showAuthModal, setShowAuthModal] = useState(false)
const [loading, setLoading] = useState(true)
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
useEffect(() => {
checkAuth()
@@ -54,15 +55,26 @@ export default function Nav() {
return (
<>
<nav>
<div className="brand">
<a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
<img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
</a>
</div>
<div className="links">
<a href="#drop">Drop</a>
<a href="#past">Past Drops</a>
<a href="#community">Community</a>
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
<div className="brand">
<a href="/" style={{ display: 'inline-block', textDecoration: 'none' }}>
<img src="/header.jpg" alt="420Deals.ch" style={{ height: '40px', width: 'auto' }} />
</a>
</div>
<button
className="mobile-menu-toggle"
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
aria-label="Toggle menu"
>
<span style={{ display: mobileMenuOpen ? 'none' : 'block' }}></span>
<span style={{ display: mobileMenuOpen ? 'block' : 'none' }}></span>
</button>
</div>
<div className={`links ${mobileMenuOpen ? 'mobile-open' : ''}`}>
<a href="#drop" onClick={() => setMobileMenuOpen(false)}>Drop</a>
<a href="#past" onClick={() => setMobileMenuOpen(false)}>Past Drops</a>
<a href="#community" onClick={() => setMobileMenuOpen(false)}>Community</a>
{!loading && (
user ? (
<>
@@ -71,6 +83,7 @@ export default function Nav() {
</span>
<a
href="/orders"
onClick={() => setMobileMenuOpen(false)}
style={{
background: 'transparent',
border: '1px solid var(--border)',
@@ -89,7 +102,10 @@ export default function Nav() {
Orders
</a>
<button
onClick={handleLogout}
onClick={() => {
handleLogout()
setMobileMenuOpen(false)
}}
style={{
background: 'transparent',
border: '1px solid #e57373',
@@ -109,7 +125,10 @@ export default function Nav() {
</>
) : (
<button
onClick={() => setShowAuthModal(true)}
onClick={() => {
setShowAuthModal(true)
setMobileMenuOpen(false)
}}
style={{
padding: '8px 16px',
fontSize: '14px',
@@ -129,6 +148,7 @@ export default function Nav() {
</button>
)
)}
</div>
</div>
</nav>

View File

@@ -11,6 +11,7 @@ interface PastDrop {
unit: string
ppu: number
image_url: string | null
images?: string[] // Array of image URLs (up to 4)
created_at: string
soldOutInHours: number
}
@@ -26,11 +27,21 @@ export default function PastDrops({ limit, showMoreLink = false }: PastDropsProp
useEffect(() => {
fetchPastDrops()
// Poll past drops every 30 seconds
const interval = setInterval(() => {
fetchPastDrops()
}, 30000) // 30 seconds
return () => clearInterval(interval)
}, [])
const fetchPastDrops = async () => {
try {
const response = await fetch('/api/drops/past')
const response = await fetch('/api/drops/past', {
// Add cache control to prevent stale data
cache: 'no-store',
})
if (response.ok) {
const data = await response.json()
setDrops(data)
@@ -98,49 +109,59 @@ export default function PastDrops({ limit, showMoreLink = false }: PastDropsProp
return (
<>
<div className="past">
{displayedDrops.map((drop) => (
<div key={drop.id} className="card">
{drop.image_url ? (
<div style={{ marginBottom: '12px' }}>
<Image
src={drop.image_url}
alt={drop.item}
width={300}
height={300}
{displayedDrops.map((drop) => {
// Get images array (prioritize new images array, fallback to legacy image_url)
const images = drop.images && drop.images.length > 0
? drop.images
: (drop.image_url ? [drop.image_url] : [])
return (
<div key={drop.id} className="card">
{images.length > 0 ? (
<div style={{ marginBottom: '12px', display: 'grid', gridTemplateColumns: images.length > 1 ? '1fr 1fr' : '1fr', gap: '4px' }}>
{images.slice(0, 4).map((imgUrl, index) => (
<Image
key={index}
src={imgUrl}
alt={`${drop.item} - Image ${index + 1}`}
width={300}
height={300}
style={{
width: '100%',
height: '200px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
))}
</div>
) : (
<div
style={{
width: '100%',
height: '200px',
background: 'var(--bg-soft)',
borderRadius: '12px',
objectFit: 'cover',
marginBottom: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--muted)',
}}
/>
</div>
) : (
<div
style={{
width: '100%',
height: '200px',
background: 'var(--bg-soft)',
borderRadius: '12px',
marginBottom: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--muted)',
}}
>
No Image
</div>
)}
<strong>{drop.item}</strong>
<br />
<span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
<br />
<span className="meta" style={{ fontSize: '13px', marginTop: '4px', display: 'block' }}>
{formatQuantity(drop.size, drop.unit)} · {formatDateAndTime(drop.created_at)}
</span>
</div>
))}
>
No Image
</div>
)}
<strong>{drop.item}</strong>
<br />
<span className="meta">{formatSoldOutTime(drop.soldOutInHours)}</span>
<br />
<span className="meta" style={{ fontSize: '13px', marginTop: '4px', display: 'block' }}>
{formatQuantity(drop.size, drop.unit)} · {formatDateAndTime(drop.created_at)}
</span>
</div>
)
})}
</div>
{showMoreLink && hasMore && (
<div style={{ textAlign: 'center', marginTop: '30px' }}>

View File

@@ -46,14 +46,7 @@ export default function UnlockBar() {
}
if (loading) {
return (
<div className="unlock-bar">
🔒 Wholesale prices locked <strong>Loading...</strong>
<br />
<small>3 verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
</div>
)
return null
}
const status = referralStatus || {
@@ -67,7 +60,9 @@ export default function UnlockBar() {
if (status.isUnlocked) {
return (
<div className="unlock-bar" style={{ background: 'var(--accent)', color: '#000' }}>
Wholesale prices unlocked <strong>You have access to wholesale pricing!</strong>
<div>
Wholesale prices unlocked <strong>You have access to wholesale pricing!</strong>
</div>
</div>
)
}
@@ -75,10 +70,12 @@ export default function UnlockBar() {
return (
<>
<div className="unlock-bar">
🔒 Wholesale prices locked <strong>{status.referralCount} / {status.referralsNeeded} referrals completed</strong> · {status.referralsRemaining} to go
<br />
<small>{status.referralsNeeded} verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
<div>
🔒 Wholesale prices locked <strong>{status.referralCount} / {status.referralsNeeded} referrals completed</strong> · {status.referralsRemaining} to go
<br />
<small>{status.referralsNeeded} verified sign-ups unlock wholesale prices forever.</small>
<a href="#unlock" onClick={handleUnlockClick}>Unlock now</a>
</div>
</div>
<UnlockModal isOpen={showModal} onClose={() => setShowModal(false)} />
</>

View File

@@ -1,12 +1,19 @@
'use client'
import { useState, useEffect } from 'react'
import { useState, useEffect, Suspense } from 'react'
import AuthModal from './AuthModal'
interface UnlockModalProps {
isOpen: boolean
onClose: () => void
}
interface User {
id: number
username: string
email: string
}
interface ReferralStatus {
referralCount: number
isUnlocked: boolean
@@ -19,6 +26,7 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
const [referralLink, setReferralLink] = useState<string>('')
const [loading, setLoading] = useState(true)
const [copied, setCopied] = useState(false)
const [showAuthModal, setShowAuthModal] = useState(false)
useEffect(() => {
if (isOpen) {
@@ -63,6 +71,12 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
}
}
const handleLogin = async (user: User) => {
setShowAuthModal(false)
// Refresh referral data after login
await fetchReferralData()
}
if (!isOpen) return null
const status = referralStatus || {
@@ -192,11 +206,26 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
borderRadius: '8px',
marginBottom: '24px',
textAlign: 'center',
color: 'var(--muted)',
fontSize: '14px',
}}
>
Please log in to get your referral link
<p style={{ color: 'var(--muted)', fontSize: '14px', margin: '0 0 12px 0' }}>
Please log in to get your referral link
</p>
<button
onClick={() => setShowAuthModal(true)}
style={{
padding: '10px 20px',
background: 'var(--accent)',
color: '#000',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '14px',
fontWeight: 500,
}}
>
Login
</button>
</div>
)}
@@ -245,6 +274,15 @@ export default function UnlockModal({ isOpen, onClose }: UnlockModalProps) {
</>
)}
</div>
{/* Auth Modal */}
<Suspense fallback={null}>
<AuthModal
isOpen={showAuthModal}
onClose={() => setShowAuthModal(false)}
onLogin={handleLogin}
/>
</Suspense>
</div>
)
}

View File

@@ -32,7 +32,14 @@ nav {
background: rgba(14, 14, 14, 0.9);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--border);
padding: 20px 40px;
padding: 20px;
display: flex;
justify-content: center;
}
nav > div {
max-width: 1200px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
@@ -44,6 +51,24 @@ nav .brand {
letter-spacing: 0.5px;
}
.mobile-menu-toggle {
display: none;
background: transparent;
border: 1px solid var(--border);
color: var(--text);
padding: 8px 12px;
border-radius: 8px;
cursor: pointer;
font-size: 20px;
line-height: 1;
}
nav .links {
display: flex;
align-items: center;
flex-wrap: wrap;
}
nav .links a {
margin-left: 28px;
font-size: 14px;
@@ -54,6 +79,60 @@ nav .links a:hover {
color: var(--text);
}
@media (max-width: 768px) {
nav > div {
flex-direction: column;
align-items: flex-start;
}
nav > div > div:first-child {
width: 100%;
justify-content: space-between;
}
.mobile-menu-toggle {
display: block;
}
nav .links {
display: none;
flex-direction: column;
width: 100%;
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid var(--border);
gap: 16px;
}
nav .links.mobile-open {
display: flex;
}
nav .links a {
margin-left: 0;
padding: 12px 0;
width: 100%;
text-align: left;
border-bottom: 1px solid var(--border);
}
nav .links a:last-child {
border-bottom: none;
}
nav .links span,
nav .links button {
margin-left: 0 !important;
margin-top: 12px;
width: 100%;
text-align: left;
}
nav .links button {
justify-content: flex-start;
}
}
.unlock-bar {
background: var(--bg-soft);
border-bottom: 1px solid var(--border);
@@ -61,6 +140,13 @@ nav .links a:hover {
font-size: 14px;
color: var(--muted);
text-align: center;
display: flex;
justify-content: center;
}
.unlock-bar > div {
max-width: 1200px;
width: 100%;
}
.unlock-bar strong {