feat: implement advanced publications UX with 12-column grid, sections and on-the-fly creation
This commit is contained in:
parent
0bce072ce4
commit
64c6568a99
@ -1,5 +1,5 @@
|
||||
import { APPWRITE_ALMEIRA_CONFIG } from '@/lib/appwrite';
|
||||
import { createSessionClient } from '@/lib/appwrite.server';
|
||||
import { createSessionClient, getLoggedInUser } from '@/lib/appwrite.server';
|
||||
import { Query } from 'node-appwrite';
|
||||
import Link from 'next/link';
|
||||
import { collectionMap, SCHEMA_MAP } from '@/lib/schema';
|
||||
@ -42,7 +42,8 @@ export default async function EntityPage({
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch preferences
|
||||
// Fetch user and preferences
|
||||
const user = await getLoggedInUser();
|
||||
const prefs = await getUserPreferences();
|
||||
const hiddenColumns = prefs.hiddenColumns?.[entity] || [];
|
||||
|
||||
@ -126,6 +127,7 @@ export default async function EntityPage({
|
||||
initialHiddenColumns={hiddenColumns}
|
||||
currentSortField={sort}
|
||||
currentSortDir={dir}
|
||||
user={user}
|
||||
/>
|
||||
|
||||
{/* Pagination */}
|
||||
|
||||
@ -17,6 +17,7 @@ interface DataTableProps {
|
||||
initialHiddenColumns: string[];
|
||||
currentSortField: string;
|
||||
currentSortDir: 'asc' | 'desc';
|
||||
user: any;
|
||||
}
|
||||
|
||||
export const DataTable = ({
|
||||
@ -26,7 +27,8 @@ export const DataTable = ({
|
||||
fieldsConfig,
|
||||
initialHiddenColumns,
|
||||
currentSortField,
|
||||
currentSortDir
|
||||
currentSortDir,
|
||||
user
|
||||
}: DataTableProps) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
@ -117,8 +119,19 @@ export const DataTable = ({
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800/60">
|
||||
{documents.map((doc) => (
|
||||
<tr key={doc.$id} className="hover:bg-slate-800/50 transition-colors group">
|
||||
{documents.map((doc) => {
|
||||
const canEdit = user?.$id === 'admin-emergency' || user?.labels?.includes('admin') || user?.labels?.includes('editor');
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={doc.$id}
|
||||
className={`transition-colors group ${canEdit ? 'hover:bg-cyan-500/5 cursor-pointer' : 'hover:bg-slate-800/50'}`}
|
||||
onClick={() => {
|
||||
if (canEdit) {
|
||||
router.push(`/dashboard/${entity}/${doc.$id}`);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{fieldsConfig.map(field => {
|
||||
if (!visibleColumns.includes(field.name)) return null;
|
||||
|
||||
@ -153,7 +166,7 @@ export const DataTable = ({
|
||||
<DeleteButton collectionId={collectionId} documentId={doc.$id} entityAlias={entity} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
)})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@ -7,6 +7,9 @@ import Link from 'next/link';
|
||||
import { FieldDefinition } from '@/lib/schema';
|
||||
import { MediaPickerMini } from './MediaPickerMini';
|
||||
import { RichTextEditor } from './RichTextEditor';
|
||||
import { QuickCreateModal } from './QuickCreateModal';
|
||||
import { collectionMap } from '@/lib/schema';
|
||||
import { Client, Databases } from 'appwrite';
|
||||
|
||||
// Minimalistic image preview for relations with 'media'
|
||||
const MediaPreview = ({ fileId, bucketId, endpoint, projectId }: any) => {
|
||||
@ -52,6 +55,11 @@ export const EntityForm = ({
|
||||
const [isAutoSlug, setIsAutoSlug] = useState(!initialData?.slug);
|
||||
const [featuredImageId, setFeaturedImageId] = useState(initialData?.imagen_destacada_id || '');
|
||||
const [editorValues, setEditorValues] = useState<Record<string, string>>({});
|
||||
const [localRelationData, setLocalRelationData] = useState(relationData);
|
||||
const [activeTab, setActiveTab] = useState('');
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [modalEntity, setModalEntity] = useState('');
|
||||
const [activeRelationField, setActiveRelationField] = useState('');
|
||||
|
||||
// Initialize editor values
|
||||
useEffect(() => {
|
||||
@ -77,6 +85,28 @@ export const EntityForm = ({
|
||||
}
|
||||
}, [title, isAutoSlug]);
|
||||
|
||||
const sections = Array.from(new Set(fields.map(f => f.section || 'General')));
|
||||
|
||||
useEffect(() => {
|
||||
if (sections.length > 0 && !activeTab) {
|
||||
setActiveTab(sections[0]);
|
||||
}
|
||||
}, [sections, activeTab]);
|
||||
|
||||
const refreshRelation = async (field: string, collectionId: string) => {
|
||||
const client = new Client()
|
||||
.setEndpoint(appwriteConfig.endpoint)
|
||||
.setProject(appwriteConfig.projectId);
|
||||
const databases = new Databases(client);
|
||||
|
||||
try {
|
||||
const res = await databases.listDocuments('almeira', collectionId, []);
|
||||
setLocalRelationData(prev => ({ ...prev, [field]: res.documents }));
|
||||
} catch (err) {
|
||||
console.error("Error al refrescar relación:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
@ -123,6 +153,7 @@ export const EntityForm = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<form onSubmit={handleSubmit} className="max-w-7xl mx-auto space-y-8 animate-fade-in pb-20">
|
||||
{/* Header Sticky */}
|
||||
<div className="sticky top-4 z-40 flex items-center justify-between bg-slate-900/80 backdrop-blur-xl border border-slate-800 p-4 rounded-2xl shadow-2xl shadow-cyan-500/10">
|
||||
@ -158,186 +189,129 @@ export const EntityForm = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
{/* Main Column */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 md:p-8 shadow-xl space-y-8 relative overflow-hidden">
|
||||
<div className="bg-slate-900 border border-slate-800 rounded-3xl p-1 flex overflow-x-auto gap-1 mb-6 sticky top-24 z-30 shadow-lg">
|
||||
{sections.map(section => (
|
||||
<button
|
||||
key={section}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(section)}
|
||||
className={`px-6 py-2.5 rounded-2xl text-xs font-black uppercase tracking-widest transition-all ${activeTab === section ? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/20' : 'text-slate-500 hover:text-slate-300 hover:bg-slate-800'}`}
|
||||
>
|
||||
{section}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-1 gap-8">
|
||||
<div className="bg-slate-900 border border-slate-800 rounded-3xl p-8 shadow-xl relative overflow-hidden">
|
||||
<div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-600 to-cyan-500 opacity-50"></div>
|
||||
|
||||
{mainFields.map(field => {
|
||||
const defaultValue = getDefValue(field);
|
||||
|
||||
if (field.name === 'titulo' || field.name === 'nombre_entidad' || field.name === 'numero_contrato') {
|
||||
return (
|
||||
<div key={field.name} className="space-y-2">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-cyan-500/80 mb-2 block">{field.label}</label>
|
||||
<input
|
||||
type="text"
|
||||
name={field.name}
|
||||
required={field.required}
|
||||
defaultValue={defaultValue}
|
||||
onChange={(e) => (field.name === 'titulo' || field.name === 'nombre_entidad') && setTitle(e.target.value)}
|
||||
placeholder={`Ingresa el ${field.label.toLowerCase()}...`}
|
||||
className="w-full bg-transparent border-b-2 border-slate-800 py-4 text-2xl md:text-3xl font-bold text-white focus:outline-none focus:border-cyan-500 transition-all placeholder:text-slate-700"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
<div className="grid grid-cols-12 gap-x-8 gap-y-10">
|
||||
{fields.filter(f => (f.section || 'General') === activeTab).map(field => {
|
||||
const defaultValue = getDefValue(field);
|
||||
const gridSpanMap: Record<number, string> = {
|
||||
1: 'col-span-1', 2: 'col-span-2', 3: 'col-span-3', 4: 'col-span-4',
|
||||
5: 'col-span-5', 6: 'col-span-6', 7: 'col-span-7', 8: 'col-span-8',
|
||||
9: 'col-span-9', 10: 'col-span-10', 11: 'col-span-11', 12: 'col-span-12'
|
||||
};
|
||||
const gridSpan = gridSpanMap[field.gridSize || 12] || 'col-span-12';
|
||||
|
||||
return (
|
||||
<div key={field.name} className={`${gridSpan} flex flex-col gap-2 group`}>
|
||||
<div className="flex justify-between items-center mb-1">
|
||||
<label className="text-[10px] font-black uppercase tracking-widest text-slate-500 group-focus-within:text-cyan-400 transition-colors">
|
||||
{field.label} {field.required && <span className="text-pink-500">*</span>}
|
||||
</label>
|
||||
{field.type === 'relation' && (
|
||||
<span className="text-[8px] font-bold text-slate-600 uppercase tracking-tighter">Double click to create quick +</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
if (field.type === 'textarea') {
|
||||
return (
|
||||
<RichTextEditor
|
||||
key={field.name}
|
||||
label={field.label}
|
||||
value={editorValues[field.name] || ''}
|
||||
onChange={(val) => setEditorValues(prev => ({ ...prev, [field.name]: val }))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={field.name} className="flex flex-col gap-2">
|
||||
<label className="text-sm font-bold tracking-widest text-slate-400 uppercase">
|
||||
{field.label} {field.required && <span className="text-pink-500">*</span>}
|
||||
</label>
|
||||
|
||||
{field.type === 'text' && (
|
||||
<input type="text" name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all" />
|
||||
)}
|
||||
|
||||
{field.type === 'number' && (
|
||||
<input type="number" step="any" name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all" />
|
||||
)}
|
||||
|
||||
{field.type === 'url' && (
|
||||
<input type="url" name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all placeholder:text-slate-700" placeholder="https://" />
|
||||
)}
|
||||
|
||||
{field.type === 'boolean' && (
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all appearance-none pr-10">
|
||||
<option value="true">Sí (Activo)</option>
|
||||
<option value="false">No (Inactivo)</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
{field.type === 'select' && field.options && (
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all appearance-none pr-10 capitalize">
|
||||
<option value="">Seleccione {field.label}...</option>
|
||||
{field.options.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
)}
|
||||
|
||||
{field.type === 'relation' && (
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="bg-slate-950 border border-slate-800 rounded-xl px-5 py-3.5 text-white focus:outline-none focus:border-cyan-500 transition-all appearance-none pr-10">
|
||||
<option value="">Buscar vinculación...</option>
|
||||
{relationData[field.name]?.map(relDoc => (
|
||||
<option key={relDoc.$id} value={relDoc.$id}>
|
||||
{relDoc[field.relationLabel || 'codigo'] || relDoc.$id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar Column */}
|
||||
<div className="space-y-6">
|
||||
<div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-6">
|
||||
<h2 className="text-xs font-black uppercase tracking-[0.2em] text-slate-500 pb-4 border-b border-slate-800 flex items-center gap-2">
|
||||
<Globe size={14} className="text-cyan-500" /> Configuración de Publicación
|
||||
</h2>
|
||||
|
||||
{sidebarFields.map(field => {
|
||||
const defaultValue = getDefValue(field);
|
||||
|
||||
return (
|
||||
<div key={field.name} className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-[10px] font-black uppercase tracking-widest text-slate-400 flex items-center gap-1">
|
||||
{field.name === 'fecha_publicacion' && <Calendar size={12} className="text-pink-500" />}
|
||||
{field.name === 'estado' && <Tag size={12} className="text-blue-500" />}
|
||||
{field.name === 'imagen_destacada_id' && <ImageIcon size={12} className="text-purple-500" />}
|
||||
{field.label}
|
||||
</label>
|
||||
{field.name === 'slug' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsAutoSlug(!isAutoSlug)}
|
||||
className={`text-[9px] font-bold px-1.5 py-0.5 rounded transition-colors ${isAutoSlug ? 'bg-cyan-500/10 text-cyan-500' : 'bg-slate-800 text-slate-500'}`}
|
||||
>
|
||||
{isAutoSlug ? 'AUTO' : 'MANUAL'}
|
||||
</button>
|
||||
{field.name === 'titulo' || field.name === 'nombre_entidad' ? (
|
||||
<input
|
||||
type="text"
|
||||
name={field.name}
|
||||
required={field.required}
|
||||
defaultValue={defaultValue}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder={`Nombre de ${field.label}...`}
|
||||
className="w-full bg-transparent border-b-2 border-slate-800 py-2 text-2xl font-bold text-white focus:outline-none focus:border-cyan-500 transition-all placeholder:text-slate-700"
|
||||
/>
|
||||
) : field.type === 'textarea' ? (
|
||||
<RichTextEditor
|
||||
label={field.label}
|
||||
value={editorValues[field.name] || ''}
|
||||
onChange={(val) => setEditorValues(prev => ({ ...prev, [field.name]: val }))}
|
||||
/>
|
||||
) : field.type === 'relation' ? (
|
||||
<div className="space-y-4">
|
||||
<select
|
||||
name={field.name}
|
||||
defaultValue={defaultValue}
|
||||
required={field.required}
|
||||
onDoubleClick={() => {
|
||||
setModalEntity(field.relationCollection as string);
|
||||
setActiveRelationField(field.name);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-5 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all appearance-none pr-10 hover:border-slate-700 cursor-pointer"
|
||||
>
|
||||
<option value="">Seleccionar vinculación...</option>
|
||||
{localRelationData[field.name]?.map(relDoc => (
|
||||
<option key={relDoc.$id} value={relDoc.$id}>
|
||||
{relDoc[field.relationLabel || 'titulo'] || relDoc.$id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{field.relationCollection === 'media' && (
|
||||
<MediaPreview
|
||||
fileId={defaultValue}
|
||||
bucketId="media"
|
||||
endpoint={appwriteConfig.endpoint}
|
||||
projectId={appwriteConfig.projectId}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : field.type === 'select' ? (
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-5 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all appearance-none pr-10 capitalize">
|
||||
{field.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
) : field.type === 'date' ? (
|
||||
<input type="datetime-local" name={field.name} defaultValue={defaultValue} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-5 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all [color-scheme:dark]" />
|
||||
) : field.type === 'boolean' ? (
|
||||
<select name={field.name} defaultValue={String(defaultValue)} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-5 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all">
|
||||
<option value="true">Sí (Activo)</option>
|
||||
<option value="false">No (Inactivo)</option>
|
||||
</select>
|
||||
) : (
|
||||
<input type={field.type === 'number' ? 'number' : 'text'} name={field.name} defaultValue={defaultValue} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-5 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{field.name === 'slug' ? (
|
||||
<input
|
||||
type="text"
|
||||
name={field.name}
|
||||
value={slug}
|
||||
onChange={(e) => { setIsAutoSlug(false); setSlug(e.target.value); }}
|
||||
required={field.required}
|
||||
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-cyan-100 font-mono focus:outline-none focus:border-cyan-500 transition-all font-bold"
|
||||
/>
|
||||
) : field.name === 'imagen_destacada_id' ? (
|
||||
<MediaPickerMini
|
||||
label={field.label}
|
||||
value={featuredImageId}
|
||||
onChange={setFeaturedImageId}
|
||||
/>
|
||||
) : field.type === 'date' ? (
|
||||
<input
|
||||
type="datetime-local"
|
||||
name={field.name}
|
||||
defaultValue={defaultValue}
|
||||
required={field.required}
|
||||
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all [color-scheme:dark]"
|
||||
/>
|
||||
) : field.type === 'select' ? (
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all capitalize">
|
||||
{field.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
) : field.type === 'relation' ? (
|
||||
<>
|
||||
<select name={field.name} defaultValue={defaultValue} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all">
|
||||
<option value="">Seleccionar...</option>
|
||||
{relationData[field.name]?.map(relDoc => (
|
||||
<option key={relDoc.$id} value={relDoc.$id}>
|
||||
{relDoc[field.relationLabel || 'titulo'] || relDoc.$id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{field.relationCollection === 'media' && (
|
||||
<MediaPreview
|
||||
fileId={defaultValue}
|
||||
bucketId="media"
|
||||
endpoint={appwriteConfig.endpoint}
|
||||
projectId={appwriteConfig.projectId}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<input type="text" name={field.name} defaultValue={defaultValue} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="bg-gradient-to-br from-indigo-900/20 to-blue-900/10 border border-slate-800 rounded-3xl p-6 shadow-xl">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
|
||||
<span className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">Estado del Sistema</span>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500 leading-relaxed italic">
|
||||
“Recuerda verificar el slug antes de publicar. Los cambios en el estado afectarán inmediatamente la visibilidad en el portal de noticias.”
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<QuickCreateModal
|
||||
entity={modalEntity}
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
onSuccess={async (newId) => {
|
||||
const relField = fields.find(f => f.name === activeRelationField);
|
||||
if (relField?.relationCollection) {
|
||||
await refreshRelation(activeRelationField, collectionMap[relField.relationCollection]);
|
||||
// Set wait to ensure state has updated options before selecting
|
||||
setTimeout(() => {
|
||||
const selectElement = document.querySelector(`select[name="${activeRelationField}"]`) as HTMLSelectElement;
|
||||
if (selectElement) {
|
||||
selectElement.value = newId;
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
108
src/components/dashboard/QuickCreateModal.tsx
Normal file
108
src/components/dashboard/QuickCreateModal.tsx
Normal file
@ -0,0 +1,108 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { X, Save, Plus } from 'lucide-react';
|
||||
import { FieldDefinition, SCHEMA_MAP, collectionMap } from '@/lib/schema';
|
||||
import { createDocumentServer } from '@/app/actions/appwrite';
|
||||
|
||||
interface QuickCreateModalProps {
|
||||
entity: string;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: (newId: string) => void;
|
||||
}
|
||||
|
||||
export const QuickCreateModal = ({ entity, isOpen, onClose, onSuccess }: QuickCreateModalProps) => {
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const fields = SCHEMA_MAP[entity] || [];
|
||||
const collectionId = collectionMap[entity];
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsPending(true);
|
||||
|
||||
try {
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const data: Record<string, any> = {};
|
||||
for (const [key, value] of formData.entries()) {
|
||||
data[key] = value;
|
||||
}
|
||||
|
||||
// Simple type conversion
|
||||
fields.forEach(f => {
|
||||
if (f.type === 'number' && data[f.name]) data[f.name] = parseFloat(data[f.name]);
|
||||
if (f.type === 'boolean') data[f.name] = data[f.name] === 'true';
|
||||
});
|
||||
|
||||
const res = await createDocumentServer(collectionId, data);
|
||||
if (res.success && res.data?.$id) {
|
||||
onSuccess(res.data.$id);
|
||||
onClose();
|
||||
} else {
|
||||
alert("Error al crear: " + (res.error || "Desconocido"));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("QuickCreate error:", error);
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-fade-in">
|
||||
<div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-xl shadow-2xl overflow-hidden animate-slide-up">
|
||||
<div className="p-6 border-b border-slate-800 flex justify-between items-center bg-slate-950/30">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-cyan-500/10 rounded-xl text-cyan-400">
|
||||
<Plus size={20} />
|
||||
</div>
|
||||
<h2 className="text-xl font-black uppercase font-outfit tracking-tighter text-white">
|
||||
Creación Rápida: <span className="text-cyan-400">{entity}</span>
|
||||
</h2>
|
||||
</div>
|
||||
<button onClick={onClose} className="p-2 text-slate-500 hover:text-white transition-colors">
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-8 space-y-6 max-h-[70vh] overflow-y-auto custom-scrollbar">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{fields.filter(f => f.name !== 'slug').map(field => (
|
||||
<div key={field.name} className={`space-y-2 ${field.type === 'textarea' ? 'md:col-span-2' : ''}`}>
|
||||
<label className="text-[10px] font-black uppercase tracking-widest text-slate-500">{field.label}</label>
|
||||
{field.type === 'textarea' ? (
|
||||
<textarea name={field.name} required={field.required} rows={3} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all"></textarea>
|
||||
) : field.type === 'select' ? (
|
||||
<select name={field.name} required={field.required} className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all capitalize">
|
||||
{field.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type={field.type === 'number' ? 'number' : field.type === 'date' ? 'datetime-local' : 'text'}
|
||||
name={field.name}
|
||||
required={field.required}
|
||||
className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 transition-all"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="pt-6 flex justify-end gap-3">
|
||||
<button type="button" onClick={onClose} className="px-6 py-2.5 rounded-xl text-sm font-bold text-slate-400 hover:text-white transition-colors">Cancelar</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending}
|
||||
className="flex items-center gap-2 bg-gradient-to-r from-blue-600 to-cyan-500 text-white text-sm font-black uppercase tracking-widest px-8 py-2.5 rounded-xl shadow-lg shadow-cyan-900/20 disabled:opacity-50"
|
||||
>
|
||||
{isPending ? <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></div> : <Save size={18} />}
|
||||
Guardar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -8,24 +8,26 @@ export type FieldDefinition = {
|
||||
options?: string[]; // For 'select' type
|
||||
relationCollection?: string; // Appwrite collection alias
|
||||
relationLabel?: string; // Field to display in relation select
|
||||
section?: string; // For grouping in the form
|
||||
gridSize?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; // 12-column grid system
|
||||
};
|
||||
|
||||
export const SCHEMA_MAP: Record<string, FieldDefinition[]> = {
|
||||
posts: [
|
||||
{ name: 'titulo', label: 'Título', type: 'text', required: true },
|
||||
{ name: 'slug', label: 'URL Amigable (Slug)', type: 'text', required: true },
|
||||
{ name: 'tipo_publicacion_id', label: 'Tipo de Publicación', type: 'relation', relationCollection: 'publication_types', relationLabel: 'descripcion', required: true },
|
||||
{ name: 'estado', label: 'Estado', type: 'select', options: ['borrador', 'pendiente', 'publicado'], required: true },
|
||||
{ name: 'fecha_publicacion', label: 'Fecha de Publicación', type: 'date', required: true },
|
||||
{ name: 'fecha_finalizacion', label: 'Expiración / Caducidad', type: 'date' },
|
||||
{ name: 'cliente_id', label: 'Patrocinador Cliente', type: 'relation', relationCollection: 'clients', relationLabel: 'nombre_entidad' },
|
||||
{ name: 'url_destino', label: 'URL Destino (Banner/Click)', type: 'url' },
|
||||
{ name: 'resumen_redes', label: 'Resumen para Redes', type: 'textarea' },
|
||||
{ name: 'contenido', label: 'Contenido Completo', type: 'textarea', required: true },
|
||||
{ name: 'imagen_destacada_id', label: 'ID de Imagen (Relacional)', type: 'relation', relationCollection: 'media', relationLabel: 'titulo' },
|
||||
{ name: 'video_url', label: 'URL de Video', type: 'url' },
|
||||
{ name: 'seo_titulo', label: 'SEO Título', type: 'text' },
|
||||
{ name: 'seo_descripcion', label: 'SEO Descripción', type: 'text' },
|
||||
{ name: 'titulo', label: 'Título', type: 'text', required: true, section: 'Datos Básicos', gridSize: 12 },
|
||||
{ name: 'slug', label: 'URL Amigable (Slug)', type: 'text', required: true, section: 'Metadatos', gridSize: 6 },
|
||||
{ name: 'tipo_publicacion_id', label: 'Tipo de Publicación', type: 'relation', relationCollection: 'publication_types', relationLabel: 'descripcion', required: true, section: 'Metadatos', gridSize: 6 },
|
||||
{ name: 'estado', label: 'Estado', type: 'select', options: ['borrador', 'pendiente', 'publicado'], required: true, section: 'Configuración', gridSize: 4 },
|
||||
{ name: 'fecha_publicacion', label: 'Fecha de Publicación', type: 'date', required: true, section: 'Configuración', gridSize: 4 },
|
||||
{ name: 'fecha_finalizacion', label: 'Expiración / Caducidad', type: 'date', section: 'Configuración', gridSize: 4 },
|
||||
{ name: 'cliente_id', label: 'Patrocinador Cliente', type: 'relation', relationCollection: 'clients', relationLabel: 'nombre_entidad', section: 'Comercial', gridSize: 6 },
|
||||
{ name: 'url_destino', label: 'URL Destino (Banner/Click)', type: 'url', section: 'Comercial', gridSize: 6 },
|
||||
{ name: 'resumen_redes', label: 'Resumen para Redes', type: 'textarea', section: 'Datos Básicos', gridSize: 12 },
|
||||
{ name: 'contenido', label: 'Contenido Completo', type: 'textarea', required: true, section: 'Datos Básicos', gridSize: 12 },
|
||||
{ name: 'imagen_destacada_id', label: 'Imagen Destacada', type: 'relation', relationCollection: 'media', relationLabel: 'titulo', section: 'Multimedia', gridSize: 12 },
|
||||
{ name: 'video_url', label: 'URL de Video (Youtube/Vimeo)', type: 'url', section: 'Multimedia', gridSize: 12 },
|
||||
{ name: 'seo_titulo', label: 'SEO Título', type: 'text', section: 'SEO', gridSize: 6 },
|
||||
{ name: 'seo_descripcion', label: 'SEO Descripción', type: 'text', section: 'SEO', gridSize: 6 },
|
||||
],
|
||||
categories: [
|
||||
{ name: 'nombre', label: 'Nombre de la Categoría', type: 'text', required: true },
|
||||
|
||||
Loading…
Reference in New Issue
Block a user