notification + admin panel
This commit is contained in:
321
app/admin/buyers/page.tsx
Normal file
321
app/admin/buyers/page.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
interface Buyer {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export default function BuyersManagementPage() {
|
||||
const router = useRouter()
|
||||
const [buyers, setBuyers] = useState<Buyer[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [authenticated, setAuthenticated] = useState(false)
|
||||
const [editingBuyer, setEditingBuyer] = useState<Buyer | null>(null)
|
||||
const [formData, setFormData] = useState({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// Check authentication
|
||||
fetch('/api/admin/check')
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.authenticated) {
|
||||
setAuthenticated(true)
|
||||
fetchBuyers()
|
||||
} else {
|
||||
router.push('/admin/login')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
router.push('/admin/login')
|
||||
})
|
||||
}, [router])
|
||||
|
||||
const fetchBuyers = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/buyers')
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setBuyers(Array.isArray(data) ? data : [])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching buyers:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (buyer: Buyer) => {
|
||||
setEditingBuyer(buyer)
|
||||
setFormData({
|
||||
username: buyer.username,
|
||||
email: buyer.email,
|
||||
password: '',
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editingBuyer) return
|
||||
|
||||
try {
|
||||
const updateData: any = {}
|
||||
if (formData.username !== editingBuyer.username) {
|
||||
updateData.username = formData.username
|
||||
}
|
||||
if (formData.email !== editingBuyer.email) {
|
||||
updateData.email = formData.email
|
||||
}
|
||||
if (formData.password) {
|
||||
updateData.password = formData.password
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
setEditingBuyer(null)
|
||||
return
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/buyers/${editingBuyer.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updateData),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Buyer updated successfully')
|
||||
setEditingBuyer(null)
|
||||
fetchBuyers()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating buyer:', error)
|
||||
alert('Failed to update buyer')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Are you sure you want to delete this buyer? This will also delete all their sales.')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/buyers/${id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Buyer deleted successfully')
|
||||
fetchBuyers()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting buyer:', error)
|
||||
alert('Failed to delete buyer')
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg)'
|
||||
}}>
|
||||
<p style={{ color: 'var(--muted)' }}>Loading...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
background: 'var(--bg)',
|
||||
padding: '40px 20px'
|
||||
}}>
|
||||
<div className="container" style={{ maxWidth: '1200px', margin: '0 auto' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: '30px'
|
||||
}}>
|
||||
<h1>Buyer Management</h1>
|
||||
<button
|
||||
onClick={() => router.push('/admin')}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Back to Dashboard
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{buyers.length === 0 ? (
|
||||
<p style={{ color: 'var(--muted)' }}>No buyers found</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
|
||||
{buyers.map((buyer) => (
|
||||
<div
|
||||
key={buyer.id}
|
||||
className="drop-card"
|
||||
style={{
|
||||
background: editingBuyer?.id === buyer.id ? 'var(--bg-soft)' : 'var(--card)',
|
||||
padding: '20px'
|
||||
}}
|
||||
>
|
||||
{editingBuyer?.id === buyer.id ? (
|
||||
<div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Username</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.username}
|
||||
onChange={(e) => setFormData({ ...formData, username: 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' }}>Email</label>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: 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' }}>New Password (leave empty to keep current)</label>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="cta"
|
||||
style={{ padding: '8px 16px', fontSize: '14px' }}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setEditingBuyer(null)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
fontSize: '14px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<h3 style={{ marginBottom: '8px' }}>{buyer.username}</h3>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Email: {buyer.email}
|
||||
</p>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
ID: {buyer.id}
|
||||
</p>
|
||||
{buyer.created_at && (
|
||||
<p style={{ color: 'var(--muted)', fontSize: '12px' }}>
|
||||
Created: {new Date(buyer.created_at).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={() => handleEdit(buyer)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '6px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(buyer.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: '#dc2626',
|
||||
border: 'none',
|
||||
borderRadius: '6px',
|
||||
color: '#fff',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
846
app/admin/drops/page.tsx
Normal file
846
app/admin/drops/page.tsx
Normal file
@@ -0,0 +1,846 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
interface Drop {
|
||||
id: number
|
||||
item: string
|
||||
size: number
|
||||
fill: number
|
||||
unit: string
|
||||
ppu: number
|
||||
image_url: string | null
|
||||
created_at: string
|
||||
start_time: string | null
|
||||
}
|
||||
|
||||
interface Sale {
|
||||
id: number
|
||||
drop_id: number
|
||||
buyer_id: number
|
||||
size: number
|
||||
payment_id: string | null
|
||||
created_at: string
|
||||
buyer_username?: string
|
||||
buyer_email?: string
|
||||
buyer_fullname?: string
|
||||
buyer_address?: string
|
||||
buyer_phone?: string
|
||||
}
|
||||
|
||||
export default function DropsManagementPage() {
|
||||
const router = useRouter()
|
||||
const [drops, setDrops] = useState<Drop[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [authenticated, setAuthenticated] = useState(false)
|
||||
const [editingDrop, setEditingDrop] = useState<Drop | null>(null)
|
||||
const [creatingDrop, setCreatingDrop] = useState(false)
|
||||
const [showSalesPopup, setShowSalesPopup] = useState(false)
|
||||
const [salesForDrop, setSalesForDrop] = useState<Sale[]>([])
|
||||
const [selectedDropId, setSelectedDropId] = useState<number | null>(null)
|
||||
const [formData, setFormData] = useState({
|
||||
item: '',
|
||||
size: '',
|
||||
unit: 'g',
|
||||
ppu: '',
|
||||
imageUrl: '',
|
||||
startTime: '',
|
||||
})
|
||||
const [imageFile, setImageFile] = useState<File | null>(null)
|
||||
const [imagePreview, setImagePreview] = useState<string>('')
|
||||
const [uploadingImage, setUploadingImage] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// Check authentication
|
||||
fetch('/api/admin/check')
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.authenticated) {
|
||||
setAuthenticated(true)
|
||||
fetchDrops()
|
||||
} else {
|
||||
router.push('/admin/login')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
router.push('/admin/login')
|
||||
})
|
||||
}, [router])
|
||||
|
||||
const fetchDrops = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/drops')
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setDrops(Array.isArray(data) ? data : [])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching drops:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (drop: Drop) => {
|
||||
setEditingDrop(drop)
|
||||
setFormData({
|
||||
item: drop.item,
|
||||
size: drop.size.toString(),
|
||||
unit: drop.unit,
|
||||
ppu: drop.ppu.toString(),
|
||||
imageUrl: drop.image_url || '',
|
||||
startTime: drop.start_time ? new Date(drop.start_time).toISOString().slice(0, 16) : '',
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editingDrop) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/drops/${editingDrop.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
item: formData.item,
|
||||
size: parseInt(formData.size),
|
||||
unit: formData.unit,
|
||||
ppu: parseInt(formData.ppu),
|
||||
imageUrl: formData.imageUrl || null,
|
||||
startTime: formData.startTime || null,
|
||||
}),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Drop updated successfully')
|
||||
setEditingDrop(null)
|
||||
fetchDrops()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating drop:', error)
|
||||
alert('Failed to update drop')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Are you sure you want to delete this drop? This will also delete all related sales.')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/drops/${id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Drop deleted successfully')
|
||||
fetchDrops()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting drop:', error)
|
||||
alert('Failed to delete drop')
|
||||
}
|
||||
}
|
||||
|
||||
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 handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
try {
|
||||
let imageUrl = formData.imageUrl || null
|
||||
|
||||
// Upload image file if provided
|
||||
if (imageFile) {
|
||||
setUploadingImage(true)
|
||||
const uploadFormData = new FormData()
|
||||
uploadFormData.append('file', imageFile)
|
||||
|
||||
const uploadResponse = await fetch('/api/upload', {
|
||||
method: 'POST',
|
||||
body: uploadFormData,
|
||||
})
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
const error = await uploadResponse.json()
|
||||
alert(`Image upload failed: ${error.error}`)
|
||||
setUploadingImage(false)
|
||||
return
|
||||
}
|
||||
|
||||
const uploadData = await uploadResponse.json()
|
||||
imageUrl = uploadData.url
|
||||
setUploadingImage(false)
|
||||
}
|
||||
|
||||
const response = await fetch('/api/drops', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
item: formData.item,
|
||||
size: parseInt(formData.size),
|
||||
unit: formData.unit,
|
||||
ppu: parseInt(formData.ppu),
|
||||
imageUrl: imageUrl,
|
||||
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 {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating drop:', error)
|
||||
alert('Failed to create drop')
|
||||
} finally {
|
||||
setUploadingImage(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleViewSales = async (dropId: number) => {
|
||||
try {
|
||||
const response = await fetch(`/api/sales/drop/${dropId}`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setSalesForDrop(Array.isArray(data) ? data : [])
|
||||
setSelectedDropId(dropId)
|
||||
setShowSalesPopup(true)
|
||||
} else {
|
||||
alert('Failed to fetch sales')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching sales:', error)
|
||||
alert('Failed to fetch sales')
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressPercentage = (fill: number, size: number) => {
|
||||
return Math.min((fill / size) * 100, 100)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg)'
|
||||
}}>
|
||||
<p style={{ color: 'var(--muted)' }}>Loading...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
background: 'var(--bg)',
|
||||
padding: '40px 20px'
|
||||
}}>
|
||||
<div className="container" style={{ maxWidth: '1200px', margin: '0 auto' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: '30px'
|
||||
}}>
|
||||
<h1>Drops Management</h1>
|
||||
<div style={{ display: 'flex', gap: '12px' }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
setCreatingDrop(!creatingDrop)
|
||||
if (creatingDrop) {
|
||||
// Reset form when canceling
|
||||
setFormData({
|
||||
item: '',
|
||||
size: '',
|
||||
unit: 'g',
|
||||
ppu: '',
|
||||
imageUrl: '',
|
||||
startTime: '',
|
||||
})
|
||||
setImageFile(null)
|
||||
setImagePreview('')
|
||||
const fileInput = document.getElementById('imageFile') as HTMLInputElement
|
||||
if (fileInput) fileInput.value = ''
|
||||
}
|
||||
}}
|
||||
className="cta"
|
||||
style={{ padding: '10px 20px', fontSize: '14px' }}
|
||||
>
|
||||
{creatingDrop ? 'Cancel' : 'Create New Drop'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => router.push('/admin')}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Back to Dashboard
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{creatingDrop && (
|
||||
<div className="drop-card" style={{ marginBottom: '30px', padding: '20px' }}>
|
||||
<h2 style={{ marginTop: 0, marginBottom: '20px' }}>Create New Drop</h2>
|
||||
<form onSubmit={handleCreate}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Item Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.item}
|
||||
onChange={(e) => setFormData({ ...formData, item: e.target.value })}
|
||||
required
|
||||
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' }}>Size *</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.size}
|
||||
onChange={(e) => setFormData({ ...formData, size: e.target.value })}
|
||||
required
|
||||
min="1"
|
||||
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' }}>Unit *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.unit}
|
||||
onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
|
||||
required
|
||||
maxLength={12}
|
||||
placeholder="g, kg, ml, etc."
|
||||
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' }}>Price Per Unit (cents) *</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.ppu}
|
||||
onChange={(e) => setFormData({ ...formData, ppu: e.target.value })}
|
||||
required
|
||||
min="1"
|
||||
placeholder="2500 = 2.50 CHF"
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Product Image</label>
|
||||
<input
|
||||
type="file"
|
||||
id="imageFile"
|
||||
accept="image/jpeg,image/jpg,image/png,image/webp"
|
||||
onChange={handleImageChange}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
/>
|
||||
{imagePreview && (
|
||||
<div style={{ marginTop: '12px' }}>
|
||||
<img
|
||||
src={imagePreview}
|
||||
alt="Preview"
|
||||
style={{
|
||||
maxWidth: '200px',
|
||||
maxHeight: '200px',
|
||||
borderRadius: '8px',
|
||||
objectFit: 'cover'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<p style={{ marginTop: '8px', fontSize: '12px', color: 'var(--muted)' }}>
|
||||
Max file size: 5MB. Allowed formats: JPEG, PNG, WebP
|
||||
</p>
|
||||
<p style={{ marginTop: '4px', fontSize: '12px', color: 'var(--muted)' }}>
|
||||
Or enter an image URL:
|
||||
</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={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)',
|
||||
marginTop: '8px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Start Time</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={formData.startTime}
|
||||
onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="cta"
|
||||
disabled={uploadingImage}
|
||||
style={{ padding: '10px 20px', fontSize: '14px' }}
|
||||
>
|
||||
{uploadingImage ? 'Uploading image...' : 'Create Drop'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{drops.length === 0 ? (
|
||||
<p style={{ color: 'var(--muted)' }}>No drops found</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
|
||||
{drops.map((drop) => (
|
||||
<div
|
||||
key={drop.id}
|
||||
className="drop-card"
|
||||
style={{
|
||||
background: editingDrop?.id === drop.id ? 'var(--bg-soft)' : 'var(--card)',
|
||||
padding: '20px'
|
||||
}}
|
||||
>
|
||||
{editingDrop?.id === drop.id ? (
|
||||
<div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Item Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.item}
|
||||
onChange={(e) => setFormData({ ...formData, item: 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' }}>Size</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.size}
|
||||
onChange={(e) => setFormData({ ...formData, size: 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' }}>Unit</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.unit}
|
||||
onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
|
||||
maxLength={12}
|
||||
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' }}>Price Per Unit (cents)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.ppu}
|
||||
onChange={(e) => setFormData({ ...formData, ppu: 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' }}>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
|
||||
type="datetime-local"
|
||||
value={formData.startTime}
|
||||
onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="cta"
|
||||
style={{ padding: '8px 16px', fontSize: '14px' }}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setEditingDrop(null)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
fontSize: '14px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px' }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<h3 style={{ marginBottom: '8px' }}>{drop.item}</h3>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
ID: {drop.id} · Size: {drop.size}{drop.unit} · Price: {(drop.ppu / 1000).toFixed(2)} CHF / {drop.unit}
|
||||
</p>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '12px', marginBottom: '12px' }}>
|
||||
Created: {new Date(drop.created_at).toLocaleString()}
|
||||
{drop.start_time && ` · Start: ${new Date(drop.start_time).toLocaleString()}`}
|
||||
</p>
|
||||
|
||||
{/* Fill Bar */}
|
||||
<div className="progress" style={{ marginBottom: '8px' }}>
|
||||
<span style={{ width: `${getProgressPercentage(drop.fill, drop.size)}%` }}></span>
|
||||
</div>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '12px' }}>
|
||||
{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'
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
<button
|
||||
onClick={() => handleViewSales(drop.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '6px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer',
|
||||
whiteSpace: 'nowrap'
|
||||
}}
|
||||
>
|
||||
View Sales
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleEdit(drop)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '6px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(drop.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: '#dc2626',
|
||||
border: 'none',
|
||||
borderRadius: '6px',
|
||||
color: '#fff',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sales Popup */}
|
||||
{showSalesPopup && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0, 0, 0, 0.7)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
padding: '20px',
|
||||
}}
|
||||
onClick={() => setShowSalesPopup(false)}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--card)',
|
||||
borderRadius: '16px',
|
||||
padding: '32px',
|
||||
maxWidth: '800px',
|
||||
width: '100%',
|
||||
maxHeight: '80vh',
|
||||
overflow: 'auto',
|
||||
boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
|
||||
<h2 style={{ margin: 0 }}>Sales for Drop #{selectedDropId}</h2>
|
||||
<button
|
||||
onClick={() => setShowSalesPopup(false)}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: 'var(--text)',
|
||||
fontSize: '24px',
|
||||
cursor: 'pointer',
|
||||
padding: '0',
|
||||
width: '32px',
|
||||
height: '32px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center'
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{salesForDrop.length === 0 ? (
|
||||
<p style={{ color: 'var(--muted)', textAlign: 'center', padding: '40px' }}>
|
||||
No sales found for this drop
|
||||
</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
|
||||
{salesForDrop.map((sale) => (
|
||||
<div
|
||||
key={sale.id}
|
||||
style={{
|
||||
background: 'var(--bg-soft)',
|
||||
padding: '16px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<p style={{ margin: 0, marginBottom: '4px', fontWeight: '600' }}>
|
||||
Sale #{sale.id}
|
||||
</p>
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Buyer: {sale.buyer_username || `#${sale.buyer_id}`} ({sale.buyer_email || 'N/A'})
|
||||
</p>
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Size: {sale.size}g
|
||||
</p>
|
||||
{(sale.buyer_fullname || sale.buyer_address || sale.buyer_phone) && (
|
||||
<div style={{
|
||||
background: 'var(--card)',
|
||||
padding: '10px',
|
||||
borderRadius: '6px',
|
||||
marginTop: '8px',
|
||||
marginBottom: '8px'
|
||||
}}>
|
||||
<p style={{ margin: 0, color: 'var(--text)', fontSize: '12px', fontWeight: '600', marginBottom: '4px' }}>
|
||||
Delivery Information:
|
||||
</p>
|
||||
{sale.buyer_fullname && (
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '12px', marginBottom: '2px' }}>
|
||||
Name: {sale.buyer_fullname}
|
||||
</p>
|
||||
)}
|
||||
{sale.buyer_address && (
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '12px', marginBottom: '2px' }}>
|
||||
Address: {sale.buyer_address}
|
||||
</p>
|
||||
)}
|
||||
{sale.buyer_phone && (
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '12px', marginBottom: '2px' }}>
|
||||
Phone: {sale.buyer_phone}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p style={{ margin: 0, color: 'var(--muted)', fontSize: '12px' }}>
|
||||
{new Date(sale.created_at).toLocaleString()}
|
||||
{sale.payment_id && ` · Payment ID: ${sale.payment_id}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
116
app/admin/login/page.tsx
Normal file
116
app/admin/login/page.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
export default function AdminLoginPage() {
|
||||
const router = useRouter()
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// Check if already authenticated
|
||||
fetch('/api/admin/check')
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.authenticated) {
|
||||
router.push('/admin')
|
||||
}
|
||||
})
|
||||
}, [router])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ password }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (response.ok) {
|
||||
router.push('/admin')
|
||||
} else {
|
||||
setError(data.error || 'Invalid password')
|
||||
}
|
||||
} catch (error) {
|
||||
setError('Failed to login. Please try again.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg)',
|
||||
padding: '20px'
|
||||
}}>
|
||||
<div style={{
|
||||
background: 'var(--card)',
|
||||
padding: '40px',
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
|
||||
maxWidth: '400px',
|
||||
width: '100%'
|
||||
}}>
|
||||
<h1 style={{ marginBottom: '24px', textAlign: 'center' }}>Admin Login</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: '20px' }}>
|
||||
<label htmlFor="password" style={{ display: 'block', marginBottom: '8px' }}>
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: '#fee2e2',
|
||||
color: '#dc2626',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '20px',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="cta"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{loading ? 'Logging in...' : 'Login'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
384
app/admin/sales/page.tsx
Normal file
384
app/admin/sales/page.tsx
Normal file
@@ -0,0 +1,384 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
interface Sale {
|
||||
id: number
|
||||
drop_id: number
|
||||
buyer_id: number
|
||||
size: number
|
||||
payment_id: string | null
|
||||
created_at: string
|
||||
drop_item?: string
|
||||
drop_unit?: string
|
||||
drop_ppu?: number
|
||||
buyer_username?: string
|
||||
buyer_email?: string
|
||||
buyer_fullname?: string
|
||||
buyer_address?: string
|
||||
buyer_phone?: string
|
||||
}
|
||||
|
||||
export default function SalesManagementPage() {
|
||||
const router = useRouter()
|
||||
const [sales, setSales] = useState<Sale[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [authenticated, setAuthenticated] = useState(false)
|
||||
const [editingSale, setEditingSale] = useState<Sale | null>(null)
|
||||
const [formData, setFormData] = useState({
|
||||
drop_id: '',
|
||||
buyer_id: '',
|
||||
size: '',
|
||||
payment_id: '',
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// Check authentication
|
||||
fetch('/api/admin/check')
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.authenticated) {
|
||||
setAuthenticated(true)
|
||||
fetchSales()
|
||||
} else {
|
||||
router.push('/admin/login')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
router.push('/admin/login')
|
||||
})
|
||||
}, [router])
|
||||
|
||||
const fetchSales = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/sales/list')
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setSales(Array.isArray(data) ? data : [])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching sales:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (sale: Sale) => {
|
||||
setEditingSale(sale)
|
||||
setFormData({
|
||||
drop_id: sale.drop_id.toString(),
|
||||
buyer_id: sale.buyer_id.toString(),
|
||||
size: sale.size.toString(),
|
||||
payment_id: sale.payment_id || '',
|
||||
})
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editingSale) return
|
||||
|
||||
try {
|
||||
const updateData: any = {}
|
||||
if (parseInt(formData.drop_id) !== editingSale.drop_id) {
|
||||
updateData.drop_id = parseInt(formData.drop_id)
|
||||
}
|
||||
if (parseInt(formData.buyer_id) !== editingSale.buyer_id) {
|
||||
updateData.buyer_id = parseInt(formData.buyer_id)
|
||||
}
|
||||
if (parseInt(formData.size) !== editingSale.size) {
|
||||
updateData.size = parseInt(formData.size)
|
||||
}
|
||||
if (formData.payment_id !== (editingSale.payment_id || '')) {
|
||||
updateData.payment_id = formData.payment_id || null
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
setEditingSale(null)
|
||||
return
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/sales/${editingSale.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updateData),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Sale updated successfully')
|
||||
setEditingSale(null)
|
||||
fetchSales()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating sale:', error)
|
||||
alert('Failed to update sale')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Are you sure you want to delete this sale?')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/sales/${id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
alert('Sale deleted successfully')
|
||||
fetchSales()
|
||||
} else {
|
||||
const error = await response.json()
|
||||
alert(`Error: ${error.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting sale:', error)
|
||||
alert('Failed to delete sale')
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'var(--bg)'
|
||||
}}>
|
||||
<p style={{ color: 'var(--muted)' }}>Loading...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
background: 'var(--bg)',
|
||||
padding: '40px 20px'
|
||||
}}>
|
||||
<div className="container" style={{ maxWidth: '1200px', margin: '0 auto' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: '30px'
|
||||
}}>
|
||||
<h1>Sales Management</h1>
|
||||
<button
|
||||
onClick={() => router.push('/admin')}
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
Back to Dashboard
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{sales.length === 0 ? (
|
||||
<p style={{ color: 'var(--muted)' }}>No sales found</p>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
|
||||
{sales.map((sale) => (
|
||||
<div
|
||||
key={sale.id}
|
||||
className="drop-card"
|
||||
style={{
|
||||
background: editingSale?.id === sale.id ? 'var(--bg-soft)' : 'var(--card)',
|
||||
padding: '20px'
|
||||
}}
|
||||
>
|
||||
{editingSale?.id === sale.id ? (
|
||||
<div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
|
||||
<div>
|
||||
<label style={{ display: 'block', marginBottom: '8px' }}>Drop ID</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.drop_id}
|
||||
onChange={(e) => setFormData({ ...formData, drop_id: 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' }}>Buyer ID</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.buyer_id}
|
||||
onChange={(e) => setFormData({ ...formData, buyer_id: 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' }}>Size (grams)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.size}
|
||||
onChange={(e) => setFormData({ ...formData, size: 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' }}>Payment ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.payment_id}
|
||||
onChange={(e) => setFormData({ ...formData, payment_id: e.target.value })}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg-soft)',
|
||||
color: 'var(--text)'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
className="cta"
|
||||
style={{ padding: '8px 16px', fontSize: '14px' }}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setEditingSale(null)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
fontSize: '14px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<h3 style={{ marginBottom: '8px' }}>Sale #{sale.id}</h3>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Drop: {sale.drop_item || `#${sale.drop_id}`} · Size: {sale.size}g
|
||||
</p>
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Buyer: {sale.buyer_username || `#${sale.buyer_id}`} ({sale.buyer_email || 'N/A'})
|
||||
</p>
|
||||
{(sale.buyer_fullname || sale.buyer_address || sale.buyer_phone) && (
|
||||
<div style={{
|
||||
background: 'var(--bg-soft)',
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
marginTop: '8px',
|
||||
marginBottom: '8px'
|
||||
}}>
|
||||
<p style={{ color: 'var(--text)', fontSize: '13px', fontWeight: '600', marginBottom: '6px' }}>
|
||||
Delivery Information:
|
||||
</p>
|
||||
{sale.buyer_fullname && (
|
||||
<p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
|
||||
Name: {sale.buyer_fullname}
|
||||
</p>
|
||||
)}
|
||||
{sale.buyer_address && (
|
||||
<p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
|
||||
Address: {sale.buyer_address}
|
||||
</p>
|
||||
)}
|
||||
{sale.buyer_phone && (
|
||||
<p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
|
||||
Phone: {sale.buyer_phone}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{sale.drop_ppu && (
|
||||
<p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
|
||||
Price: {((sale.drop_ppu / 1000) * sale.size).toFixed(2)} CHF
|
||||
</p>
|
||||
)}
|
||||
<p style={{ color: 'var(--muted)', fontSize: '12px' }}>
|
||||
Created: {new Date(sale.created_at).toLocaleString()}
|
||||
{sale.payment_id && ` · Payment: ${sale.payment_id}`}
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<button
|
||||
onClick={() => handleEdit(sale)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '6px',
|
||||
color: 'var(--text)',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(sale.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
background: '#dc2626',
|
||||
border: 'none',
|
||||
borderRadius: '6px',
|
||||
color: '#fff',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
12
app/api/admin/check/route.ts
Normal file
12
app/api/admin/check/route.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { isAdminAuthenticated } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authenticated = await isAdminAuthenticated()
|
||||
return NextResponse.json({ authenticated })
|
||||
} catch (error) {
|
||||
return NextResponse.json({ authenticated: false })
|
||||
}
|
||||
}
|
||||
|
||||
33
app/api/admin/login/route.ts
Normal file
33
app/api/admin/login/route.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { verifyAdminPassword, setAdminSession } from '@/lib/admin-auth'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { password } = body
|
||||
|
||||
if (!password) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Password is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (verifyAdminPassword(password)) {
|
||||
await setAdminSession()
|
||||
return NextResponse.json({ success: true })
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid password' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during admin login:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to process login' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
16
app/api/admin/logout/route.ts
Normal file
16
app/api/admin/logout/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { clearAdminSession } from '@/lib/admin-auth'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
await clearAdminSession()
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error during admin logout:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to process logout' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
215
app/api/drops/[id]/route.ts
Normal file
215
app/api/drops/[id]/route.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/drops/[id] - Get a specific drop
|
||||
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 drop ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const [rows] = await pool.execute(
|
||||
'SELECT * FROM drops WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
|
||||
const drops = rows as any[]
|
||||
if (drops.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Drop not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
const drop = drops[0]
|
||||
|
||||
// Calculate fill from sales
|
||||
const [salesRows] = await pool.execute(
|
||||
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
|
||||
[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,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error fetching drop:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch drop' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/drops/[id] - Update a drop
|
||||
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 drop ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { item, size, unit, ppu, imageUrl, startTime } = body
|
||||
|
||||
// Check if drop exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM drops WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Drop not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Build update query dynamically
|
||||
const updates: string[] = []
|
||||
const values: any[] = []
|
||||
|
||||
if (item !== undefined) {
|
||||
updates.push('item = ?')
|
||||
values.push(item)
|
||||
}
|
||||
|
||||
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 (unit !== undefined) {
|
||||
updates.push('unit = ?')
|
||||
values.push(unit)
|
||||
}
|
||||
|
||||
if (ppu !== undefined) {
|
||||
if (ppu <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Price per unit must be greater than 0' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
updates.push('ppu = ?')
|
||||
values.push(ppu)
|
||||
}
|
||||
|
||||
if (imageUrl !== undefined) {
|
||||
updates.push('image_url = ?')
|
||||
values.push(imageUrl || null)
|
||||
}
|
||||
|
||||
if (startTime !== undefined) {
|
||||
updates.push('start_time = ?')
|
||||
values.push(startTime || null)
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No fields to update' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
values.push(id)
|
||||
const query = `UPDATE drops SET ${updates.join(', ')} WHERE id = ?`
|
||||
await pool.execute(query, values)
|
||||
|
||||
// Fetch updated drop
|
||||
const [rows] = await pool.execute('SELECT * FROM drops WHERE id = ?', [id])
|
||||
const drop = rows[0] as any
|
||||
|
||||
// Calculate fill
|
||||
const [salesRows] = await pool.execute(
|
||||
'SELECT COALESCE(SUM(size), 0) as total_fill FROM sales WHERE drop_id = ?',
|
||||
[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,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error updating drop:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update drop' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/drops/[id] - Delete a drop
|
||||
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 drop ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check if drop exists
|
||||
const [existingRows] = await pool.execute(
|
||||
'SELECT id FROM drops WHERE id = ?',
|
||||
[id]
|
||||
)
|
||||
const existing = existingRows as any[]
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Drop not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Delete drop (cascade will handle related sales)
|
||||
await pool.execute('DELETE FROM drops WHERE id = ?', [id])
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Error deleting drop:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to delete drop' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
76
app/api/notifications/subscribe/route.ts
Normal file
76
app/api/notifications/subscribe/route.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { cookies } from 'next/headers'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// POST /api/notifications/subscribe - Subscribe to notifications
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Get buyer_id from session cookie if logged in
|
||||
const cookieStore = await cookies()
|
||||
const buyerIdCookie = cookieStore.get('buyer_id')?.value
|
||||
const buyer_id = buyerIdCookie ? parseInt(buyerIdCookie, 10) : null
|
||||
|
||||
const body = await request.json()
|
||||
const { email, phone } = body
|
||||
|
||||
// Validate that at least one field is provided
|
||||
if (!email && !phone) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Email or phone number is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Validate email format if provided
|
||||
if (email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailRegex.test(email)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid email format' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate phone format if provided (basic validation)
|
||||
if (phone) {
|
||||
const phoneRegex = /^[+]?[\d\s\-()]{10,15}$/
|
||||
if (!phoneRegex.test(phone)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid phone number format' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert email subscription if provided
|
||||
// Using INSERT IGNORE to handle duplicate addresses (address is now primary key)
|
||||
if (email) {
|
||||
await pool.execute(
|
||||
'INSERT IGNORE INTO notification_subscribers (buyer_id, type, address) VALUES (?, ?, ?)',
|
||||
[buyer_id, 'email', email.trim()]
|
||||
)
|
||||
}
|
||||
|
||||
// Insert phone subscription if provided
|
||||
// Using INSERT IGNORE to handle duplicate addresses (address is now primary key)
|
||||
if (phone) {
|
||||
await pool.execute(
|
||||
'INSERT IGNORE INTO notification_subscribers (buyer_id, type, address) VALUES (?, ?, ?)',
|
||||
[buyer_id, 'phone', phone.trim()]
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: true, message: 'Successfully subscribed to notifications' },
|
||||
{ status: 200 }
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Error subscribing to notifications:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to subscribe to notifications' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
51
app/api/sales/drop/[dropId]/route.ts
Normal file
51
app/api/sales/drop/[dropId]/route.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
|
||||
// GET /api/sales/drop/[dropId] - Get all sales for a specific drop
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { dropId: string } }
|
||||
) {
|
||||
try {
|
||||
const dropId = parseInt(params.dropId, 10)
|
||||
if (isNaN(dropId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid drop 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,
|
||||
bd.fullname as buyer_fullname,
|
||||
bd.address as buyer_address,
|
||||
bd.phone as buyer_phone
|
||||
FROM sales s
|
||||
LEFT JOIN drops d ON s.drop_id = d.id
|
||||
LEFT JOIN buyers b ON s.buyer_id = b.id
|
||||
LEFT JOIN buyer_data bd ON s.buyer_data_id = bd.id
|
||||
WHERE s.drop_id = ?
|
||||
ORDER BY s.created_at DESC`,
|
||||
[dropId]
|
||||
)
|
||||
return NextResponse.json(rows)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sales for drop:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch sales' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,10 +16,14 @@ export async function GET(request: NextRequest) {
|
||||
d.unit as drop_unit,
|
||||
d.ppu as drop_ppu,
|
||||
b.username as buyer_username,
|
||||
b.email as buyer_email
|
||||
b.email as buyer_email,
|
||||
bd.fullname as buyer_fullname,
|
||||
bd.address as buyer_address,
|
||||
bd.phone as buyer_phone
|
||||
FROM sales s
|
||||
LEFT JOIN drops d ON s.drop_id = d.id
|
||||
LEFT JOIN buyers b ON s.buyer_id = b.id
|
||||
LEFT JOIN buyer_data bd ON s.buyer_data_id = bd.id
|
||||
ORDER BY s.created_at DESC`
|
||||
)
|
||||
return NextResponse.json(rows)
|
||||
|
||||
@@ -5,34 +5,139 @@ import { useState } from 'react'
|
||||
export default function Signup() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [whatsapp, setWhatsapp] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [showPopup, setShowPopup] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// Handle form submission
|
||||
console.log('Form submitted', { email, whatsapp })
|
||||
setError('')
|
||||
|
||||
// Validate that at least one field is filled
|
||||
if (!email.trim() && !whatsapp.trim()) {
|
||||
setError('Please enter at least an email or phone number')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/notifications/subscribe', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: email.trim(),
|
||||
phone: whatsapp.trim(),
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || 'Failed to subscribe')
|
||||
}
|
||||
|
||||
// Show success popup
|
||||
setShowPopup(true)
|
||||
|
||||
// Clear form
|
||||
setEmail('')
|
||||
setWhatsapp('')
|
||||
|
||||
// Hide popup after 5 seconds
|
||||
setTimeout(() => {
|
||||
setShowPopup(false)
|
||||
}, 5000)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An error occurred')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="signup">
|
||||
<h2>Drop Notifications</h2>
|
||||
<p>Receive updates about new drops via email or WhatsApp.</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="E-Mail"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
<>
|
||||
<div className="signup">
|
||||
<h2>Drop Notifications</h2>
|
||||
<p>Receive updates about new drops via email or WhatsApp.</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="E-Mail"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={loading}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="WhatsApp Number"
|
||||
value={whatsapp}
|
||||
onChange={(e) => setWhatsapp(e.target.value)}
|
||||
disabled={loading}
|
||||
/>
|
||||
<br />
|
||||
{error && <div style={{ color: '#ff4444', marginTop: '10px', fontSize: '14px' }}>{error}</div>}
|
||||
<button type="submit" disabled={loading}>
|
||||
{loading ? 'Subscribing...' : 'Get Notified'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{showPopup && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
background: '#1c1c1c',
|
||||
border: '1px solid #2a2a2a',
|
||||
borderRadius: '16px',
|
||||
padding: '30px 40px',
|
||||
zIndex: 1000,
|
||||
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.5)',
|
||||
maxWidth: '400px',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<p style={{ margin: 0, fontSize: '16px', color: '#eaeaea' }}>
|
||||
You will receive a notification as soon as a new drop drops.
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShowPopup(false)}
|
||||
style={{
|
||||
marginTop: '20px',
|
||||
padding: '10px 20px',
|
||||
background: '#3ddc84',
|
||||
color: '#000',
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
}}
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showPopup && (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0, 0, 0, 0.7)',
|
||||
zIndex: 999,
|
||||
}}
|
||||
onClick={() => setShowPopup(false)}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="WhatsApp Number"
|
||||
value={whatsapp}
|
||||
onChange={(e) => setWhatsapp(e.target.value)}
|
||||
/>
|
||||
<br />
|
||||
<button type="submit">Get Notified</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user