-
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { ArrowLeft, Download, ExternalLink, Star, Trash2 } from 'lucide-react'
|
||||
import { useApi } from '../../hooks/useApi'
|
||||
import api, { errorMessage, fieldErrors } from '../../services/api'
|
||||
import { ErrorBlock, LoadingBlock, useFeedback } from '../components/feedback'
|
||||
import ImageUploader from '../components/ImageUploader'
|
||||
import { aInput, AField, Btn, Card, PageHeader, Pill, Toggle } from '../components/kit'
|
||||
|
||||
const EMPTY = { title: '', category: 'residential', location: '', capacity_kw: '', installation_date: '', description: '', status: 'completed', is_published: false }
|
||||
|
||||
function toForm(p) {
|
||||
return {
|
||||
title: p.title,
|
||||
category: p.category,
|
||||
location: p.location || '',
|
||||
capacity_kw: p.capacity_kw ?? '',
|
||||
installation_date: p.installation_date || '',
|
||||
description: p.description || '',
|
||||
status: p.status,
|
||||
is_published: p.is_published,
|
||||
}
|
||||
}
|
||||
|
||||
function toPayload(f) {
|
||||
return {
|
||||
...f,
|
||||
location: f.location.trim() || null,
|
||||
description: f.description.trim() || null,
|
||||
capacity_kw: f.capacity_kw === '' ? null : Number(f.capacity_kw),
|
||||
installation_date: f.installation_date || null,
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadOriginal(img) {
|
||||
const res = await api.get(img.original_download_path.replace(/^\/api/, ''), { responseType: 'blob' })
|
||||
const url = URL.createObjectURL(res.data)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = img.original_filename
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 2000)
|
||||
}
|
||||
|
||||
function Gallery({ project, onChange }) {
|
||||
const { toast, confirm } = useFeedback()
|
||||
const [busyId, setBusyId] = useState(null)
|
||||
const [captions, setCaptions] = useState({})
|
||||
|
||||
const act = async (id, fn, okMsg) => {
|
||||
setBusyId(id)
|
||||
try {
|
||||
const r = await fn()
|
||||
if (r?.data?.images) onChange(r.data)
|
||||
if (okMsg) toast(okMsg)
|
||||
return true
|
||||
} catch (e) {
|
||||
toast(errorMessage(e), 'error')
|
||||
return false
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async (img) => {
|
||||
const ok = await confirm({ title: 'Delete photo?', message: `"${img.original_filename}" and its watermarked copy will be permanently deleted.`, confirmLabel: 'Delete photo', danger: true })
|
||||
if (!ok) return
|
||||
const done = await act(img.id, () => api.delete(`/admin/project-images/${img.id}`), 'Photo deleted')
|
||||
if (done) {
|
||||
const r = await api.get(`/admin/projects/${project.id}`)
|
||||
onChange(r.data)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-[16px] font-bold text-navy">Photos ({project.images.length})</h2>
|
||||
<span className="text-[12px] text-slate">The public gallery shows watermarked copies only.</span>
|
||||
</div>
|
||||
<ImageUploader
|
||||
url={`/admin/projects/${project.id}/images`}
|
||||
onUploaded={(res) => {
|
||||
onChange(res.project)
|
||||
toast(`${res.uploaded.length} photo${res.uploaded.length === 1 ? '' : 's'} uploaded and watermarked`)
|
||||
}}
|
||||
/>
|
||||
{project.images.length > 0 && (
|
||||
<ul className="mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{project.images.map((img) => (
|
||||
<li key={img.id} className={`overflow-hidden rounded-2xl ring-1 ${img.is_featured ? 'ring-2 ring-yellow-badge' : 'ring-line'} ${busyId === img.id ? 'opacity-50' : ''}`}>
|
||||
<a href={img.url} target="_blank" rel="noopener" className="relative block aspect-[4/3] bg-surface" title="Open watermarked image">
|
||||
<img src={img.thumbnail_url} alt={img.caption || img.original_filename} className="size-full object-cover" loading="lazy" />
|
||||
{img.is_featured && <span className="absolute top-2 left-2 inline-flex items-center gap-1 rounded-full bg-yellow-badge px-2 py-0.5 text-[11px] font-bold text-black"><Star className="size-3" fill="currentColor" /> Featured</span>}
|
||||
</a>
|
||||
<div className="space-y-2 p-3">
|
||||
<p className="truncate text-[12px] text-slate" title={img.original_filename}>
|
||||
{img.original_filename} · {img.width}×{img.height} · {(img.file_size / 1024 / 1024).toFixed(1)} MB
|
||||
</p>
|
||||
<input
|
||||
className={`${aInput} py-1.5 text-[13px]`}
|
||||
placeholder="Caption (optional)"
|
||||
value={captions[img.id] ?? img.caption ?? ''}
|
||||
onChange={(e) => setCaptions((c) => ({ ...c, [img.id]: e.target.value }))}
|
||||
onBlur={() => {
|
||||
const v = captions[img.id]
|
||||
if (v !== undefined && v !== (img.caption ?? '')) act(img.id, () => api.patch(`/admin/project-images/${img.id}`, { caption: v.trim() || null }), 'Caption saved')
|
||||
}}
|
||||
maxLength={300}
|
||||
aria-label="Caption"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{!img.is_featured && (
|
||||
<Btn variant="ghost" className="h-8 px-3 text-[12px]" onClick={() => act(img.id, () => api.patch(`/admin/project-images/${img.id}`, { is_featured: true }), 'Featured image set')}>
|
||||
<Star className="size-3.5" /> Set featured
|
||||
</Btn>
|
||||
)}
|
||||
<Btn variant="ghost" className="h-8 px-3 text-[12px]" onClick={() => downloadOriginal(img).catch((e) => toast(errorMessage(e), 'error'))} title="Download original (no watermark)">
|
||||
<Download className="size-3.5" /> Original
|
||||
</Btn>
|
||||
<Btn variant="danger" className="h-8 px-3 text-[12px]" onClick={() => remove(img)}>
|
||||
<Trash2 className="size-3.5" /> Delete
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ProjectEditorPage() {
|
||||
const { id } = useParams()
|
||||
const isNew = !id
|
||||
const navigate = useNavigate()
|
||||
const { toast, confirm } = useFeedback()
|
||||
const { data, loading, error, reload, setData } = useApi(`/admin/projects/${id}`, { enabled: !isNew })
|
||||
const [form, setForm] = useState(EMPTY)
|
||||
const [errors, setErrors] = useState({})
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Fill the form once per loaded project (photo changes must not wipe unsaved edits).
|
||||
const loadedId = data?.id
|
||||
useEffect(() => {
|
||||
if (data) setForm(toForm(data))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [loadedId])
|
||||
|
||||
const set = (k) => (e) => {
|
||||
setForm((f) => ({ ...f, [k]: e?.target ? e.target.value : e }))
|
||||
setErrors((er) => ({ ...er, [k]: undefined }))
|
||||
}
|
||||
|
||||
const save = async (ev) => {
|
||||
ev?.preventDefault()
|
||||
const e = {}
|
||||
if (form.title.trim().length < 2) e.title = 'Enter a project title'
|
||||
if (form.capacity_kw !== '' && !(Number(form.capacity_kw) > 0)) e.capacity_kw = 'Capacity must be a positive number'
|
||||
setErrors(e)
|
||||
if (Object.keys(e).length) return
|
||||
setSaving(true)
|
||||
try {
|
||||
if (isNew) {
|
||||
const r = await api.post('/admin/projects', toPayload(form))
|
||||
toast('Project created — now add photos')
|
||||
navigate(`/admin/projects/${r.data.id}`, { replace: true })
|
||||
} else {
|
||||
const r = await api.put(`/admin/projects/${id}`, toPayload(form))
|
||||
setData(r.data)
|
||||
setForm(toForm(r.data))
|
||||
toast('Project saved')
|
||||
}
|
||||
} catch (err) {
|
||||
setErrors(fieldErrors(err))
|
||||
toast(errorMessage(err), 'error')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async () => {
|
||||
const ok = await confirm({ title: 'Delete project?', message: `"${data.title}" and all ${data.images.length} photos will be permanently deleted.`, confirmLabel: 'Delete project', danger: true })
|
||||
if (!ok) return
|
||||
try {
|
||||
await api.delete(`/admin/projects/${id}`)
|
||||
toast('Project deleted')
|
||||
navigate('/admin/projects', { replace: true })
|
||||
} catch (err) {
|
||||
toast(errorMessage(err), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
if (!isNew && error) return <ErrorBlock message={error} onRetry={reload} />
|
||||
if (!isNew && (!data || String(data.id) !== String(id))) return <LoadingBlock />
|
||||
|
||||
return (
|
||||
<>
|
||||
<Link to="/admin/projects" className="mb-4 inline-flex items-center gap-1.5 text-[14px] font-semibold text-brand hover:underline"><ArrowLeft className="size-4" /> Projects</Link>
|
||||
<PageHeader
|
||||
title={isNew ? 'New project' : data.title}
|
||||
subtitle={isNew ? 'Save the details first, then upload photos.' : <span className="inline-flex items-center gap-2"><Pill on={data.is_published}>{data.is_published ? 'Published' : 'Draft'}</Pill> /{data.slug}</span>}
|
||||
actions={
|
||||
!isNew && (
|
||||
<>
|
||||
{data.is_published && (
|
||||
<a href={`/projects/${data.slug}`} target="_blank" rel="noopener"><Btn variant="ghost" as="span"><ExternalLink className="size-4" /> View on site</Btn></a>
|
||||
)}
|
||||
<Btn variant="danger" onClick={remove}><Trash2 className="size-4" /> Delete</Btn>
|
||||
</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-[420px_1fr]">
|
||||
<Card className="h-fit">
|
||||
<form onSubmit={save} noValidate className="space-y-4">
|
||||
<AField label="Title *" error={errors.title}>
|
||||
<input className={aInput} value={form.title} onChange={set('title')} maxLength={200} aria-invalid={!!errors.title} />
|
||||
</AField>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<AField label="Category" error={errors.category}>
|
||||
<select className={aInput} value={form.category} onChange={set('category')}>
|
||||
<option value="residential">Residential</option>
|
||||
<option value="commercial">Commercial</option>
|
||||
</select>
|
||||
</AField>
|
||||
<AField label="Status">
|
||||
<select className={aInput} value={form.status} onChange={set('status')}>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="ongoing">Ongoing</option>
|
||||
</select>
|
||||
</AField>
|
||||
</div>
|
||||
<AField label="Location" error={errors.location}>
|
||||
<input className={aInput} value={form.location} onChange={set('location')} placeholder="e.g. Patia, Bhubaneswar" maxLength={200} />
|
||||
</AField>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<AField label="Capacity (kW)" error={errors.capacity_kw}>
|
||||
<input className={aInput} type="number" min="0" step="0.1" value={form.capacity_kw} onChange={set('capacity_kw')} aria-invalid={!!errors.capacity_kw} />
|
||||
</AField>
|
||||
<AField label="Installation date" error={errors.installation_date}>
|
||||
<input className={aInput} type="date" value={form.installation_date} onChange={set('installation_date')} />
|
||||
</AField>
|
||||
</div>
|
||||
<AField label="Description" error={errors.description}>
|
||||
<textarea className={`${aInput} min-h-32`} value={form.description} onChange={set('description')} maxLength={10000} />
|
||||
</AField>
|
||||
<Toggle checked={form.is_published} onChange={set('is_published')} label="Published on website" />
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Btn type="submit" busy={saving}>{isNew ? 'Create project' : 'Save changes'}</Btn>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
{isNew ? (
|
||||
<Card className="grid place-items-center text-center text-[14px] text-slate">
|
||||
<p className="max-w-sm py-10">Create the project first — the photo uploader will appear here.</p>
|
||||
</Card>
|
||||
) : (
|
||||
<Gallery project={data} onChange={setData} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user