Refactor user management in usuarios.tsx: integrate react-query for data fetching and mutations, streamline role handling, and enhance user ban/unban functionality.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { createFileRoute, Link, useRouter } from '@tanstack/react-router'
|
||||
import { useSuspenseQuery, queryOptions, useQueryClient } from '@tanstack/react-query'
|
||||
import { supabase, useSupabaseAuth } from '@/auth/supabase'
|
||||
import * as Icons from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
@@ -18,6 +19,7 @@ type Plan = {
|
||||
sistema_evaluacion: string | null
|
||||
total_creditos: number | null
|
||||
}
|
||||
|
||||
type Asignatura = {
|
||||
id: string
|
||||
nombre: string
|
||||
@@ -34,78 +36,86 @@ type LoaderData = {
|
||||
recientes: Array<{ tipo: 'plan' | 'asignatura'; id: string; nombre: string; fecha: string | null }>
|
||||
}
|
||||
|
||||
/* ========= Loader ========= */
|
||||
/* ========= Query Key & Fetcher ========= */
|
||||
const dashboardKeys = {
|
||||
root: ['dashboard'] as const,
|
||||
summary: () => [...dashboardKeys.root, 'summary'] as const,
|
||||
}
|
||||
|
||||
async function fetchDashboard(): Promise<LoaderData> {
|
||||
const [facRes, carRes, planesRes, asigRes] = await Promise.all([
|
||||
supabase.from('facultades').select('*', { count: 'exact', head: true }),
|
||||
supabase.from('carreras').select('*', { count: 'exact', head: true }),
|
||||
supabase
|
||||
.from('plan_estudios')
|
||||
.select(
|
||||
'id, nombre, fecha_creacion, objetivo_general, perfil_ingreso, perfil_egreso, sistema_evaluacion, total_creditos'
|
||||
),
|
||||
supabase
|
||||
.from('asignaturas')
|
||||
.select('id, nombre, fecha_creacion, contenidos, criterios_evaluacion, bibliografia'),
|
||||
])
|
||||
|
||||
const planes = (planesRes.data ?? []) as Plan[]
|
||||
const asignaturas = (asigRes.data ?? []) as Asignatura[]
|
||||
|
||||
// Calidad de planes
|
||||
const needed: (keyof Plan)[] = [
|
||||
'objetivo_general',
|
||||
'perfil_ingreso',
|
||||
'perfil_egreso',
|
||||
'sistema_evaluacion',
|
||||
'total_creditos',
|
||||
]
|
||||
const completos = planes.filter((p) => needed.every((k) => p[k] !== null && String(p[k] ?? '').trim() !== '')).length
|
||||
const calidadPlanesPct = planes.length ? Math.round((completos / planes.length) * 100) : 0
|
||||
|
||||
// Salud de asignaturas
|
||||
const sinBibliografia = asignaturas.filter(
|
||||
(a) => !a.bibliografia || (Array.isArray(a.bibliografia) && a.bibliografia.length === 0)
|
||||
).length
|
||||
const sinCriterios = asignaturas.filter((a) => !a.criterios_evaluacion?.trim()).length
|
||||
const sinContenidos = asignaturas.filter(
|
||||
(a) => !a.contenidos || (Array.isArray(a.contenidos) && a.contenidos.length === 0)
|
||||
).length
|
||||
|
||||
// Actividad reciente (últimos 8 ítems)
|
||||
const recientes = [
|
||||
...planes.map((p) => ({ tipo: 'plan' as const, id: p.id, nombre: p.nombre, fecha: p.fecha_creacion })),
|
||||
...asignaturas.map((a) => ({ tipo: 'asignatura' as const, id: a.id, nombre: a.nombre, fecha: a.fecha_creacion })),
|
||||
]
|
||||
.sort((a, b) => new Date(b.fecha ?? 0).getTime() - new Date(a.fecha ?? 0).getTime())
|
||||
.slice(0, 8)
|
||||
|
||||
return {
|
||||
kpis: {
|
||||
facultades: facRes.count ?? 0,
|
||||
carreras: carRes.count ?? 0,
|
||||
planes: planes.length,
|
||||
asignaturas: asignaturas.length,
|
||||
},
|
||||
calidadPlanesPct,
|
||||
saludAsignaturas: { sinBibliografia, sinCriterios, sinContenidos },
|
||||
recientes,
|
||||
}
|
||||
}
|
||||
|
||||
const dashboardOptions = () =>
|
||||
queryOptions({ queryKey: dashboardKeys.summary(), queryFn: fetchDashboard, staleTime: 30_000 })
|
||||
|
||||
/* ========= Ruta ========= */
|
||||
export const Route = createFileRoute('/_authenticated/dashboard')({
|
||||
component: RouteComponent,
|
||||
pendingComponent: DashboardSkeleton,
|
||||
loader: async (): Promise<LoaderData> => {
|
||||
// KPI counts
|
||||
const [{ count: facCount }, { count: carCount }, { data: planesRaw }, { data: asignRaw }] =
|
||||
await Promise.all([
|
||||
supabase.from('facultades').select('*', { count: 'exact', head: true }),
|
||||
supabase.from('carreras').select('*', { count: 'exact', head: true }),
|
||||
supabase
|
||||
.from('plan_estudios')
|
||||
.select(
|
||||
'id, nombre, fecha_creacion, objetivo_general, perfil_ingreso, perfil_egreso, sistema_evaluacion, total_creditos'
|
||||
),
|
||||
supabase
|
||||
.from('asignaturas')
|
||||
.select('id, nombre, fecha_creacion, contenidos, criterios_evaluacion, bibliografia')
|
||||
])
|
||||
|
||||
const planes = (planesRaw ?? []) as Plan[]
|
||||
const asignaturas = (asignRaw ?? []) as Asignatura[]
|
||||
|
||||
// Calidad de planes
|
||||
const needed: (keyof Plan)[] = [
|
||||
'objetivo_general',
|
||||
'perfil_ingreso',
|
||||
'perfil_egreso',
|
||||
'sistema_evaluacion',
|
||||
'total_creditos'
|
||||
]
|
||||
const completos = planes.filter(p =>
|
||||
needed.every(k => p[k] !== null && String(p[k] ?? '').toString().trim() !== '')
|
||||
).length
|
||||
const calidadPlanesPct = planes.length ? Math.round((completos / planes.length) * 100) : 0
|
||||
|
||||
// Salud de asignaturas
|
||||
const sinBibliografia = asignaturas.filter(
|
||||
a => !a.bibliografia || (Array.isArray(a.bibliografia) && a.bibliografia.length === 0)
|
||||
).length
|
||||
const sinCriterios = asignaturas.filter(a => !a.criterios_evaluacion?.trim()).length
|
||||
const sinContenidos = asignaturas.filter(
|
||||
a => !a.contenidos || (Array.isArray(a.contenidos) && a.contenidos.length === 0)
|
||||
).length
|
||||
|
||||
// Actividad reciente (últimos 8 ítems)
|
||||
const recientes = [
|
||||
...planes.map(p => ({ tipo: 'plan' as const, id: p.id, nombre: p.nombre, fecha: p.fecha_creacion })),
|
||||
...asignaturas.map(a => ({ tipo: 'asignatura' as const, id: a.id, nombre: a.nombre, fecha: a.fecha_creacion }))
|
||||
]
|
||||
.sort((a, b) => new Date(b.fecha ?? 0).getTime() - new Date(a.fecha ?? 0).getTime())
|
||||
.slice(0, 8)
|
||||
|
||||
return {
|
||||
kpis: {
|
||||
facultades: facCount ?? 0,
|
||||
carreras: carCount ?? 0,
|
||||
planes: planes.length,
|
||||
asignaturas: asignaturas.length
|
||||
},
|
||||
calidadPlanesPct,
|
||||
saludAsignaturas: { sinBibliografia, sinCriterios, sinContenidos },
|
||||
recientes
|
||||
}
|
||||
}
|
||||
loader: async ({ context: { queryClient } }) => {
|
||||
await queryClient.ensureQueryData(dashboardOptions())
|
||||
return null
|
||||
},
|
||||
})
|
||||
|
||||
/* ========= Helpers visuales ========= */
|
||||
function gradient(bg = '#2563eb') {
|
||||
return {
|
||||
background: `linear-gradient(135deg, ${bg} 0%, ${bg}cc 45%, ${bg}a6 75%, ${bg}66 100%)`
|
||||
} as React.CSSProperties
|
||||
return { background: `linear-gradient(135deg, ${bg} 0%, ${bg}cc 45%, ${bg}a6 75%, ${bg}66 100%)` } as React.CSSProperties
|
||||
}
|
||||
function hex(color?: string | null, fallback = '#2563eb') {
|
||||
return color && /^#([0-9a-f]{6}|[0-9a-f]{3})$/i.test(color) ? color : fallback
|
||||
@@ -139,22 +149,9 @@ function Ring({ pct, color }: { pct: number; color: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function Tile({
|
||||
to,
|
||||
label,
|
||||
value,
|
||||
Icon
|
||||
}: {
|
||||
to: string
|
||||
label: string
|
||||
value: number | string
|
||||
Icon: React.ComponentType<React.SVGProps<SVGSVGElement>>
|
||||
}) {
|
||||
function Tile({ to, label, value, Icon }: { to: string; label: string; value: number | string; Icon: React.ComponentType<React.SVGProps<SVGSVGElement>> }) {
|
||||
return (
|
||||
<Link
|
||||
to={to}
|
||||
className="group rounded-2xl ring-1 ring-black/5 bg-white/80 dark:bg-neutral-900/60 p-5 flex items-center justify-between hover:-translate-y-0.5 transition-all"
|
||||
>
|
||||
<Link to={to} className="group rounded-2xl ring-1 ring-black/5 bg-white/80 dark:bg-neutral-900/60 p-5 flex items-center justify-between hover:-translate-y-0.5 transition-all">
|
||||
<div>
|
||||
<div className="text-sm text-neutral-500">{label}</div>
|
||||
<div className="text-3xl font-bold tabular-nums">{value}</div>
|
||||
@@ -168,21 +165,18 @@ function Tile({
|
||||
|
||||
/* ========= Página ========= */
|
||||
function RouteComponent() {
|
||||
const { kpis, calidadPlanesPct, saludAsignaturas, recientes } = Route.useLoaderData() as LoaderData
|
||||
const { data } = useSuspenseQuery(dashboardOptions())
|
||||
const { kpis, calidadPlanesPct, saludAsignaturas, recientes } = data
|
||||
|
||||
const auth = useSupabaseAuth()
|
||||
const router = useRouter()
|
||||
const primary = hex(auth.claims?.facultad_color, '#1d4ed8') // si guardan color de facultad en claims
|
||||
const qc = useQueryClient()
|
||||
const primary = hex(auth.claims?.facultad_color, '#1d4ed8')
|
||||
|
||||
const name = auth.user?.user_metadata?.nombre || auth.user?.email?.split('@')[0] || '¡Hola!'
|
||||
|
||||
const isAdmin = !!auth.claims?.claims_admin
|
||||
const role = auth.claims?.role as
|
||||
| 'lci'
|
||||
| 'vicerrectoria'
|
||||
| 'secretario_academico'
|
||||
| 'jefe_carrera'
|
||||
| 'planeacion'
|
||||
| undefined
|
||||
const role = auth.claims?.role as 'lci' | 'vicerrectoria' | 'secretario_academico' | 'jefe_carrera' | 'planeacion' | undefined
|
||||
|
||||
// Mensaje contextual
|
||||
const roleHint = useMemo(() => {
|
||||
@@ -204,10 +198,7 @@ function RouteComponent() {
|
||||
<div className="p-6 space-y-8">
|
||||
{/* Header con saludo y búsqueda global */}
|
||||
<div className="relative rounded-3xl overflow-hidden shadow-xl text-white" style={gradient(primary)}>
|
||||
<div
|
||||
className="absolute inset-0 opacity-25"
|
||||
style={{ background: 'radial-gradient(800px 300px at 20% -10%, #fff, transparent 60%)' }}
|
||||
/>
|
||||
<div className="absolute inset-0 opacity-25" style={{ background: 'radial-gradient(800px 300px at 20% -10%, #fff, transparent 60%)' }} />
|
||||
<div className="relative p-6 md:p-8 flex flex-col gap-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
@@ -215,7 +206,11 @@ function RouteComponent() {
|
||||
<p className="opacity-95">{roleHint}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{role && <Badge variant="secondary" className="bg-white/20 text-white border-white/30">{role}</Badge>}
|
||||
{role && (
|
||||
<Badge variant="secondary" className="bg-white/20 text-white border-white/30">
|
||||
{role}
|
||||
</Badge>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Badge className="bg-white/20 text-white border-white/30 flex items-center gap-1">
|
||||
<Icons.ShieldCheck className="w-3.5 h-3.5" /> admin
|
||||
@@ -228,7 +223,7 @@ function RouteComponent() {
|
||||
<Input
|
||||
placeholder="Buscar planes, asignaturas o personas… (Enter)"
|
||||
className="bg-white/90 text-neutral-800 placeholder:text-neutral-400"
|
||||
onKeyDown={e => {
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
const q = (e.target as HTMLInputElement).value.trim()
|
||||
if (!q) return
|
||||
@@ -239,7 +234,10 @@ function RouteComponent() {
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="bg-white/20 text-white hover:bg-white/30 border-white/30"
|
||||
onClick={() => router.invalidate()}
|
||||
onClick={async () => {
|
||||
await qc.invalidateQueries({ queryKey: dashboardKeys.root })
|
||||
router.invalidate()
|
||||
}}
|
||||
title="Actualizar"
|
||||
>
|
||||
<Icons.RefreshCcw className="w-4 h-4" />
|
||||
@@ -248,23 +246,18 @@ function RouteComponent() {
|
||||
|
||||
{/* Atajos rápidos (según rol) */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link
|
||||
to="/planes"
|
||||
className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30"
|
||||
>
|
||||
<Link to="/planes" className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30">
|
||||
<Icons.ScrollText className="w-4 h-4" /> Nuevo plan
|
||||
</Link>
|
||||
<Link
|
||||
to="/asignaturas"
|
||||
search={{ carreraId: '', f: '', facultadId: '', planId: '', q: '' }}
|
||||
className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30">
|
||||
className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30"
|
||||
>
|
||||
<Icons.BookOpen className="w-4 h-4" /> Nueva asignatura
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
to="/usuarios"
|
||||
className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30"
|
||||
>
|
||||
<Link to="/usuarios" className="inline-flex items-center gap-2 rounded-xl bg-white/20 border border-white/30 px-3 py-1.5 text-sm hover:bg-white/30">
|
||||
<Icons.UserPlus className="w-4 h-4" /> Invitar usuario
|
||||
</Link>
|
||||
)}
|
||||
@@ -303,21 +296,9 @@ function RouteComponent() {
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<HealthRow
|
||||
to="/_authenticated/asignaturas?f=sinBibliografia"
|
||||
label="Sin bibliografía"
|
||||
value={saludAsignaturas.sinBibliografia}
|
||||
/>
|
||||
<HealthRow
|
||||
to="/_authenticated/asignaturas?f=sinCriterios"
|
||||
label="Sin criterios de evaluación"
|
||||
value={saludAsignaturas.sinCriterios}
|
||||
/>
|
||||
<HealthRow
|
||||
to="/_authenticated/asignaturas?f=sinContenidos"
|
||||
label="Sin contenidos"
|
||||
value={saludAsignaturas.sinContenidos}
|
||||
/>
|
||||
<HealthRow to="/_authenticated/asignaturas?f=sinBibliografia" label="Sin bibliografía" value={saludAsignaturas.sinBibliografia} />
|
||||
<HealthRow to="/_authenticated/asignaturas?f=sinCriterios" label="Sin criterios de evaluación" value={saludAsignaturas.sinCriterios} />
|
||||
<HealthRow to="/_authenticated/asignaturas?f=sinContenidos" label="Sin contenidos" value={saludAsignaturas.sinContenidos} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -330,11 +311,9 @@ function RouteComponent() {
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{recientes.length === 0 && (
|
||||
<div className="text-sm text-neutral-500">Sin actividad registrada.</div>
|
||||
)}
|
||||
{recientes.length === 0 && <div className="text-sm text-neutral-500">Sin actividad registrada.</div>}
|
||||
<ul className="divide-y">
|
||||
{recientes.map(r => (
|
||||
{recientes.map((r) => (
|
||||
<li key={`${r.tipo}-${r.id}`} className="py-2 flex items-center justify-between gap-3">
|
||||
<Link
|
||||
to={r.tipo === 'plan' ? '/plan/$planId' : '/asignatura/$asignaturaId'}
|
||||
@@ -349,9 +328,7 @@ function RouteComponent() {
|
||||
)}
|
||||
<span className="truncate">{r.nombre}</span>
|
||||
</Link>
|
||||
<span className="text-xs text-neutral-500">
|
||||
{r.fecha ? new Date(r.fecha).toLocaleDateString() : ''}
|
||||
</span>
|
||||
<span className="text-xs text-neutral-500">{r.fecha ? new Date(r.fecha).toLocaleDateString() : ''}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -367,10 +344,9 @@ function HealthRow({ label, value, to }: { label: string; value: number; to: str
|
||||
return (
|
||||
<Link
|
||||
to={to}
|
||||
className={`flex items-center justify-between rounded-xl px-4 py-3 ring-1 ${warn
|
||||
? 'ring-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100'
|
||||
: 'ring-neutral-200 hover:bg-neutral-50'
|
||||
} transition-colors`}
|
||||
className={`flex items-center justify-between rounded-xl px-4 py-3 ring-1 ${
|
||||
warn ? 'ring-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100' : 'ring-neutral-200 hover:bg-neutral-50'
|
||||
} transition-colors`}
|
||||
>
|
||||
<span className="text-sm">{label}</span>
|
||||
<span className="text-lg font-semibold tabular-nums">{value}</span>
|
||||
|
||||
Reference in New Issue
Block a user