feat: enable project catalog management
This commit is contained in:
@@ -1,31 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRef, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useToast } from '@/contexts/ToastContext';
|
||||
|
||||
type UploadedImage = {
|
||||
url: string;
|
||||
path: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
const CATEGORY_OPTIONS = [
|
||||
{ value: 'Engenharia Veicular', label: 'Engenharia Veicular' },
|
||||
{ value: 'Projetos Mecânicos', label: 'Projetos Mecânicos' },
|
||||
{ value: 'Laudos e Inspeções', label: 'Laudos e Inspeções' },
|
||||
{ value: 'Segurança do Trabalho', label: 'Segurança do Trabalho' },
|
||||
];
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'Concluído', label: 'Concluído' },
|
||||
{ value: 'Em andamento', label: 'Em andamento' },
|
||||
{ value: 'Rascunho', label: 'Rascunho' },
|
||||
];
|
||||
|
||||
export default function NewProject() {
|
||||
const router = useRouter();
|
||||
const { success, error } = useToast();
|
||||
const coverInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const galleryInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
category: '',
|
||||
client: '',
|
||||
status: 'active',
|
||||
status: 'Concluído',
|
||||
description: '',
|
||||
date: ''
|
||||
date: '',
|
||||
featured: false,
|
||||
});
|
||||
const [coverImage, setCoverImage] = useState<UploadedImage | null>(null);
|
||||
const [galleryImages, setGalleryImages] = useState<UploadedImage[]>([]);
|
||||
const [uploadingCover, setUploadingCover] = useState(false);
|
||||
const [uploadingGallery, setUploadingGallery] = useState(false);
|
||||
|
||||
const isSaving = loading || uploadingCover || uploadingGallery;
|
||||
|
||||
const uploadFile = async (file: File): Promise<UploadedImage | null> => {
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
error('Arquivo maior que 2MB. Escolha uma imagem menor.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const supportedTypes = ['image/png', 'image/jpeg', 'image/webp'];
|
||||
if (!supportedTypes.includes(file.type)) {
|
||||
error('Formato inválido. Utilize PNG, JPG ou WEBP.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
|
||||
const response = await fetch('/api/upload', {
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
throw new Error(data?.error || 'Erro ao enviar imagem');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return {
|
||||
url: data.url,
|
||||
path: data.path,
|
||||
name: file.name,
|
||||
};
|
||||
};
|
||||
|
||||
const handleCoverSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setUploadingCover(true);
|
||||
try {
|
||||
const uploaded = await uploadFile(file);
|
||||
if (uploaded) {
|
||||
setCoverImage(uploaded);
|
||||
success('Imagem de capa carregada.');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Erro ao enviar imagem de capa:', err);
|
||||
error(err instanceof Error ? err.message : 'Falha ao enviar imagem de capa.');
|
||||
} finally {
|
||||
setUploadingCover(false);
|
||||
event.target.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleGallerySelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(event.target.files ?? []);
|
||||
if (files.length === 0) return;
|
||||
|
||||
if (galleryImages.length + files.length > 8) {
|
||||
error('Limite de 8 imagens atingido. Remova algumas antes de adicionar novas.');
|
||||
event.target.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadingGallery(true);
|
||||
try {
|
||||
for (const file of files) {
|
||||
const uploaded = await uploadFile(file);
|
||||
if (uploaded) {
|
||||
setGalleryImages((prev) => [...prev, uploaded]);
|
||||
}
|
||||
}
|
||||
success('Galeria atualizada.');
|
||||
} catch (err) {
|
||||
console.error('Erro ao enviar imagem da galeria:', err);
|
||||
error(err instanceof Error ? err.message : 'Falha ao enviar imagem da galeria.');
|
||||
} finally {
|
||||
setUploadingGallery(false);
|
||||
event.target.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveGalleryImage = (path: string) => {
|
||||
setGalleryImages((prev) => prev.filter((image) => image.path !== path));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
if (!formData.title || !formData.category) {
|
||||
error('Informe ao menos o título e a categoria do projeto.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Simulate API call
|
||||
setTimeout(() => {
|
||||
console.log('Project data:', formData);
|
||||
setLoading(false);
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch('/api/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: formData.title.trim(),
|
||||
category: formData.category,
|
||||
client: formData.client?.trim() || null,
|
||||
status: formData.status,
|
||||
description: formData.description?.trim() || null,
|
||||
completionDate: formData.date ? new Date(formData.date).toISOString() : null,
|
||||
coverImage: coverImage?.url ?? null,
|
||||
galleryImages: galleryImages.map((image) => image.url),
|
||||
featured: formData.featured,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.error || 'Erro ao salvar projeto');
|
||||
}
|
||||
|
||||
success('Projeto cadastrado com sucesso!');
|
||||
router.push('/admin/projetos');
|
||||
}, 1500);
|
||||
} catch (err) {
|
||||
console.error('Erro ao salvar projeto:', err);
|
||||
error(err instanceof Error ? err.message : 'Não foi possível salvar o projeto.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -73,10 +217,9 @@ export default function NewProject() {
|
||||
required
|
||||
>
|
||||
<option value="">Selecione uma categoria</option>
|
||||
<option value="veicular">Engenharia Veicular</option>
|
||||
<option value="mecanica">Projetos Mecânicos</option>
|
||||
<option value="laudos">Laudos e Inspeções</option>
|
||||
<option value="seguranca">Segurança do Trabalho</option>
|
||||
{CATEGORY_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -108,9 +251,9 @@ export default function NewProject() {
|
||||
onChange={(e) => setFormData({...formData, status: e.target.value})}
|
||||
className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all appearance-none cursor-pointer"
|
||||
>
|
||||
<option value="active">Concluído</option>
|
||||
<option value="pending">Em Andamento</option>
|
||||
<option value="draft">Rascunho</option>
|
||||
{STATUS_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -124,6 +267,19 @@ export default function NewProject() {
|
||||
placeholder="Descreva os detalhes técnicos, desafios e soluções do projeto..."
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<label className="flex items-center gap-3 text-sm font-bold text-gray-700 dark:text-gray-300">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.featured}
|
||||
onChange={(e) => setFormData({ ...formData, featured: e.target.checked })}
|
||||
className="h-5 w-5 rounded border-gray-300 text-primary focus:ring-primary"
|
||||
/>
|
||||
Destacar este projeto no site
|
||||
</label>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Projetos em destaque podem ser exibidos em seções especiais como a home.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -137,33 +293,97 @@ export default function NewProject() {
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Imagem de Capa</label>
|
||||
<div className="border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl p-8 text-center hover:border-primary dark:hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5">
|
||||
<div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center text-primary mx-auto mb-4">
|
||||
<i className="ri-upload-cloud-2-line text-3xl"></i>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-300 font-medium mb-1">Clique para fazer upload ou arraste e solte</p>
|
||||
<p className="text-xs text-gray-400">PNG, JPG ou WEBP (Max. 2MB)</p>
|
||||
<div
|
||||
onClick={() => coverInputRef.current?.click()}
|
||||
className="border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl p-6 text-center hover:border-primary dark:hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5 relative min-h-[200px] flex items-center justify-center"
|
||||
>
|
||||
{coverImage ? (
|
||||
<div className="w-full h-full relative">
|
||||
<img src={coverImage.url} alt={coverImage.name} className="w-full h-full object-cover rounded-lg" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setCoverImage(null);
|
||||
}}
|
||||
className="absolute top-3 right-3 bg-black/60 text-white w-8 h-8 rounded-full flex items-center justify-center hover:bg-black/80 transition-colors"
|
||||
>
|
||||
<i className="ri-close-line"></i>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center text-primary mb-4">
|
||||
{uploadingCover ? (
|
||||
<i className="ri-loader-4-line text-3xl animate-spin"></i>
|
||||
) : (
|
||||
<i className="ri-upload-cloud-2-line text-3xl"></i>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-300 font-medium mb-1">
|
||||
{uploadingCover ? 'Enviando imagem...' : 'Clique para fazer upload ou arraste e solte'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">PNG, JPG ou WEBP (máximo 2MB)</p>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
ref={coverInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleCoverSelect}
|
||||
disabled={uploadingCover}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Galeria de Fotos</label>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="aspect-square border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl flex flex-col items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5">
|
||||
<i className="ri-add-line text-3xl mb-2"></i>
|
||||
<span className="text-xs font-bold">Adicionar</span>
|
||||
</div>
|
||||
{/* Placeholders for uploaded images */}
|
||||
{[1, 2].map((i) => (
|
||||
<div key={i} className="aspect-square rounded-xl bg-gray-200 dark:bg-white/10 relative group overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => galleryInputRef.current?.click()}
|
||||
className="aspect-square border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl flex flex-col items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5"
|
||||
disabled={uploadingGallery}
|
||||
>
|
||||
{uploadingGallery ? (
|
||||
<>
|
||||
<i className="ri-loader-4-line text-3xl mb-2 animate-spin"></i>
|
||||
<span className="text-xs font-bold">Enviando...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<i className="ri-add-line text-3xl mb-2"></i>
|
||||
<span className="text-xs font-bold">Adicionar</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{galleryImages.map((image) => (
|
||||
<div key={image.path} className="aspect-square rounded-xl bg-gray-200 dark:bg-white/10 relative group overflow-hidden">
|
||||
<img src={image.url} alt={image.name} className="w-full h-full object-cover" />
|
||||
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
|
||||
<button type="button" className="w-8 h-8 rounded-lg bg-white/20 hover:bg-white/40 text-white flex items-center justify-center backdrop-blur-sm transition-colors">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveGalleryImage(image.path)}
|
||||
className="w-9 h-9 rounded-lg bg-white/20 hover:bg-white/40 text-white flex items-center justify-center backdrop-blur-sm transition-colors"
|
||||
>
|
||||
<i className="ri-delete-bin-line"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<input
|
||||
ref={galleryInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleGallerySelect}
|
||||
disabled={uploadingGallery}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Adicione até 8 imagens para apresentar detalhes do projeto.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -178,10 +398,10 @@ export default function NewProject() {
|
||||
</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
disabled={isSaving}
|
||||
className="px-8 py-3 bg-primary text-white rounded-xl font-bold hover-primary transition-colors shadow-lg shadow-primary/20 flex items-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? (
|
||||
{isSaving ? (
|
||||
<>
|
||||
<i className="ri-loader-4-line animate-spin"></i>
|
||||
Salvando...
|
||||
|
||||
Reference in New Issue
Block a user