import { APPWRITE_ALMEIRA_CONFIG, endpoint, projectId } from '@/lib/appwrite'; import { createAdminClient, getLoggedInUser } from '@/lib/appwrite.server'; import { Query } from 'node-appwrite'; import Link from 'next/link'; import { collectionMap, SCHEMA_MAP } from '@/lib/schema'; import { DataTable } from '@/components/dashboard/DataTable'; import { getUserPreferences } from '@/lib/preferences'; import { ErrorBoundary } from '@/components/publications/ErrorBoundary'; import { saveEntityAction } from '@/app/actions/entities'; import type { Post, AuthUser } from '@/types/publications'; import { PublicationsList } from '@/components/publications/PublicationsList'; export default async function EntityPage({ params, searchParams, }: { params: Promise<{ entity: string }>; searchParams: Promise<{ q?: string; page?: string; sort?: string; dir?: string }>; }) { const { entity } = await params; const sParams = await searchParams; const q = sParams.q || ''; const page = Number(sParams.page) || 1; const sort = sParams.sort || '$createdAt'; const dir: 'asc' | 'desc' = sParams.dir === 'asc' ? 'asc' : 'desc'; const limit: number = entity === 'posts' ? 12 : 15; const offset = (page - 1) * limit; const collectionId = collectionMap[entity]; const fieldsConfig = SCHEMA_MAP[entity] || []; const entityNames: Record = { posts: 'Publicaciones', categories: 'Categorías', clients: 'Clientes', client_types: 'Tipos de Cliente', countries: 'Países', departments: 'Departamentos', cities: 'Ciudades', contracts: 'Contratos', payment_methods: 'Formas de Pago', publication_types: 'Tipos de Publicación', }; const entityName = entityNames[entity] || entity.replace(/_/g, ' '); if (!collectionId) { return (

Colección no encontrada

La ruta /dashboard/{entity} no está configurada.

← Volver al inicio
); } const user = JSON.parse(JSON.stringify(await getLoggedInUser())); const prefs = await getUserPreferences(); const hiddenColumns = prefs.hiddenColumns?.[entity] || []; let documents: any[] = []; let total = 0; let relationData: Record = {}; try { const client = await createAdminClient(); const queries = [Query.limit(limit), Query.offset(offset)]; if (dir === 'asc') queries.push(Query.orderAsc(sort)); else queries.push(Query.orderDesc(sort)); if (q) { const searchableFields = fieldsConfig .filter((f: any) => f.type === 'text' || f.type === 'textarea') .map((f: any) => f.name) .slice(0, 2); if (searchableFields.length > 0) { queries.push(Query.contains(searchableFields[0], q)); } } const response = await client.databases.listDocuments( APPWRITE_ALMEIRA_CONFIG.databaseId, collectionId, queries ); documents = JSON.parse(JSON.stringify(response.documents)); total = response.total; const fields = SCHEMA_MAP[entity] || []; await Promise.all( fields .filter((f) => f.type === 'relation' && f.relationCollection) .map(async (field) => { const relKey = field.relationCollection as string; const relColId = collectionMap[relKey]; if (!relColId) return; const ids = Array.from(new Set( response.documents .map(d => typeof d[field.name] === 'object' && d[field.name] !== null ? d[field.name].$id : d[field.name]) .filter(id => typeof id === 'string' && id.length > 0) )); if (ids.length === 0) { relationData[field.name] = []; return; } try { const relRes = await client.databases.listDocuments( APPWRITE_ALMEIRA_CONFIG.databaseId, relColId, [Query.equal('$id', ids), Query.limit(100)] ); relationData[field.name] = JSON.parse(JSON.stringify(relRes.documents)); } catch { } }) ); // Enrich documents with resolved relation data for DataTable documents = documents.map(doc => { const enriched = { ...doc }; fields.forEach(field => { if (field.type === 'relation' && typeof enriched[field.name] === 'string' && relationData[field.name]) { const relDoc = relationData[field.name].find(r => r.$id === enriched[field.name]); if (relDoc) { enriched[field.name] = relDoc; } } }); return enriched; }); documents = JSON.parse(JSON.stringify(documents)); } catch (error) { console.error(`Error fetching entity ${entity}:`, error); } const boundEditAction = async (id: string, formData: FormData) => { 'use server'; const { updateEntityAction } = await import('@/app/actions/entities'); return updateEntityAction(entity, id, formData); }; return (

{entityName}

Total en sistema: {total}

+ Nuevo
{entity === 'posts' ? ( ) : ( )} {total > limit && (() => { const totalPages = Math.ceil(total / limit); return (
« INICIO ANTERIOR Página {page} de {totalPages} = totalPages ? 'opacity-30 pointer-events-none bg-slate-900' : 'bg-slate-900 text-white hover:border-cyan-500'}`} > SIGUIENTE = totalPages ? 'opacity-30 pointer-events-none bg-slate-900' : 'bg-slate-900 text-white hover:border-cyan-500'}`} title="Ir a la última página" > FINAL »
); })()}
); }