Merge branch 'fix/Incidencias'
This commit is contained in:
@@ -1,357 +1,406 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Send, Sparkles, Bot, User, Check, X, RefreshCw, Lightbulb, Wand2 } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { useRouterState } from '@tanstack/react-router'
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from '@/components/ui/command';
|
||||
import type { IAMessage, IASugerencia, CampoEstructura } from '@/types/materia';
|
||||
import { cn } from '@/lib/utils';
|
||||
//import { toast } from 'sonner';
|
||||
Sparkles,
|
||||
Send,
|
||||
Target,
|
||||
UserCheck,
|
||||
Lightbulb,
|
||||
FileText,
|
||||
GraduationCap,
|
||||
BookOpen,
|
||||
Check,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import { useState, useEffect, useRef, useMemo } from 'react'
|
||||
|
||||
interface IAMateriaTabProps {
|
||||
campos: CampoEstructura[];
|
||||
datosGenerales: Record<string, any>;
|
||||
messages: IAMessage[];
|
||||
onSendMessage: (message: string, campoId?: string) => void;
|
||||
onAcceptSuggestion: (sugerencia: IASugerencia) => void;
|
||||
onRejectSuggestion: (messageId: string) => void;
|
||||
import type { IAMessage, IASugerencia, CampoEstructura } from '@/types/materia'
|
||||
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// Tipos importados de tu archivo de materia
|
||||
|
||||
const PRESETS = [
|
||||
{
|
||||
id: 'mejorar-objetivo',
|
||||
label: 'Mejorar objetivo',
|
||||
icon: Target,
|
||||
prompt: 'Mejora la redacción del objetivo de esta asignatura...',
|
||||
},
|
||||
{
|
||||
id: 'contenido-tematico',
|
||||
label: 'Sugerir contenido',
|
||||
icon: BookOpen,
|
||||
prompt: 'Genera un desglose de temas para esta materia...',
|
||||
},
|
||||
{
|
||||
id: 'actividades',
|
||||
label: 'Actividades de aprendizaje',
|
||||
icon: GraduationCap,
|
||||
prompt: 'Sugiere actividades prácticas para los temas seleccionados...',
|
||||
},
|
||||
{
|
||||
id: 'bibliografia',
|
||||
label: 'Actualizar bibliografía',
|
||||
icon: FileText,
|
||||
prompt: 'Recomienda bibliografía reciente para esta asignatura...',
|
||||
},
|
||||
]
|
||||
|
||||
interface SelectedField {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
const quickActions = [
|
||||
{ id: 'mejorar-objetivos', label: 'Mejorar objetivos', icon: Wand2, prompt: 'Mejora el :objetivo_general para que sea más específico y medible' },
|
||||
{ id: 'generar-contenido', label: 'Generar contenido temático', icon: Lightbulb, prompt: 'Sugiere un contenido temático completo basado en los objetivos y competencias' },
|
||||
{ id: 'alinear-perfil', label: 'Alinear con perfil de egreso', icon: RefreshCw, prompt: 'Revisa las :competencias y alinéalas con el perfil de egreso del plan' },
|
||||
{ id: 'ajustar-biblio', label: 'Recomendar bibliografía', icon: Sparkles, prompt: 'Recomienda bibliografía actualizada basándote en el contenido temático' },
|
||||
];
|
||||
interface IAMateriaTabProps {
|
||||
campos: Array<CampoEstructura>
|
||||
datosGenerales: Record<string, any>
|
||||
messages: Array<IAMessage>
|
||||
onSendMessage: (message: string, campoId?: string) => void
|
||||
onAcceptSuggestion: (sugerencia: IASugerencia) => void
|
||||
onRejectSuggestion: (messageId: string) => void
|
||||
}
|
||||
|
||||
export function IAMateriaTab({ campos, datosGenerales, messages, onSendMessage, onAcceptSuggestion, onRejectSuggestion }: IAMateriaTabProps) {
|
||||
const [input, setInput] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [showFieldSelector, setShowFieldSelector] = useState(false);
|
||||
const [fieldSelectorPosition, setFieldSelectorPosition] = useState({ top: 0, left: 0 });
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
export function IAMateriaTab({
|
||||
campos,
|
||||
datosGenerales,
|
||||
messages,
|
||||
onSendMessage,
|
||||
onAcceptSuggestion,
|
||||
onRejectSuggestion,
|
||||
}: IAMateriaTabProps) {
|
||||
const routerState = useRouterState()
|
||||
|
||||
// ESTADOS PRINCIPALES (Igual que en Planes)
|
||||
const [input, setInput] = useState('')
|
||||
const [selectedFields, setSelectedFields] = useState<Array<SelectedField>>([])
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// 1. Transformar datos de la materia para el menú
|
||||
const availableFields = useMemo(() => {
|
||||
// Extraemos las claves directamente del objeto datosGenerales
|
||||
// ["nombre", "descripcion", "perfil_de_egreso", "fines_de_aprendizaje_o_formacion"]
|
||||
return Object.keys(datosGenerales).map((key) => {
|
||||
// Buscamos si existe un nombre amigable en la estructura de campos
|
||||
const estructuraCampo = campos.find((c) => c.id === key)
|
||||
|
||||
// Si existe en 'campos', usamos su nombre; si no, formateamos la clave (ej: perfil_de_egreso -> Perfil De Egreso)
|
||||
const labelAmigable =
|
||||
estructuraCampo?.nombre ||
|
||||
key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())
|
||||
|
||||
return {
|
||||
key: key,
|
||||
label: labelAmigable,
|
||||
value: String(datosGenerales[key] || ''),
|
||||
}
|
||||
})
|
||||
}, [campos, datosGenerales])
|
||||
|
||||
// 2. Manejar el estado inicial si viene de "Datos de Materia" (Prefill)
|
||||
|
||||
useEffect(() => {
|
||||
const state = routerState.location.state as any
|
||||
|
||||
if (state?.prefillCampo && availableFields.length > 0) {
|
||||
const field = availableFields.find((f) => f.key === state.prefillCampo)
|
||||
|
||||
if (field && !selectedFields.find((sf) => sf.key === field.key)) {
|
||||
setSelectedFields([field])
|
||||
// Sincronizamos el texto inicial con el campo pre-seleccionado
|
||||
setInput(`Mejora el campo ${field.key}: `)
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [availableFields])
|
||||
|
||||
// Scroll automático
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
|
||||
}
|
||||
}, [messages]);
|
||||
}, [messages, isLoading])
|
||||
|
||||
// 3. Lógica para el disparador ":"
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
const pos = e.target.selectionStart;
|
||||
setInput(value);
|
||||
setCursorPosition(pos);
|
||||
const val = e.target.value
|
||||
setInput(val)
|
||||
setShowSuggestions(val.endsWith(':'))
|
||||
}
|
||||
|
||||
// Check for : character to trigger field selector
|
||||
const lastChar = value.charAt(pos - 1);
|
||||
if (lastChar === ':') {
|
||||
const rect = textareaRef.current?.getBoundingClientRect();
|
||||
if (rect) {
|
||||
setFieldSelectorPosition({ top: rect.bottom + 8, left: rect.left });
|
||||
setShowFieldSelector(true);
|
||||
const toggleField = (field: SelectedField) => {
|
||||
setSelectedFields((prev) => {
|
||||
const isSelected = prev.find((f) => f.key === field.key)
|
||||
|
||||
// Si lo estamos seleccionando (no estaba antes)
|
||||
if (!isSelected) {
|
||||
// Actualizamos el texto del input:
|
||||
// Si termina en ":", lo reemplazamos por el key para que sea "Mejora perfil_de_egreso "
|
||||
// Si no, simplemente lo añadimos al final.
|
||||
setInput((prevText) => {
|
||||
const [beforeColon, afterColon = ''] = prevText.split(':')
|
||||
|
||||
// Campos ya escritos después de :
|
||||
const existingKeys = afterColon
|
||||
.split(',')
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
// Si ya existe, no lo volvemos a agregar
|
||||
if (existingKeys.includes(field.key)) {
|
||||
return prevText
|
||||
}
|
||||
|
||||
const updatedKeys = [...existingKeys, field.key].join(', ')
|
||||
|
||||
return `${beforeColon.trim()}: ${updatedKeys} `
|
||||
})
|
||||
|
||||
return [field]
|
||||
}
|
||||
} else if (showFieldSelector && (lastChar === ' ' || !value.includes(':'))) {
|
||||
setShowFieldSelector(false);
|
||||
}
|
||||
};
|
||||
|
||||
const insertFieldMention = (campoId: string) => {
|
||||
const beforeCursor = input.slice(0, cursorPosition);
|
||||
const afterCursor = input.slice(cursorPosition);
|
||||
const lastColonIndex = beforeCursor.lastIndexOf(':');
|
||||
const newInput = beforeCursor.slice(0, lastColonIndex) + `:${campoId}` + afterCursor;
|
||||
setInput(newInput);
|
||||
setShowFieldSelector(false);
|
||||
textareaRef.current?.focus();
|
||||
};
|
||||
// Si lo estamos deseleccionando, solo quitamos el tag
|
||||
return prev.filter((f) => f.key !== field.key)
|
||||
})
|
||||
setShowSuggestions(false)
|
||||
}
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim() || isLoading) return;
|
||||
const buildPrompt = (userInput: string) => {
|
||||
if (selectedFields.length === 0) return userInput
|
||||
const fieldsText = selectedFields
|
||||
.map((f) => `- ${f.label}: ${f.value || '(vacio)'}`)
|
||||
.join('\n')
|
||||
|
||||
// Extract field mention if any
|
||||
const fieldMatch = input.match(/:(\w+)/);
|
||||
const campoId = fieldMatch ? fieldMatch[1] : undefined;
|
||||
return `${userInput}\n\nCampos a analizar:\n${fieldsText}`.trim()
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
onSendMessage(input, campoId);
|
||||
setInput('');
|
||||
const handleSend = async (promptOverride?: string) => {
|
||||
const rawText = promptOverride || input
|
||||
if (!rawText.trim() && selectedFields.length === 0) return
|
||||
|
||||
// Simulate AI response delay
|
||||
setTimeout(() => {
|
||||
setIsLoading(false);
|
||||
}, 1500);
|
||||
};
|
||||
const finalPrompt = buildPrompt(rawText)
|
||||
|
||||
const handleQuickAction = (prompt: string) => {
|
||||
setInput(prompt);
|
||||
textareaRef.current?.focus();
|
||||
};
|
||||
setIsLoading(true)
|
||||
// Llamamos a la función que viene por props
|
||||
onSendMessage(finalPrompt, selectedFields[0]?.key)
|
||||
|
||||
const renderMessageContent = (content: string) => {
|
||||
// Render field mentions as styled badges
|
||||
return content.split(/(:[\w_]+)/g).map((part, i) => {
|
||||
if (part.startsWith(':')) {
|
||||
const campo = campos.find(c => c.id === part.slice(1));
|
||||
return (
|
||||
<span key={i} className="field-mention mx-0.5">
|
||||
{campo?.nombre || part}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return part;
|
||||
});
|
||||
};
|
||||
setInput('')
|
||||
setSelectedFields([])
|
||||
|
||||
// Simular carga local para el feedback visual
|
||||
setTimeout(() => setIsLoading(false), 1200)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-display text-2xl font-semibold text-foreground flex items-center gap-2">
|
||||
<Sparkles className="w-6 h-6 text-accent" />
|
||||
IA de la materia
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Usa <kbd className="px-1.5 py-0.5 bg-muted rounded text-xs font-mono">:</kbd> para mencionar campos específicos
|
||||
</p>
|
||||
<div className="flex h-[calc(100vh-160px)] max-h-[calc(100vh-160px)] w-full gap-6 overflow-hidden p-4">
|
||||
{/* PANEL DE CHAT PRINCIPAL */}
|
||||
<div className="relative flex min-w-0 flex-[3] flex-col overflow-hidden rounded-xl border border-slate-200 bg-slate-50/50 shadow-sm">
|
||||
{/* Barra superior */}
|
||||
<div className="shrink-0 border-b bg-white p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[10px] font-bold tracking-wider text-slate-400 uppercase">
|
||||
IA de Asignatura
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Chat area */}
|
||||
<Card className="lg:col-span-2 card-elevated flex flex-col h-[600px]">
|
||||
<CardHeader className="pb-2 border-b">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
Conversación
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1 flex flex-col p-0">
|
||||
<ScrollArea className="flex-1 p-4" ref={scrollRef}>
|
||||
<div className="space-y-4">
|
||||
{messages.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Bot className="w-12 h-12 mx-auto text-muted-foreground/50 mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
Inicia una conversación para mejorar tu materia con IA
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((message) => (
|
||||
<div key={message.id} className={cn(
|
||||
"flex gap-3",
|
||||
message.role === 'user' ? "justify-end" : "justify-start"
|
||||
)}>
|
||||
{message.role === 'assistant' && (
|
||||
<div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center flex-shrink-0">
|
||||
<Bot className="w-4 h-4 text-accent" />
|
||||
</div>
|
||||
{/* CONTENIDO DEL CHAT */}
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<ScrollArea ref={scrollRef} className="h-full w-full">
|
||||
<div className="mx-auto max-w-3xl space-y-6 p-6">
|
||||
{messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`flex ${msg.role === 'user' ? 'flex-row-reverse' : 'flex-row'} items-start gap-3`}
|
||||
>
|
||||
<Avatar
|
||||
className={`h-8 w-8 shrink-0 border ${msg.role === 'assistant' ? 'bg-teal-50' : 'bg-slate-200'}`}
|
||||
>
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{msg.role === 'assistant' ? (
|
||||
<Sparkles size={14} className="text-teal-600" />
|
||||
) : (
|
||||
<UserCheck size={14} />
|
||||
)}
|
||||
<div className={cn(
|
||||
"max-w-[80%] rounded-lg px-4 py-3",
|
||||
message.role === 'user'
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted"
|
||||
)}>
|
||||
<p className="text-sm whitespace-pre-wrap">
|
||||
{renderMessageContent(message.content)}
|
||||
</p>
|
||||
{message.sugerencia && !message.sugerencia.aceptada && (
|
||||
<div className="mt-3 p-3 bg-background/80 rounded-md border">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">
|
||||
Sugerencia para: {message.sugerencia.campoNombre}
|
||||
</p>
|
||||
<div className="text-sm text-foreground bg-accent/10 p-2 rounded mb-3 max-h-32 overflow-y-auto">
|
||||
{message.sugerencia.valorSugerido}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => onAcceptSuggestion(message.sugerencia!)}
|
||||
className="bg-success hover:bg-success/90 text-success-foreground"
|
||||
>
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
Aplicar
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => onRejectSuggestion(message.id)}
|
||||
>
|
||||
<X className="w-3 h-3 mr-1" />
|
||||
Rechazar
|
||||
</Button>
|
||||
</div>
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div
|
||||
className={`flex max-w-[85%] flex-col ${msg.role === 'user' ? 'items-end' : 'items-start'}`}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-2xl p-3 text-sm whitespace-pre-wrap shadow-sm',
|
||||
msg.role === 'user'
|
||||
? 'rounded-tr-none bg-teal-600 text-white'
|
||||
: 'rounded-tl-none border bg-white text-slate-700',
|
||||
)}
|
||||
>
|
||||
{msg.content}
|
||||
</div>
|
||||
|
||||
{/* Renderizado de Sugerencias (Homologado con lógica de Materia) */}
|
||||
{msg.sugerencia && !msg.sugerencia.aceptada && (
|
||||
<div className="animate-in fade-in slide-in-from-top-1 mt-3 w-full">
|
||||
<div className="rounded-xl border border-teal-100 bg-white p-4 shadow-md">
|
||||
<p className="mb-2 text-[10px] font-bold text-slate-400 uppercase">
|
||||
Propuesta para: {msg.sugerencia.campoNombre}
|
||||
</p>
|
||||
<div className="mb-4 max-h-40 overflow-y-auto rounded-lg bg-slate-50 p-3 text-xs text-slate-600 italic">
|
||||
{msg.sugerencia.valorSugerido}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
onAcceptSuggestion(msg.sugerencia!)
|
||||
}
|
||||
className="h-8 bg-teal-600 text-xs hover:bg-teal-700"
|
||||
>
|
||||
<Check size={14} className="mr-1" /> Aplicar
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => onRejectSuggestion(msg.id)}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<X size={14} className="mr-1" /> Descartar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{message.sugerencia?.aceptada && (
|
||||
<Badge className="mt-2 badge-library">
|
||||
<Check className="w-3 h-3 mr-1" />
|
||||
Sugerencia aplicada
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{message.role === 'user' && (
|
||||
<div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
|
||||
<User className="w-4 h-4 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{isLoading && (
|
||||
<div className="flex gap-3">
|
||||
<div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center flex-shrink-0">
|
||||
<Bot className="w-4 h-4 text-accent animate-pulse" />
|
||||
</div>
|
||||
<div className="bg-muted rounded-lg px-4 py-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="w-2 h-2 bg-accent rounded-full animate-bounce [animation-delay:-0.3s]" />
|
||||
<div className="w-2 h-2 bg-accent rounded-full animate-bounce [animation-delay:-0.15s]" />
|
||||
<div className="w-2 h-2 bg-accent rounded-full animate-bounce" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{msg.sugerencia?.aceptada && (
|
||||
<Badge className="mt-2 border-teal-200 bg-teal-100 text-teal-700 hover:bg-teal-100">
|
||||
<Check className="mr-1 h-3 w-3" /> Sugerencia aplicada
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
))}
|
||||
{isLoading && (
|
||||
<div className="flex gap-2 p-4">
|
||||
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400" />
|
||||
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400 [animation-delay:0.2s]" />
|
||||
<div className="h-2 w-2 animate-bounce rounded-full bg-teal-400 [animation-delay:0.4s]" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Input area */}
|
||||
<div className="p-4 border-t">
|
||||
<div className="relative">
|
||||
{/* INPUT FIJO AL FONDO */}
|
||||
<div className="shrink-0 border-t bg-white p-4">
|
||||
<div className="relative mx-auto max-w-4xl">
|
||||
{/* MENÚ DE SUGERENCIAS FLOTANTE */}
|
||||
{showSuggestions && (
|
||||
<div className="animate-in slide-in-from-bottom-2 absolute bottom-full z-50 mb-2 w-72 overflow-hidden rounded-xl border bg-white shadow-2xl">
|
||||
<div className="border-b bg-slate-50 px-3 py-2 text-[10px] font-bold tracking-wider text-slate-500 uppercase">
|
||||
Seleccionar campo de materia
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto p-1">
|
||||
{availableFields.map((field) => (
|
||||
<button
|
||||
key={field.key}
|
||||
onClick={() => toggleField(field)}
|
||||
className="group flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-teal-50"
|
||||
>
|
||||
<span className="text-slate-700 group-hover:text-teal-700">
|
||||
{field.label}
|
||||
</span>
|
||||
{selectedFields.find((f) => f.key === field.key) && (
|
||||
<Check size={14} className="text-teal-600" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* CONTENEDOR DEL INPUT */}
|
||||
<div className="flex flex-col gap-2 rounded-xl border bg-slate-50 p-2 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-teal-500">
|
||||
{/* Visualización de Tags */}
|
||||
{selectedFields.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-2 pt-1">
|
||||
{selectedFields.map((field) => (
|
||||
<div
|
||||
key={field.key}
|
||||
className="animate-in zoom-in-95 flex items-center gap-1 rounded-md border border-teal-200 bg-teal-100 px-2 py-0.5 text-[11px] font-semibold text-teal-800"
|
||||
>
|
||||
<span className="opacity-70">Campo:</span> {field.label}
|
||||
<button
|
||||
onClick={() => toggleField(field)}
|
||||
className="ml-1 rounded-full p-0.5 transition-colors hover:bg-teal-200"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}}
|
||||
placeholder="Escribe tu mensaje... Usa : para mencionar campos"
|
||||
className="min-h-[80px] pr-12 resize-none"
|
||||
disabled={isLoading}
|
||||
placeholder={
|
||||
selectedFields.length > 0
|
||||
? 'Instrucciones para los campos seleccionados...'
|
||||
: 'Escribe tu solicitud o ":" para campos...'
|
||||
}
|
||||
className="max-h-[120px] min-h-[40px] flex-1 resize-none border-none bg-transparent py-2 text-sm shadow-none focus-visible:ring-0"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSend}
|
||||
disabled={!input.trim() || isLoading}
|
||||
className="absolute bottom-3 right-3 h-8 w-8 p-0"
|
||||
onClick={() => handleSend()}
|
||||
disabled={
|
||||
(!input.trim() && selectedFields.length === 0) || isLoading
|
||||
}
|
||||
size="icon"
|
||||
className="mb-1 h-9 w-9 shrink-0 bg-teal-600 hover:bg-teal-700"
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
<Send size={16} className="text-white" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Field selector popover */}
|
||||
{showFieldSelector && (
|
||||
<div className="absolute z-50 mt-1 w-64 bg-popover border rounded-lg shadow-lg">
|
||||
<Command>
|
||||
<CommandInput placeholder="Buscar campo..." />
|
||||
<CommandList>
|
||||
<CommandEmpty>No se encontró el campo</CommandEmpty>
|
||||
<CommandGroup heading="Campos disponibles">
|
||||
{campos.map((campo) => (
|
||||
<CommandItem
|
||||
key={campo.id}
|
||||
value={campo.id}
|
||||
onSelect={() => insertFieldMention(campo.id)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<span className="font-mono text-xs text-accent mr-2">
|
||||
:{campo.id}
|
||||
</span>
|
||||
<span>{campo.nombre}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar with quick actions and fields */}
|
||||
<div className="space-y-4">
|
||||
{/* Quick actions */}
|
||||
<Card className="card-elevated">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Acciones rápidas</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{quickActions.map((action) => {
|
||||
const Icon = action.icon;
|
||||
return (
|
||||
<Button
|
||||
key={action.id}
|
||||
variant="outline"
|
||||
className="w-full justify-start text-left h-auto py-3"
|
||||
onClick={() => handleQuickAction(action.prompt)}
|
||||
>
|
||||
<Icon className="w-4 h-4 mr-2 text-accent flex-shrink-0" />
|
||||
<span className="text-sm">{action.label}</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Available fields */}
|
||||
<Card className="card-elevated">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Campos de la materia</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ScrollArea className="h-[280px]">
|
||||
<div className="space-y-2">
|
||||
{campos.map((campo) => {
|
||||
const hasValue = !!datosGenerales[campo.id];
|
||||
return (
|
||||
<div
|
||||
key={campo.id}
|
||||
className={cn(
|
||||
"p-2 rounded-md border cursor-pointer transition-colors hover:bg-muted/50",
|
||||
hasValue ? "border-success/30" : "border-warning/30"
|
||||
)}
|
||||
onClick={() => {
|
||||
setInput(prev => prev + `:${campo.id} `);
|
||||
textareaRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-mono text-accent">:{campo.id}</span>
|
||||
{hasValue ? (
|
||||
<Badge variant="outline" className="text-xs text-success border-success/30">
|
||||
Completo
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-xs text-warning border-warning/30">
|
||||
Vacío
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-foreground mt-1">{campo.nombre}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* PANEL LATERAL (ACCIONES RÁPIDAS) */}
|
||||
<div className="flex flex-[1] flex-col gap-4 overflow-y-auto pr-2">
|
||||
<h4 className="flex items-center gap-2 text-left text-sm font-bold text-slate-800">
|
||||
<Lightbulb size={18} className="text-orange-500" /> Acciones rápidas
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{PRESETS.map((preset) => (
|
||||
<button
|
||||
key={preset.id}
|
||||
onClick={() => handleSend(preset.prompt)}
|
||||
className="group flex w-full items-center gap-3 rounded-xl border bg-white p-3 text-left text-sm shadow-sm transition-all hover:border-teal-500 hover:bg-teal-50"
|
||||
>
|
||||
<div className="rounded-lg bg-slate-100 p-2 text-slate-500 group-hover:bg-teal-100 group-hover:text-teal-600">
|
||||
<preset.icon size={16} />
|
||||
</div>
|
||||
<span className="leading-tight font-medium text-slate-700">
|
||||
{preset.label}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
createFileRoute,
|
||||
Link,
|
||||
useNavigate,
|
||||
useParams,
|
||||
useRouterState,
|
||||
} from '@tanstack/react-router'
|
||||
@@ -59,13 +60,17 @@ function EditableHeaderField({
|
||||
onSave: (val: string) => void
|
||||
className?: string
|
||||
}) {
|
||||
const textValue = String(value)
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
value={String(value)}
|
||||
value={textValue}
|
||||
// El truco es usar el atributo "size" o calcular el ancho dinámicamente
|
||||
style={{ width: `${Math.max(textValue.length, 1)}ch` }}
|
||||
onChange={(e) => onSave(e.target.value)}
|
||||
onBlur={(e) => onSave(e.target.value)}
|
||||
className={` w-[${String(value).length || 1}ch] max-w-[6ch] border-none bg-transparent text-center outline-none focus:ring-2 focus:ring-blue-400 ${className ?? ''} `}
|
||||
className={`border-none bg-transparent outline-none focus:ring-2 focus:ring-blue-400 ${className ?? ''}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -91,6 +96,7 @@ export default function MateriaDetailPage() {
|
||||
const [messages, setMessages] = useState<Array<IAMessage>>([])
|
||||
const [datosGenerales, setDatosGenerales] = useState({})
|
||||
const [campos, setCampos] = useState<Array<CampoEstructura>>([])
|
||||
const [activeTab, setActiveTab] = useState('datos')
|
||||
|
||||
// Dentro de MateriaDetailPage
|
||||
const [headerData, setHeaderData] = useState({
|
||||
@@ -100,6 +106,13 @@ export default function MateriaDetailPage() {
|
||||
ciclo: 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
// Si en el state de la ruta viene una pestaña específica, cámbiate a ella
|
||||
if (state?.activeTab) {
|
||||
setActiveTab(state.activeTab)
|
||||
}
|
||||
}, [state])
|
||||
|
||||
// Sincronizar cuando llegue la API
|
||||
useEffect(() => {
|
||||
if (asignaturasApi) {
|
||||
@@ -208,11 +221,23 @@ export default function MateriaDetailPage() {
|
||||
|
||||
<div className="flex flex-wrap gap-4 text-sm text-blue-200">
|
||||
<span className="flex items-center gap-1">
|
||||
<GraduationCap className="h-4 w-4" />
|
||||
{asignaturasApi?.planes_estudio?.datos?.nombre}
|
||||
<GraduationCap className="h-4 w-4 shrink-0" />
|
||||
{/* Eliminamos el max-w y dejamos que el flex-wrap haga su trabajo */}
|
||||
<EditableHeaderField
|
||||
value={asignaturasApi?.planes_estudio?.datos?.nombre || ''}
|
||||
onSave={(val) => handleUpdateHeader('plan_nombre', val)}
|
||||
className="min-w-[10ch] text-blue-100" // min-w para que sea clickeable si está vacío
|
||||
/>
|
||||
</span>
|
||||
<span>
|
||||
{asignaturasApi?.planes_estudio?.carreras?.facultades?.nombre}
|
||||
<span className="flex items-center gap-1">
|
||||
<EditableHeaderField
|
||||
value={
|
||||
asignaturasApi?.planes_estudio?.carreras?.facultades
|
||||
?.nombre || ''
|
||||
}
|
||||
onSave={(val) => handleUpdateHeader('facultad_nombre', val)}
|
||||
className="min-w-[10ch] text-blue-100"
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -258,7 +283,11 @@ export default function MateriaDetailPage() {
|
||||
{/* ================= TABS ================= */}
|
||||
<section className="border-b bg-white">
|
||||
<div className="mx-auto max-w-7xl px-6">
|
||||
<Tabs defaultValue="datos">
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={setActiveTab}
|
||||
className="w-full"
|
||||
>
|
||||
<TabsList className="h-auto gap-6 bg-transparent p-0">
|
||||
<TabsTrigger value="datos">Datos generales</TabsTrigger>
|
||||
<TabsTrigger value="contenido">Contenido temático</TabsTrigger>
|
||||
@@ -272,7 +301,11 @@ export default function MateriaDetailPage() {
|
||||
|
||||
{/* ================= TAB: DATOS GENERALES ================= */}
|
||||
<TabsContent value="datos">
|
||||
<DatosGenerales data={datosGenerales} isLoading={loadingAsig} />
|
||||
<DatosGenerales
|
||||
data={datosGenerales}
|
||||
isLoading={loadingAsig}
|
||||
asignaturaId={asignaturaId}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="contenido">
|
||||
@@ -330,10 +363,15 @@ export default function MateriaDetailPage() {
|
||||
|
||||
/* ================= TAB CONTENT ================= */
|
||||
interface DatosGeneralesProps {
|
||||
asignaturaId: string
|
||||
data: AsignaturaDatos
|
||||
isLoading: boolean
|
||||
}
|
||||
function DatosGenerales({ data, isLoading }: DatosGeneralesProps) {
|
||||
function DatosGenerales({
|
||||
data,
|
||||
isLoading,
|
||||
asignaturaId,
|
||||
}: DatosGeneralesProps) {
|
||||
const formatTitle = (key: string): string =>
|
||||
key.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())
|
||||
|
||||
@@ -360,7 +398,9 @@ function DatosGenerales({ data, isLoading }: DatosGeneralesProps) {
|
||||
{!isLoading &&
|
||||
Object.entries(data).map(([key, value]) => (
|
||||
<InfoCard
|
||||
asignaturaId={asignaturaId}
|
||||
key={key}
|
||||
clave={key}
|
||||
title={formatTitle(key)}
|
||||
initialContent={value}
|
||||
onEnhanceAI={(contenido) => {
|
||||
@@ -411,6 +451,8 @@ function DatosGenerales({ data, isLoading }: DatosGeneralesProps) {
|
||||
}
|
||||
|
||||
interface InfoCardProps {
|
||||
asignaturaId?: string
|
||||
clave: string
|
||||
title: string
|
||||
initialContent: any
|
||||
type?: 'text' | 'requirements' | 'evaluation'
|
||||
@@ -418,6 +460,8 @@ interface InfoCardProps {
|
||||
}
|
||||
|
||||
function InfoCard({
|
||||
asignaturaId,
|
||||
clave,
|
||||
title,
|
||||
initialContent,
|
||||
type = 'text',
|
||||
@@ -428,11 +472,27 @@ function InfoCard({
|
||||
const [tempText, setTempText] = useState(
|
||||
type === 'text' ? initialContent : JSON.stringify(initialContent, null, 2),
|
||||
)
|
||||
|
||||
const navigate = useNavigate()
|
||||
const handleSave = () => {
|
||||
setData(tempText)
|
||||
setIsEditing(false)
|
||||
}
|
||||
const handleIARequest = (data) => {
|
||||
console.log(data)
|
||||
console.log(asignaturaId)
|
||||
|
||||
navigate({
|
||||
to: '/planes/$planId/asignaturas/$asignaturaId',
|
||||
params: {
|
||||
asignaturaId: asignaturaId,
|
||||
},
|
||||
state: {
|
||||
activeTab: 'ia',
|
||||
prefillCampo: data,
|
||||
prefillContenido: data, // el contenido actual del card
|
||||
} as any,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="transition-all hover:border-slate-300">
|
||||
@@ -448,7 +508,7 @@ function InfoCard({
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-blue-500 hover:bg-blue-50 hover:text-blue-600"
|
||||
onClick={() => onEnhanceAI?.(data)} // Enviamos la data actual a la IA
|
||||
onClick={() => handleIARequest(clave)} // Enviamos la data actual a la IA
|
||||
title="Mejorar con IA"
|
||||
>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
|
||||
@@ -178,7 +178,7 @@ export async function plans_history(planId: UUID): Promise<Array<CambioPlan>> {
|
||||
const { data, error } = await supabase
|
||||
.from('cambios_plan')
|
||||
.select(
|
||||
'id,plan_estudio_id,cambiado_por,cambiado_en,tipo,campo,valor_anterior,valor_nuevo,interaccion_ia_id',
|
||||
'id,plan_estudio_id,cambiado_por,cambiado_en,tipo,campo,valor_anterior,valor_nuevo',
|
||||
)
|
||||
.eq('plan_estudio_id', planId)
|
||||
.order('cambiado_en', { ascending: false })
|
||||
|
||||
@@ -148,7 +148,7 @@ export interface FileRoutesByFullPath {
|
||||
'/login': typeof LoginRoute
|
||||
'/planes': typeof PlanesListaRouteRouteWithChildren
|
||||
'/demo/tanstack-query': typeof DemoTanstackQueryRoute
|
||||
'/planes/$planId': typeof PlanesPlanIdIndexRoute
|
||||
'/planes/$planId': typeof PlanesPlanIdDetalleRouteRouteWithChildren
|
||||
'/planes/$planId/asignaturas': typeof PlanesPlanIdAsignaturasListaRouteRouteWithChildren
|
||||
'/planes/nuevo': typeof PlanesListaNuevoRoute
|
||||
'/planes/$planId/': typeof PlanesPlanIdIndexRoute
|
||||
@@ -169,10 +169,6 @@ export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/planes': typeof PlanesListaRouteRouteWithChildren
|
||||
'/demo/tanstack-query': typeof DemoTanstackQueryRoute
|
||||
<<<<<<< HEAD
|
||||
'/planes/PlanesListRoute': typeof PlanesPlanesListRouteRoute
|
||||
=======
|
||||
>>>>>>> 4950f7efbf664bbd31ac8a673fe594af5baf07f6
|
||||
'/planes/$planId': typeof PlanesPlanIdIndexRoute
|
||||
'/planes/nuevo': typeof PlanesListaNuevoRoute
|
||||
'/planes/$planId/asignaturas/$asignaturaId': typeof PlanesPlanIdAsignaturasAsignaturaIdRouteRoute
|
||||
@@ -325,11 +321,7 @@ declare module '@tanstack/react-router' {
|
||||
'/planes/$planId/': {
|
||||
id: '/planes/$planId/'
|
||||
path: '/planes/$planId'
|
||||
<<<<<<< HEAD
|
||||
fullPath: '/planes/$planId/'
|
||||
=======
|
||||
fullPath: '/planes/$planId'
|
||||
>>>>>>> 4950f7efbf664bbd31ac8a673fe594af5baf07f6
|
||||
preLoaderRoute: typeof PlanesPlanIdIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
|
||||
@@ -6,6 +6,12 @@ import type { DatosGeneralesField } from '@/types/plan'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { usePlan } from '@/data'
|
||||
// import { toast } from 'sonner' // Asegúrate de tener sonner instalado o quita la línea
|
||||
export const Route = createFileRoute('/planes/$planId/_detalle/datos')({
|
||||
@@ -28,24 +34,41 @@ function DatosGeneralesPage() {
|
||||
|
||||
// Efecto para transformar data?.datos en el arreglo de campos
|
||||
useEffect(() => {
|
||||
// 2. Validación de seguridad para sourceData
|
||||
const sourceData = data?.datos
|
||||
const properties = data?.estructuras_plan?.definicion?.properties
|
||||
|
||||
if (sourceData && typeof sourceData === 'object') {
|
||||
const valores = data?.datos as Record<string, unknown>
|
||||
|
||||
if (properties && typeof properties === 'object') {
|
||||
const datosTransformados: Array<DatosGeneralesField> = Object.entries(
|
||||
sourceData,
|
||||
).map(([key, value], index) => ({
|
||||
id: (index + 1).toString(),
|
||||
label: formatLabel(key),
|
||||
// Forzamos el valor a string de forma segura
|
||||
value: typeof value === 'string' ? value : value?.toString() || '',
|
||||
requerido: true,
|
||||
tipo: 'texto',
|
||||
}))
|
||||
properties,
|
||||
).map(([key, schema], index) => {
|
||||
const rawValue = valores[key]
|
||||
|
||||
return {
|
||||
id: (index + 1).toString(),
|
||||
label: schema?.title || formatLabel(key),
|
||||
helperText: schema?.description || '',
|
||||
holder: schema?.examples || '',
|
||||
value:
|
||||
rawValue !== undefined && rawValue !== null ? String(rawValue) : '',
|
||||
|
||||
requerido: true,
|
||||
|
||||
// 👇 TIPO DE CAMPO
|
||||
tipo: Array.isArray(schema?.enum)
|
||||
? 'select'
|
||||
: schema?.type === 'number'
|
||||
? 'number'
|
||||
: 'texto',
|
||||
|
||||
opciones: schema?.enum || [],
|
||||
}
|
||||
})
|
||||
|
||||
setCampos(datosTransformados)
|
||||
}
|
||||
console.log(data)
|
||||
|
||||
console.log(properties)
|
||||
}, [data])
|
||||
|
||||
// 3. Manejadores de acciones (Ahora como funciones locales)
|
||||
@@ -105,37 +128,58 @@ function DatosGeneralesPage() {
|
||||
}`}
|
||||
>
|
||||
{/* Header de la Card */}
|
||||
<div className="flex items-center justify-between border-b bg-slate-50/50 px-5 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-medium text-slate-700">
|
||||
{campo.label}
|
||||
</h3>
|
||||
{campo.requerido && (
|
||||
<span className="text-xs text-red-500">*</span>
|
||||
<TooltipProvider>
|
||||
<div className="flex items-center justify-between border-b bg-slate-50/50 px-5 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<h3 className="cursor-help text-sm font-medium text-slate-700">
|
||||
{campo.label}
|
||||
</h3>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs text-xs">
|
||||
{campo.helperText || 'Información del campo'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{campo.requerido && (
|
||||
<span className="text-xs text-red-500">*</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isEditing && (
|
||||
<div className="flex gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-teal-600"
|
||||
onClick={() => handleIARequest(campo.value)}
|
||||
>
|
||||
<Sparkles size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Generar con IA</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(campo)}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Editar campo</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isEditing && (
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-teal-600"
|
||||
onClick={() => handleIARequest(campo.value)}
|
||||
>
|
||||
<Sparkles size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleEdit(campo)}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
{/* Contenido de la Card */}
|
||||
<div className="p-5">
|
||||
@@ -145,6 +189,7 @@ function DatosGeneralesPage() {
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
className="min-h-[120px]"
|
||||
placeholder={campo.holder}
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Clock,
|
||||
FileJson,
|
||||
} from 'lucide-react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -19,9 +20,34 @@ export const Route = createFileRoute('/planes/$planId/_detalle/documento')({
|
||||
|
||||
function RouteComponent() {
|
||||
const { planId } = useParams({ from: '/planes/$planId/_detalle/documento' })
|
||||
const handleDownloadPdf = async () => {
|
||||
console.log('entre aqui ')
|
||||
const [pdfUrl, setPdfUrl] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const loadPdfPreview = useCallback(async () => {
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const pdfBlob = await fetchPlanPdf({ plan_estudio_id: planId })
|
||||
const url = window.URL.createObjectURL(pdfBlob)
|
||||
|
||||
// Limpiar URL anterior si existe para evitar fugas de memoria
|
||||
if (pdfUrl) window.URL.revokeObjectURL(pdfUrl)
|
||||
|
||||
setPdfUrl(url)
|
||||
} catch (error) {
|
||||
console.error('Error cargando preview:', error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [planId])
|
||||
|
||||
useEffect(() => {
|
||||
loadPdfPreview()
|
||||
return () => {
|
||||
if (pdfUrl) window.URL.revokeObjectURL(pdfUrl)
|
||||
}
|
||||
}, [loadPdfPreview])
|
||||
|
||||
const handleDownloadPdf = async () => {
|
||||
try {
|
||||
const pdfBlob = await fetchPlanPdf({
|
||||
plan_estudio_id: planId,
|
||||
@@ -54,7 +80,12 @@ function RouteComponent() {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" className="gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
onClick={loadPdfPreview}
|
||||
>
|
||||
<RefreshCcw size={16} /> Regenerar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="gap-2">
|
||||
@@ -90,70 +121,42 @@ function RouteComponent() {
|
||||
</div>
|
||||
|
||||
{/* CONTENEDOR DEL DOCUMENTO (Visor) */}
|
||||
{/* CONTENEDOR DEL VISOR REAL */}
|
||||
<Card className="overflow-hidden border-slate-200 shadow-sm">
|
||||
<div className="flex items-center justify-between border-b bg-slate-100/50 p-2 px-4">
|
||||
<div className="flex items-center gap-2 text-xs font-medium text-slate-500">
|
||||
<FileText size={14} />
|
||||
Plan_Estudios_ISC_2024.pdf
|
||||
<FileText size={14} /> Preview_Documento.pdf
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="h-7 gap-1 text-xs">
|
||||
Abrir en nueva pestaña <ExternalLink size={12} />
|
||||
</Button>
|
||||
{pdfUrl && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={() => window.open(pdfUrl, '_blank')}
|
||||
>
|
||||
Abrir en nueva pestaña <ExternalLink size={12} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardContent className="flex min-h-[800px] justify-center bg-slate-200/50 p-0 py-8">
|
||||
{/* SIMULACIÓN DE HOJA DE PAPEL */}
|
||||
<div className="relative min-h-[1000px] w-full max-w-[800px] border bg-white p-12 shadow-2xl md:p-16">
|
||||
{/* Contenido del Plan */}
|
||||
<div className="mb-12 text-center">
|
||||
<p className="mb-1 text-xs font-bold tracking-widest text-slate-400 uppercase">
|
||||
Universidad Tecnológica
|
||||
</p>
|
||||
<h2 className="text-2xl font-bold text-slate-800">
|
||||
Plan de Estudios 2024
|
||||
</h2>
|
||||
<h3 className="text-lg font-semibold text-teal-700">
|
||||
Ingeniería en Sistemas Computacionales
|
||||
</h3>
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
Facultad de Ingeniería
|
||||
</p>
|
||||
<CardContent className="flex min-h-[800px] justify-center bg-slate-500 p-0">
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-4 text-white">
|
||||
<RefreshCcw size={40} className="animate-spin opacity-50" />
|
||||
<p className="animate-pulse">Generando vista previa del PDF...</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-8 text-slate-700">
|
||||
<section>
|
||||
<h4 className="mb-2 text-sm font-bold">1. Objetivo General</h4>
|
||||
<p className="text-justify text-sm leading-relaxed">
|
||||
Formar profesionales altamente capacitados en el desarrollo de
|
||||
soluciones tecnológicas innovadoras, con sólidos conocimientos
|
||||
en programación, bases de datos, redes y seguridad
|
||||
informática.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4 className="mb-2 text-sm font-bold">2. Perfil de Ingreso</h4>
|
||||
<p className="text-justify text-sm leading-relaxed">
|
||||
Egresados de educación media superior con conocimientos
|
||||
básicos de matemáticas, razonamiento lógico y habilidades de
|
||||
comunicación. Interés por la tecnología y la resolución de
|
||||
problemas.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4 className="mb-2 text-sm font-bold">3. Perfil de Egreso</h4>
|
||||
<p className="text-justify text-sm leading-relaxed">
|
||||
Profesional capaz de diseñar, desarrollar e implementar
|
||||
sistemas de software de calidad, administrar infraestructuras
|
||||
de red y liderar proyectos tecnológicos multidisciplinarios.
|
||||
</p>
|
||||
</section>
|
||||
) : pdfUrl ? (
|
||||
/* 3. VISOR DE PDF REAL */
|
||||
<iframe
|
||||
src={`${pdfUrl}#toolbar=0&navpanes=0`}
|
||||
className="h-[1000px] w-full max-w-[1000px] border-none shadow-2xl"
|
||||
title="PDF Preview"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center p-20 text-slate-400">
|
||||
No se pudo cargar la vista previa.
|
||||
</div>
|
||||
|
||||
{/* Marca de agua o decoración lateral (opcional) */}
|
||||
<div className="absolute top-0 left-0 h-full w-1 bg-slate-100" />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { format, formatDistanceToNow, parseISO } from 'date-fns'
|
||||
import { es } from 'date-fns/locale'
|
||||
import {
|
||||
GitBranch,
|
||||
Edit3,
|
||||
@@ -12,19 +13,17 @@ import {
|
||||
History,
|
||||
Calendar,
|
||||
} from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { usePlanHistorial } from '@/data/hooks/usePlans'
|
||||
import { format, formatDistanceToNow, parseISO } from 'date-fns'
|
||||
import { es } from 'date-fns/locale'
|
||||
|
||||
export const Route = createFileRoute('/planes/$planId/_detalle/historial')({
|
||||
component: RouteComponent,
|
||||
@@ -58,9 +57,7 @@ const getEventConfig = (tipo: string, campo: string) => {
|
||||
|
||||
function RouteComponent() {
|
||||
const { planId } = Route.useParams()
|
||||
const { data: rawData, isLoading } = usePlanHistorial(
|
||||
'0e0aea4d-b8b4-4e75-8279-6224c3ac769f',
|
||||
)
|
||||
const { data: rawData, isLoading } = usePlanHistorial(planId)
|
||||
|
||||
// ESTADOS PARA EL MODAL
|
||||
const [selectedEvent, setSelectedEvent] = useState<any>(null)
|
||||
|
||||
@@ -106,7 +106,7 @@ function RouteComponent() {
|
||||
if (field && !selectedFields.find((sf) => sf.key === field.key)) {
|
||||
setSelectedFields([field])
|
||||
}
|
||||
setInput(`Mejora este campo: `)
|
||||
setInput(`Mejora este campo: ${field?.label} `)
|
||||
}
|
||||
}, [availableFields])
|
||||
|
||||
@@ -121,46 +121,85 @@ function RouteComponent() {
|
||||
}
|
||||
}
|
||||
|
||||
const injectFieldsIntoInput = (
|
||||
input: string,
|
||||
fields: Array<SelectedField>,
|
||||
) => {
|
||||
const baseText = input.replace(/\[[^\]]+]/g, '').trim()
|
||||
|
||||
const tags = fields.map((f) => `[${f.label}]`).join(' ')
|
||||
|
||||
return `${baseText} ${tags}`.trim()
|
||||
}
|
||||
const toggleField = (field: SelectedField) => {
|
||||
setSelectedFields((prev) =>
|
||||
prev.find((f) => f.key === field.key)
|
||||
? prev.filter((f) => f.key !== field.key)
|
||||
: [...prev, field],
|
||||
)
|
||||
if (input.endsWith(':')) setInput(input.slice(0, -1))
|
||||
setSelectedFields((prev) => {
|
||||
let nextFields
|
||||
|
||||
if (prev.find((f) => f.key === field.key)) {
|
||||
nextFields = prev.filter((f) => f.key !== field.key)
|
||||
} else {
|
||||
nextFields = [...prev, field]
|
||||
}
|
||||
|
||||
setInput((prevInput) =>
|
||||
injectFieldsIntoInput(prevInput || 'Mejora este campo:', nextFields),
|
||||
)
|
||||
|
||||
return nextFields
|
||||
})
|
||||
|
||||
setShowSuggestions(false)
|
||||
}
|
||||
const buildPrompt = (userInput: string) => {
|
||||
if (selectedFields.length === 0) return userInput
|
||||
|
||||
const fieldsText = selectedFields
|
||||
.map((f) => `- ${f.label}: ${f.value || '(sin contenido)'}`)
|
||||
.join('\n')
|
||||
|
||||
return `
|
||||
${userInput || 'Mejora los siguientes campos:'}
|
||||
|
||||
Campos a analizar:
|
||||
${fieldsText}
|
||||
`.trim()
|
||||
}
|
||||
|
||||
const handleSend = async (promptOverride?: string) => {
|
||||
const textToSend = promptOverride || input
|
||||
if (!textToSend.trim() && selectedFields.length === 0) return
|
||||
const rawText = promptOverride || input
|
||||
if (!rawText.trim() && selectedFields.length === 0) return
|
||||
|
||||
const finalPrompt = buildPrompt(rawText)
|
||||
|
||||
const userMsg = {
|
||||
id: Date.now().toString(),
|
||||
role: 'user',
|
||||
content: textToSend,
|
||||
content: finalPrompt,
|
||||
}
|
||||
|
||||
setMessages((prev) => [...prev, userMsg])
|
||||
setInput('')
|
||||
setIsLoading(true)
|
||||
|
||||
// Aquí simularías la llamada a la API enviando 'selectedFields' como contexto
|
||||
setTimeout(() => {
|
||||
const mockText =
|
||||
'Sugerencia generada basada en los campos seleccionados...'
|
||||
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: Date.now().toString(),
|
||||
role: 'assistant',
|
||||
content: `He analizado ${selectedFields.length > 0 ? selectedFields.map((f) => f.label).join(', ') : 'tu solicitud'}. Aquí tienes una propuesta:\n\n${mockText}`,
|
||||
content: `He analizado ${selectedFields
|
||||
.map((f) => f.label)
|
||||
.join(', ')}. Aquí tienes una propuesta:\n\n${mockText}`,
|
||||
},
|
||||
])
|
||||
|
||||
setPendingSuggestion({ text: mockText })
|
||||
setIsLoading(false)
|
||||
}, 1200)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-160px)] max-h-[calc(100vh-160px)] w-full gap-6 overflow-hidden p-4">
|
||||
{/* PANEL DE CHAT PRINCIPAL */}
|
||||
@@ -169,27 +208,8 @@ function RouteComponent() {
|
||||
<div className="shrink-0 border-b bg-white p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[10px] font-bold text-slate-400 uppercase">
|
||||
Campos a mejorar:
|
||||
Mejorar con IA
|
||||
</span>
|
||||
{selectedFields.map((field) => (
|
||||
<div
|
||||
key={field.key}
|
||||
className="animate-in zoom-in-95 flex items-center gap-1.5 rounded-lg border border-teal-100 bg-teal-50 px-2 py-1 text-xs font-medium text-teal-700"
|
||||
>
|
||||
{field.label}
|
||||
<button
|
||||
onClick={() => toggleField(field)}
|
||||
className="hover:text-red-500"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{selectedFields.length === 0 && (
|
||||
<span className="text-xs text-slate-400 italic">
|
||||
Escribe ":" para añadir campos
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
CalendarDays,
|
||||
Save,
|
||||
} from 'lucide-react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, forwardRef } from 'react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -145,7 +145,7 @@ function RouteComponent() {
|
||||
{/* 3. Cards de Información con Context Menu */}
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<InfoCard
|
||||
icon={<GraduationCap className="text-slate-400" />}
|
||||
label="Nivel"
|
||||
@@ -221,31 +221,32 @@ function RouteComponent() {
|
||||
)
|
||||
}
|
||||
|
||||
function InfoCard({
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
isEditable,
|
||||
}: {
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
value: string | number | undefined
|
||||
isEditable?: boolean
|
||||
}) {
|
||||
const InfoCard = forwardRef<
|
||||
HTMLDivElement,
|
||||
{
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
value: string | number | undefined
|
||||
isEditable?: boolean
|
||||
} & React.HTMLAttributes<HTMLDivElement>
|
||||
>(function InfoCard(
|
||||
{ icon, label, value, isEditable, className, ...props },
|
||||
ref,
|
||||
) {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
{...props}
|
||||
className={`flex h-[72px] w-full items-center gap-4 rounded-xl border border-slate-200/60 bg-slate-50/50 p-4 shadow-sm transition-all ${
|
||||
isEditable
|
||||
? 'cursor-pointer hover:border-teal-200 hover:bg-white focus:outline-none focus-visible:ring-2 focus-visible:ring-teal-500/40'
|
||||
: ''
|
||||
}`}
|
||||
} ${className ?? ''}`}
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border bg-white shadow-sm">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
{' '}
|
||||
{/* min-w-0 es vital para que el truncate funcione en flex */}
|
||||
<p className="mb-0.5 truncate text-[10px] font-bold tracking-wider text-slate-400 uppercase">
|
||||
{label}
|
||||
</p>
|
||||
@@ -255,7 +256,7 @@ function InfoCard({
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
function Tab({
|
||||
to,
|
||||
|
||||
@@ -65,12 +65,15 @@ export interface Plan {
|
||||
estadoActual: PlanStatus
|
||||
}
|
||||
|
||||
export interface DatosGeneralesField {
|
||||
export type DatosGeneralesField = {
|
||||
id: string
|
||||
label: string
|
||||
helperText?: string
|
||||
holder?: string
|
||||
value: string
|
||||
tipo: 'texto' | 'lista' | 'parrafo'
|
||||
requerido: boolean
|
||||
tipo: 'texto' | 'parrafo' | 'lista' | 'number' | 'select'
|
||||
opciones?: Array<string>
|
||||
}
|
||||
|
||||
export interface CambioPlan {
|
||||
|
||||
Reference in New Issue
Block a user