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