Initial commit: Proyecto portal-requisicion-vacantes

This commit is contained in:
Isaac_Aracena
2026-06-12 16:08:49 -04:00
commit b5a16d8daf
112 changed files with 18334 additions and 0 deletions
+709
View File
@@ -0,0 +1,709 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Search,
Clock,
CheckCircle2,
XCircle,
AlertTriangle,
Eye,
MapPin,
Building2,
Users,
Calendar,
DollarSign,
FileText,
ThumbsUp,
ThumbsDown,
ArrowRight,
Filter,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { requisitions, countries, currentUser } from '@/lib/mock-data'
import { STATUS_CONFIG, URGENCY_CONFIG, type Requisition } from '@/lib/types'
import { toast } from 'sonner'
function getInitials(name: string): string {
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
}
function getDaysUntilDeadline(deadline: string): number {
const now = new Date()
const deadlineDate = new Date(deadline)
return Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
}
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString('es-ES', {
day: '2-digit',
month: 'short',
year: 'numeric',
})
}
function getDaysSinceCreated(dateString: string): number {
const now = new Date()
const created = new Date(dateString)
return Math.ceil((now.getTime() - created.getTime()) / (1000 * 60 * 60 * 24))
}
interface ApprovalCardProps {
requisition: Requisition
approvalType: 'rrhh' | 'admin'
onApprove: (req: Requisition) => void
onReject: (req: Requisition) => void
onView: (req: Requisition) => void
}
function ApprovalCard({ requisition, approvalType, onApprove, onReject, onView }: ApprovalCardProps) {
const urgency = URGENCY_CONFIG[requisition.urgency]
const daysLeft = getDaysUntilDeadline(requisition.hardDeadline)
const daysPending = getDaysSinceCreated(requisition.createdAt)
const isOverdue = daysLeft < 0
const isAtRisk = daysLeft >= 0 && daysLeft <= 7
const isPendingTooLong = daysPending > 2
return (
<Card className={cn(
'transition-all hover:shadow-md',
isPendingTooLong && 'border-amber-200 dark:border-amber-800',
requisition.urgency === 'critica' && 'border-red-200 dark:border-red-800'
)}>
<CardContent className="p-4">
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
{/* Header */}
<div className="flex items-center gap-2 mb-2">
<Link
href={`/requisiciones/${requisition.id}`}
className="font-semibold text-primary hover:underline"
>
{requisition.id}
</Link>
<Badge variant="outline" className={cn('text-xs', urgency.color, urgency.bgColor)}>
{urgency.label}
</Badge>
{isPendingTooLong && (
<Badge variant="outline" className="text-xs text-amber-600 bg-amber-50 border-amber-200">
<Clock className="mr-1 h-3 w-3" />
{daysPending}d pendiente
</Badge>
)}
</div>
{/* Position & Location */}
<h3 className="font-medium text-base mb-1">{requisition.positionName}</h3>
<div className="flex items-center gap-4 text-sm text-muted-foreground mb-3">
<span className="flex items-center gap-1">
<MapPin className="h-3.5 w-3.5" />
{requisition.cityName}, {requisition.countryName}
</span>
<span className="flex items-center gap-1">
<Building2 className="h-3.5 w-3.5" />
{requisition.departmentName}
</span>
<span className="flex items-center gap-1">
<Users className="h-3.5 w-3.5" />
{requisition.quantity} vacante{requisition.quantity > 1 ? 's' : ''}
</span>
</div>
{/* Justification Preview */}
<p className="text-sm text-muted-foreground line-clamp-2 mb-3">
{requisition.justification}
</p>
{/* Requester & SLA */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
<AvatarFallback className="text-xs">
{getInitials(requisition.requesterName)}
</AvatarFallback>
</Avatar>
<span className="text-sm text-muted-foreground">
{requisition.requesterName}
</span>
<span className="text-xs text-muted-foreground">
- {formatDate(requisition.createdAt)}
</span>
</div>
<div className={cn(
'flex items-center gap-1 text-sm',
isOverdue && 'text-red-600',
isAtRisk && !isOverdue && 'text-amber-600'
)}>
<Clock className="h-3.5 w-3.5" />
<span>
SLA: {isOverdue ? `${Math.abs(daysLeft)}d vencido` : `${daysLeft}d`}
</span>
</div>
</div>
{/* HR Approval Info (for Admin view) */}
{approvalType === 'admin' && requisition.approvedByHrAt && (
<div className="mt-3 pt-3 border-t">
<div className="flex items-center gap-2 text-sm text-emerald-600">
<CheckCircle2 className="h-4 w-4" />
<span>Aprobado por RR.HH. el {formatDate(requisition.approvedByHrAt)}</span>
</div>
</div>
)}
{/* Compensation (visible to authorized roles) */}
{(requisition.salaryPackage || requisition.budget) && (
<div className="mt-3 pt-3 border-t flex items-center gap-4 text-sm">
<DollarSign className="h-4 w-4 text-muted-foreground" />
{requisition.salaryPackage && (
<span>{requisition.salaryPackage}</span>
)}
{requisition.budget && (
<span className="text-muted-foreground">
Presupuesto: {requisition.currency} {requisition.budget.toLocaleString()}
</span>
)}
</div>
)}
</div>
{/* Action Buttons */}
<div className="flex flex-col gap-2">
<Button size="sm" onClick={() => onApprove(requisition)} className="bg-emerald-600 hover:bg-emerald-700">
<ThumbsUp className="mr-1 h-4 w-4" />
Aprobar
</Button>
<Button size="sm" variant="outline" onClick={() => onReject(requisition)} className="text-destructive hover:bg-destructive hover:text-destructive-foreground">
<ThumbsDown className="mr-1 h-4 w-4" />
Rechazar
</Button>
<Button size="sm" variant="ghost" onClick={() => onView(requisition)}>
<Eye className="mr-1 h-4 w-4" />
Ver más
</Button>
</div>
</div>
</CardContent>
</Card>
)
}
export function ApprovalsPage() {
const [searchTerm, setSearchTerm] = React.useState('')
const [countryFilter, setCountryFilter] = React.useState('all')
const [activeTab, setActiveTab] = React.useState<'rrhh' | 'admin'>('rrhh')
// Dialog states
const [selectedRequisition, setSelectedRequisition] = React.useState<Requisition | null>(null)
const [approveDialogOpen, setApproveDialogOpen] = React.useState(false)
const [rejectDialogOpen, setRejectDialogOpen] = React.useState(false)
const [detailDialogOpen, setDetailDialogOpen] = React.useState(false)
const [rejectComment, setRejectComment] = React.useState('')
const [approveComment, setApproveComment] = React.useState('')
// Filter requisitions based on approval type
const pendingHR = requisitions.filter(r => r.status === 'pendiente_rrhh')
const pendingAdmin = requisitions.filter(r => r.status === 'pendiente_admin')
const currentQueue = activeTab === 'rrhh' ? pendingHR : pendingAdmin
const filteredQueue = React.useMemo(() => {
let filtered = [...currentQueue]
if (searchTerm) {
const term = searchTerm.toLowerCase()
filtered = filtered.filter(r =>
r.id.toLowerCase().includes(term) ||
r.positionName.toLowerCase().includes(term) ||
r.requesterName.toLowerCase().includes(term)
)
}
if (countryFilter !== 'all') {
filtered = filtered.filter(r => r.countryId === countryFilter)
}
// Sort by urgency and then by date
filtered.sort((a, b) => {
const urgencyOrder = { critica: 0, alta: 1, normal: 2 }
const urgencyDiff = urgencyOrder[a.urgency] - urgencyOrder[b.urgency]
if (urgencyDiff !== 0) return urgencyDiff
return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
})
return filtered
}, [currentQueue, searchTerm, countryFilter])
const handleApprove = (requisition: Requisition) => {
setSelectedRequisition(requisition)
setApproveDialogOpen(true)
}
const handleReject = (requisition: Requisition) => {
setSelectedRequisition(requisition)
setRejectDialogOpen(true)
}
const handleView = (requisition: Requisition) => {
setSelectedRequisition(requisition)
setDetailDialogOpen(true)
}
const confirmApprove = () => {
if (!selectedRequisition) return
toast.success('Requisición aprobada', {
description: `${selectedRequisition.id} ha sido aprobada y pasará al siguiente paso.`,
})
setApproveDialogOpen(false)
setApproveComment('')
setSelectedRequisition(null)
}
const confirmReject = () => {
if (!selectedRequisition || !rejectComment.trim()) return
toast.success('Requisición devuelta', {
description: `${selectedRequisition.id} ha sido devuelta al solicitante para corrección.`,
})
setRejectDialogOpen(false)
setRejectComment('')
setSelectedRequisition(null)
}
return (
<div className="p-6 space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight">Aprobaciones</h1>
<p className="text-muted-foreground">
Gestiona las requisiciones pendientes de aprobación
</p>
</div>
</div>
{/* Stats Cards */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Pendientes RR.HH.</p>
<p className="text-2xl font-bold">{pendingHR.length}</p>
</div>
<div className="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
<Clock className="h-5 w-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Pendientes Admin</p>
<p className="text-2xl font-bold">{pendingAdmin.length}</p>
</div>
<div className="h-10 w-10 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
<Building2 className="h-5 w-5 text-purple-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Urgentes</p>
<p className="text-2xl font-bold text-red-600">
{[...pendingHR, ...pendingAdmin].filter(r => r.urgency === 'critica').length}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
<AlertTriangle className="h-5 w-5 text-red-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">{'>'}48h Pendientes</p>
<p className="text-2xl font-bold text-amber-600">
{[...pendingHR, ...pendingAdmin].filter(r => getDaysSinceCreated(r.createdAt) > 2).length}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
<Clock className="h-5 w-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
</div>
{/* Tabs */}
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'rrhh' | 'admin')}>
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<TabsList>
<TabsTrigger value="rrhh" className="gap-2">
<Users className="h-4 w-4" />
RR.HH. ({pendingHR.length})
</TabsTrigger>
<TabsTrigger value="admin" className="gap-2">
<Building2 className="h-4 w-4" />
Administración ({pendingAdmin.length})
</TabsTrigger>
</TabsList>
{/* Filters */}
<div className="flex items-center gap-2">
<div className="relative w-64">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Buscar requisición..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-9"
/>
</div>
<Select value={countryFilter} onValueChange={setCountryFilter}>
<SelectTrigger className="w-[160px]">
<Filter className="mr-2 h-4 w-4" />
<SelectValue placeholder="País" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los países</SelectItem>
{countries.map((country) => (
<SelectItem key={country.id} value={country.id}>
{country.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<TabsContent value="rrhh" className="mt-6">
{filteredQueue.length > 0 ? (
<div className="space-y-4">
{filteredQueue.map((requisition) => (
<ApprovalCard
key={requisition.id}
requisition={requisition}
approvalType="rrhh"
onApprove={handleApprove}
onReject={handleReject}
onView={handleView}
/>
))}
</div>
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<CheckCircle2 className="h-12 w-12 text-emerald-500 mb-4" />
<h3 className="text-lg font-semibold">Sin pendientes</h3>
<p className="text-sm text-muted-foreground">
No hay requisiciones pendientes de aprobación de RR.HH.
</p>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="admin" className="mt-6">
{filteredQueue.length > 0 ? (
<div className="space-y-4">
{filteredQueue.map((requisition) => (
<ApprovalCard
key={requisition.id}
requisition={requisition}
approvalType="admin"
onApprove={handleApprove}
onReject={handleReject}
onView={handleView}
/>
))}
</div>
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<CheckCircle2 className="h-12 w-12 text-emerald-500 mb-4" />
<h3 className="text-lg font-semibold">Sin pendientes</h3>
<p className="text-sm text-muted-foreground">
No hay requisiciones pendientes de aprobación de Administración
</p>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
{/* Approve Dialog */}
<Dialog open={approveDialogOpen} onOpenChange={setApproveDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Aprobar Requisición</DialogTitle>
<DialogDescription>
{selectedRequisition && (
<>
Estás por aprobar <strong>{selectedRequisition.id}</strong> - {selectedRequisition.positionName}
</>
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="approveComment">Comentario (opcional)</Label>
<Textarea
id="approveComment"
value={approveComment}
onChange={(e) => setApproveComment(e.target.value)}
placeholder="Agregar un comentario de aprobación..."
rows={3}
/>
</div>
{activeTab === 'rrhh' && (
<div className="rounded-lg bg-muted/50 p-3 text-sm">
<p className="text-muted-foreground">
Al aprobar, la requisición pasará a <strong>Pendiente Administración</strong> para aprobación financiera.
</p>
</div>
)}
{activeTab === 'admin' && (
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-950/30 p-3 text-sm border border-emerald-200 dark:border-emerald-800">
<p className="text-emerald-700 dark:text-emerald-300">
Al aprobar, la requisición pasará a <strong>Reclutando</strong> y se habilitará para asignar reclutador.
</p>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setApproveDialogOpen(false)}>
Cancelar
</Button>
<Button onClick={confirmApprove} className="bg-emerald-600 hover:bg-emerald-700">
<CheckCircle2 className="mr-2 h-4 w-4" />
Confirmar Aprobación
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Reject Dialog */}
<Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Rechazar / Solicitar Corrección</DialogTitle>
<DialogDescription>
{selectedRequisition && (
<>
La requisición <strong>{selectedRequisition.id}</strong> será devuelta al solicitante para corrección.
</>
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="rejectComment">Motivo del rechazo / corrección requerida *</Label>
<Textarea
id="rejectComment"
value={rejectComment}
onChange={(e) => setRejectComment(e.target.value)}
placeholder="Describe qué información falta o debe corregirse..."
rows={4}
/>
<p className="text-xs text-muted-foreground">
Este comentario será visible para el solicitante.
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setRejectDialogOpen(false)}>
Cancelar
</Button>
<Button
variant="destructive"
onClick={confirmReject}
disabled={!rejectComment.trim()}
>
<XCircle className="mr-2 h-4 w-4" />
Confirmar Rechazo
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Detail Dialog */}
<Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Detalle de Requisición</DialogTitle>
</DialogHeader>
{selectedRequisition && (
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
{/* Header Info */}
<div className="flex items-start justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<span className="font-semibold">{selectedRequisition.id}</span>
<Badge variant="outline" className={cn(
'text-xs',
URGENCY_CONFIG[selectedRequisition.urgency].color,
URGENCY_CONFIG[selectedRequisition.urgency].bgColor
)}>
{URGENCY_CONFIG[selectedRequisition.urgency].label}
</Badge>
</div>
<h3 className="text-lg font-semibold">{selectedRequisition.positionName}</h3>
</div>
</div>
<Separator />
{/* Details Grid */}
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Ubicación</p>
<p className="font-medium">{selectedRequisition.cityName}, {selectedRequisition.countryName}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Departamento</p>
<p className="font-medium">{selectedRequisition.departmentName}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Cantidad de Vacantes</p>
<p className="font-medium">{selectedRequisition.quantity}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Modalidad</p>
<p className="font-medium capitalize">{selectedRequisition.modalidad}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Tipo de Contratación</p>
<p className="font-medium capitalize">{selectedRequisition.tipoContratacion}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Fecha Límite SLA</p>
<p className="font-medium">{formatDate(selectedRequisition.hardDeadline)}</p>
</div>
</div>
<Separator />
{/* Justification */}
<div>
<h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
Justificación
</h4>
<p className="text-sm">{selectedRequisition.justification}</p>
</div>
{/* Compensation */}
{(selectedRequisition.salaryPackage || selectedRequisition.budget) && (
<>
<Separator />
<div>
<h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
Compensación
</h4>
<div className="grid gap-4 sm:grid-cols-2">
{selectedRequisition.salaryPackage && (
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Paquete Salarial</p>
<p className="font-medium">{selectedRequisition.salaryPackage}</p>
</div>
)}
{selectedRequisition.budget && (
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Presupuesto</p>
<p className="font-medium">
{selectedRequisition.currency} {selectedRequisition.budget.toLocaleString()}
</p>
</div>
)}
</div>
</div>
</>
)}
{/* Requester */}
<Separator />
<div className="flex items-center gap-3">
<Avatar>
<AvatarFallback>{getInitials(selectedRequisition.requesterName)}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{selectedRequisition.requesterName}</p>
<p className="text-sm text-muted-foreground">
Solicitante - {formatDate(selectedRequisition.createdAt)}
</p>
</div>
</div>
</div>
</ScrollArea>
)}
<DialogFooter className="flex-row gap-2 sm:justify-between">
<Button variant="outline" asChild>
<Link href={`/requisiciones/${selectedRequisition?.id}`}>
Ver página completa
<ArrowRight className="ml-2 h-4 w-4" />
</Link>
</Button>
<div className="flex gap-2">
<Button
variant="outline"
className="text-destructive"
onClick={() => {
setDetailDialogOpen(false)
if (selectedRequisition) handleReject(selectedRequisition)
}}
>
<ThumbsDown className="mr-2 h-4 w-4" />
Rechazar
</Button>
<Button
className="bg-emerald-600 hover:bg-emerald-700"
onClick={() => {
setDetailDialogOpen(false)
if (selectedRequisition) handleApprove(selectedRequisition)
}}
>
<ThumbsUp className="mr-2 h-4 w-4" />
Aprobar
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
+587
View File
@@ -0,0 +1,587 @@
"use client"
import { useState } from "react"
import { mockInterviews, mockCandidates, mockRequisitions, mockUsers } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Calendar } from "@/components/ui/calendar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
ChevronLeft,
ChevronRight,
Plus,
Video,
MapPin,
Clock,
User,
Calendar as CalendarIcon,
Users,
MoreVertical,
Mail,
Phone,
FileText,
CheckCircle2,
XCircle,
Edit,
Trash2,
ExternalLink
} from "lucide-react"
import { cn } from "@/lib/utils"
const weekDays = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"]
const monthNames = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
export function CalendarPage() {
const [currentDate, setCurrentDate] = useState(new Date())
const [selectedDate, setSelectedDate] = useState<Date | null>(null)
const [viewMode, setViewMode] = useState<"month" | "week" | "day">("month")
const [isNewInterviewOpen, setIsNewInterviewOpen] = useState(false)
const [selectedInterview, setSelectedInterview] = useState<typeof mockInterviews[0] | null>(null)
const [filterType, setFilterType] = useState<string>("all")
const interviews = mockInterviews
const getDaysInMonth = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth()
const firstDay = new Date(year, month, 1)
const lastDay = new Date(year, month + 1, 0)
const daysInMonth = lastDay.getDate()
const startingDay = firstDay.getDay()
const days: (Date | null)[] = []
for (let i = 0; i < startingDay; i++) {
days.push(null)
}
for (let i = 1; i <= daysInMonth; i++) {
days.push(new Date(year, month, i))
}
return days
}
const getInterviewsForDate = (date: Date) => {
return interviews.filter(interview => {
const interviewDate = new Date(interview.scheduledDate)
return (
interviewDate.getDate() === date.getDate() &&
interviewDate.getMonth() === date.getMonth() &&
interviewDate.getFullYear() === date.getFullYear()
)
}).filter(interview => {
if (filterType === "all") return true
return interview.type === filterType
})
}
const navigateMonth = (direction: "prev" | "next") => {
setCurrentDate(prev => {
const newDate = new Date(prev)
if (direction === "prev") {
newDate.setMonth(newDate.getMonth() - 1)
} else {
newDate.setMonth(newDate.getMonth() + 1)
}
return newDate
})
}
const getInterviewTypeColor = (type: string) => {
const colors: Record<string, string> = {
rrhh: "bg-primary text-primary-foreground",
technical: "bg-blue-500 text-white",
manager: "bg-purple-500 text-white",
final: "bg-accent text-accent-foreground"
}
return colors[type] || "bg-secondary text-secondary-foreground"
}
const getInterviewTypeLabel = (type: string) => {
const labels: Record<string, string> = {
rrhh: "RR.HH.",
technical: "Técnica",
manager: "Gerente",
final: "Final"
}
return labels[type] || type
}
const getCandidateName = (candidateId: string) => {
const candidate = mockCandidates.find(c => c.id === candidateId)
return candidate?.name || "Candidato"
}
const getRequisitionTitle = (requisitionId: string) => {
const requisition = mockRequisitions.find(r => r.id === requisitionId)
return requisition?.position || "Vacante"
}
const formatTime = (dateString: string) => {
const date = new Date(dateString)
return date.toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" })
}
const days = getDaysInMonth(currentDate)
const upcomingInterviews = interviews
.filter(i => new Date(i.scheduledDate) >= new Date())
.sort((a, b) => new Date(a.scheduledDate).getTime() - new Date(b.scheduledDate).getTime())
.slice(0, 5)
const todayInterviews = getInterviewsForDate(new Date())
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Calendario de Entrevistas</h1>
<p className="text-muted-foreground">
Gestiona y agenda entrevistas con candidatos
</p>
</div>
<Dialog open={isNewInterviewOpen} onOpenChange={setIsNewInterviewOpen}>
<DialogTrigger asChild>
<Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
<Plus className="mr-2 h-4 w-4" />
Agendar Entrevista
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Agendar Nueva Entrevista</DialogTitle>
<DialogDescription>
Programa una entrevista con un candidato
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="space-y-2">
<Label>Candidato</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar candidato" />
</SelectTrigger>
<SelectContent>
{mockCandidates.map(candidate => (
<SelectItem key={candidate.id} value={candidate.id}>
{candidate.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Tipo de Entrevista</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar tipo" />
</SelectTrigger>
<SelectContent>
<SelectItem value="rrhh">Entrevista RR.HH.</SelectItem>
<SelectItem value="technical">Entrevista Técnica</SelectItem>
<SelectItem value="manager">Entrevista Gerente</SelectItem>
<SelectItem value="final">Entrevista Final</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Fecha</Label>
<Input type="date" />
</div>
<div className="space-y-2">
<Label>Hora</Label>
<Input type="time" />
</div>
</div>
<div className="space-y-2">
<Label>Duracion (minutos)</Label>
<Select defaultValue="60">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="30">30 minutos</SelectItem>
<SelectItem value="45">45 minutos</SelectItem>
<SelectItem value="60">60 minutos</SelectItem>
<SelectItem value="90">90 minutos</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Modalidad</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar modalidad" />
</SelectTrigger>
<SelectContent>
<SelectItem value="video">Videoconferencia</SelectItem>
<SelectItem value="presencial">Presencial</SelectItem>
<SelectItem value="phone">Telefonica</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Entrevistadores</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar entrevistadores" />
</SelectTrigger>
<SelectContent>
{mockUsers.filter(u => u.role === "recruiter" || u.role === "hr_manager").map(user => (
<SelectItem key={user.id} value={user.id}>
{user.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Notas</Label>
<Textarea placeholder="Notas adicionales para la entrevista..." />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsNewInterviewOpen(false)}>
Cancelar
</Button>
<Button className="bg-accent hover:bg-accent/90" onClick={() => setIsNewInterviewOpen(false)}>
Agendar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
{/* Calendar */}
<div className="lg:col-span-3">
<Card>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button variant="outline" size="icon" onClick={() => navigateMonth("prev")}>
<ChevronLeft className="h-4 w-4" />
</Button>
<h2 className="text-xl font-semibold">
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
</h2>
<Button variant="outline" size="icon" onClick={() => navigateMonth("next")}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
<div className="flex items-center gap-2">
<Select value={filterType} onValueChange={setFilterType}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Filtrar por tipo" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los tipos</SelectItem>
<SelectItem value="rrhh">Entrevista RR.HH.</SelectItem>
<SelectItem value="technical">Entrevista Técnica</SelectItem>
<SelectItem value="manager">Entrevista Gerente</SelectItem>
<SelectItem value="final">Entrevista Final</SelectItem>
</SelectContent>
</Select>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentDate(new Date())}
>
Hoy
</Button>
</div>
</div>
</CardHeader>
<CardContent>
{/* Week Headers */}
<div className="grid grid-cols-7 gap-px mb-2">
{weekDays.map(day => (
<div key={day} className="text-center text-sm font-medium text-muted-foreground py-2">
{day}
</div>
))}
</div>
{/* Calendar Grid */}
<div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
{days.map((day, index) => {
const dayInterviews = day ? getInterviewsForDate(day) : []
const isToday = day &&
day.getDate() === new Date().getDate() &&
day.getMonth() === new Date().getMonth() &&
day.getFullYear() === new Date().getFullYear()
const isSelected = day && selectedDate &&
day.getDate() === selectedDate.getDate() &&
day.getMonth() === selectedDate.getMonth() &&
day.getFullYear() === selectedDate.getFullYear()
return (
<div
key={index}
className={cn(
"min-h-[120px] bg-card p-2 cursor-pointer transition-colors hover:bg-muted/50",
!day && "bg-muted/30",
isSelected && "ring-2 ring-primary ring-inset"
)}
onClick={() => day && setSelectedDate(day)}
>
{day && (
<>
<div className={cn(
"text-sm font-medium mb-1",
isToday && "w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center"
)}>
{day.getDate()}
</div>
<div className="space-y-1">
{dayInterviews.slice(0, 3).map(interview => (
<div
key={interview.id}
className={cn(
"text-xs p-1 rounded truncate cursor-pointer",
getInterviewTypeColor(interview.type)
)}
onClick={(e) => {
e.stopPropagation()
setSelectedInterview(interview)
}}
>
{formatTime(interview.scheduledDate)} - {getCandidateName(interview.candidateId)}
</div>
))}
{dayInterviews.length > 3 && (
<div className="text-xs text-muted-foreground text-center">
+{dayInterviews.length - 3} mas
</div>
)}
</div>
</>
)}
</div>
)
})}
</div>
</CardContent>
</Card>
</div>
{/* Sidebar */}
<div className="space-y-6">
{/* Today's Interviews */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Entrevistas de Hoy</CardTitle>
<CardDescription>{todayInterviews.length} programadas</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{todayInterviews.length > 0 ? todayInterviews.map(interview => (
<div
key={interview.id}
className="p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => setSelectedInterview(interview)}
>
<div className="flex items-center justify-between mb-2">
<Badge className={getInterviewTypeColor(interview.type)}>
{getInterviewTypeLabel(interview.type)}
</Badge>
<span className="text-sm font-medium">{formatTime(interview.scheduledDate)}</span>
</div>
<div className="text-sm font-medium">{getCandidateName(interview.candidateId)}</div>
<div className="text-xs text-muted-foreground">{getRequisitionTitle(interview.requisitionId)}</div>
</div>
)) : (
<div className="text-center py-4 text-muted-foreground text-sm">
No hay entrevistas hoy
</div>
)}
</CardContent>
</Card>
{/* Upcoming */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Proximas Entrevistas</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{upcomingInterviews.map(interview => (
<div
key={interview.id}
className="p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => setSelectedInterview(interview)}
>
<div className="flex items-center justify-between mb-1">
<Badge variant="outline" className="text-xs">
{getInterviewTypeLabel(interview.type)}
</Badge>
<span className="text-xs text-muted-foreground">
{new Date(interview.scheduledDate).toLocaleDateString("es-MX", {
day: "numeric",
month: "short"
})}
</span>
</div>
<div className="text-sm font-medium">{getCandidateName(interview.candidateId)}</div>
<div className="flex items-center gap-1 text-xs text-muted-foreground mt-1">
<Clock className="h-3 w-3" />
{formatTime(interview.scheduledDate)}
</div>
</div>
))}
</CardContent>
</Card>
{/* Legend */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Tipos de Entrevista</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded bg-primary" />
<span className="text-sm">Entrevista RR.HH.</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded bg-blue-500" />
<span className="text-sm">Entrevista Técnica</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded bg-purple-500" />
<span className="text-sm">Entrevista Gerente</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded bg-accent" />
<span className="text-sm">Entrevista Final</span>
</div>
</CardContent>
</Card>
</div>
</div>
{/* Interview Detail Dialog */}
<Dialog open={!!selectedInterview} onOpenChange={() => setSelectedInterview(null)}>
<DialogContent className="max-w-lg">
{selectedInterview && (
<>
<DialogHeader>
<div className="flex items-center justify-between">
<Badge className={getInterviewTypeColor(selectedInterview.type)}>
{getInterviewTypeLabel(selectedInterview.type)}
</Badge>
<Badge variant={
selectedInterview.status === "scheduled" ? "secondary" :
selectedInterview.status === "completed" ? "default" :
"destructive"
}>
{selectedInterview.status === "scheduled" ? "Programada" :
selectedInterview.status === "completed" ? "Completada" :
"Cancelada"}
</Badge>
</div>
<DialogTitle className="mt-2">
Entrevista con {getCandidateName(selectedInterview.candidateId)}
</DialogTitle>
<DialogDescription>
{getRequisitionTitle(selectedInterview.requisitionId)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
<CalendarIcon className="h-5 w-5 text-muted-foreground" />
<div>
<div className="font-medium">
{new Date(selectedInterview.scheduledDate).toLocaleDateString("es-MX", {
weekday: "long",
day: "numeric",
month: "long",
year: "numeric"
})}
</div>
<div className="text-sm text-muted-foreground">
{formatTime(selectedInterview.scheduledDate)} - {selectedInterview.duration} minutos
</div>
</div>
</div>
<div className="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
{selectedInterview.location === "video" ? (
<Video className="h-5 w-5 text-muted-foreground" />
) : (
<MapPin className="h-5 w-5 text-muted-foreground" />
)}
<div>
<div className="font-medium">
{selectedInterview.location === "video" ? "Videoconferencia" : "Presencial"}
</div>
{selectedInterview.meetingLink && (
<a
href={selectedInterview.meetingLink}
className="text-sm text-primary hover:underline flex items-center gap-1"
>
Unirse a la reunion <ExternalLink className="h-3 w-3" />
</a>
)}
</div>
</div>
<div className="space-y-2">
<Label className="text-sm text-muted-foreground">Entrevistadores</Label>
<div className="flex flex-wrap gap-2">
{selectedInterview.interviewers.map(interviewerId => {
const interviewer = mockUsers.find(u => u.id === interviewerId)
return interviewer ? (
<div key={interviewerId} className="flex items-center gap-2 px-3 py-1.5 bg-muted rounded-full">
<Avatar className="h-6 w-6">
<AvatarImage src={interviewer.avatar} />
<AvatarFallback className="text-xs">
{interviewer.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<span className="text-sm">{interviewer.name}</span>
</div>
) : null
})}
</div>
</div>
{selectedInterview.notes && (
<div className="space-y-2">
<Label className="text-sm text-muted-foreground">Notas</Label>
<p className="text-sm p-3 bg-muted/50 rounded-lg">{selectedInterview.notes}</p>
</div>
)}
</div>
<DialogFooter className="gap-2">
<Button variant="outline" size="sm">
<Edit className="mr-2 h-4 w-4" />
Editar
</Button>
<Button variant="outline" size="sm" className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
Cancelar
</Button>
{selectedInterview.status === "scheduled" && (
<Button size="sm" className="bg-accent hover:bg-accent/90">
<CheckCircle2 className="mr-2 h-4 w-4" />
Completar
</Button>
)}
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
</div>
)
}
+509
View File
@@ -0,0 +1,509 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell,
LineChart,
Line,
Legend,
AreaChart,
Area,
} from 'recharts'
import {
FileText,
Clock,
CheckCircle2,
AlertTriangle,
TrendingUp,
TrendingDown,
Users,
ArrowRight,
Calendar,
Target,
Activity,
Timer,
AlertCircle,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import {
requisitions,
countries,
recruiterCapacity,
getDashboardStats
} from '@/lib/mock-data'
import { STATUS_CONFIG, type Requisition } from '@/lib/types'
// Chart data
const statusDistribution = [
{ name: 'Reclutando', value: 4, color: '#6ec1e4' },
{ name: 'Pendiente RR.HH.', value: 1, color: '#f59e0b' },
{ name: 'Pendiente Admin', value: 1, color: '#8b5cf6' },
{ name: 'Corrección', value: 1, color: '#f97316' },
{ name: 'Cerrado', value: 1, color: '#22c55e' },
{ name: 'Cancelado', value: 1, color: '#ef4444' },
]
const requisitionsByCountry = [
{ country: 'México', abiertas: 3, cerradas: 0, canceladas: 0 },
{ country: 'Colombia', abiertas: 2, cerradas: 0, canceladas: 0 },
{ country: 'Perú', abiertas: 1, cerradas: 0, canceladas: 0 },
{ country: 'Chile', abiertas: 0, cerradas: 1, canceladas: 0 },
{ country: 'Rep. Dom.', abiertas: 1, cerradas: 0, canceladas: 0 },
{ country: 'Argentina', abiertas: 1, cerradas: 0, canceladas: 0 },
{ country: 'Guatemala', abiertas: 0, cerradas: 0, canceladas: 1 },
]
const ttfTrend = [
{ mes: 'Sep', dias: 28 },
{ mes: 'Oct', dias: 25 },
{ mes: 'Nov', dias: 22 },
{ mes: 'Dic', dias: 20 },
{ mes: 'Ene', dias: 18 },
]
const stageVelocity = [
{ stage: 'Búsqueda', promedio: 5 },
{ stage: '1era Entrev.', promedio: 3 },
{ stage: '2da Entrev.', promedio: 4 },
{ stage: 'Referencias', promedio: 3 },
{ stage: 'Exámenes', promedio: 2 },
{ stage: 'Selección', promedio: 1 },
]
function getInitials(name: string): string {
return name
.split(' ')
.map(n => n[0])
.join('')
.toUpperCase()
.slice(0, 2)
}
function getDaysUntilDeadline(deadline: string): number {
const now = new Date()
const deadlineDate = new Date(deadline)
return Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
}
function getCapacityStatus(score: number, max: number): { label: string; color: string; bgColor: string } {
const percentage = (score / max) * 100
if (percentage < 60) return { label: 'Disponible', color: 'text-emerald-700 dark:text-emerald-400', bgColor: 'bg-emerald-100 dark:bg-emerald-900/30' }
if (percentage < 90) return { label: 'A capacidad', color: 'text-amber-700 dark:text-amber-400', bgColor: 'bg-amber-100 dark:bg-amber-900/30' }
return { label: 'Sobrecargado', color: 'text-red-700 dark:text-red-400', bgColor: 'bg-red-100 dark:bg-red-900/30' }
}
interface StatCardProps {
title: string
value: string | number
subtitle?: string
icon: React.ElementType
trend?: { value: number; positive: boolean }
iconColor?: string
iconBgColor?: string
}
function StatCard({ title, value, subtitle, icon: Icon, trend, iconColor = 'text-primary', iconBgColor = 'bg-primary/10' }: StatCardProps) {
return (
<Card>
<CardContent className="p-6">
<div className="flex items-start justify-between">
<div className="space-y-2">
<p className="text-sm font-medium text-muted-foreground">{title}</p>
<div className="flex items-baseline gap-2">
<p className="text-3xl font-bold tracking-tight">{value}</p>
{trend && (
<span className={cn(
'flex items-center text-xs font-medium',
trend.positive ? 'text-emerald-600' : 'text-red-600'
)}>
{trend.positive ? <TrendingUp className="mr-0.5 h-3 w-3" /> : <TrendingDown className="mr-0.5 h-3 w-3" />}
{trend.value}%
</span>
)}
</div>
{subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>}
</div>
<div className={cn('flex h-12 w-12 items-center justify-center rounded-xl', iconBgColor)}>
<Icon className={cn('h-6 w-6', iconColor)} />
</div>
</div>
</CardContent>
</Card>
)
}
function RequisitionRow({ requisition }: { requisition: Requisition }) {
const status = STATUS_CONFIG[requisition.status]
const daysLeft = getDaysUntilDeadline(requisition.hardDeadline)
const isOverdue = daysLeft < 0
const isAtRisk = daysLeft >= 0 && daysLeft <= 7
return (
<Link
href={`/requisiciones/${requisition.id}`}
className="flex items-center gap-4 rounded-lg p-3 transition-colors hover:bg-muted/50"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm">{requisition.id}</span>
<Badge variant="outline" className={cn('text-xs', status.color, status.bgColor, status.borderColor)}>
{status.label}
</Badge>
</div>
<p className="text-sm text-muted-foreground truncate">
{requisition.positionName} - {requisition.cityName}, {requisition.countryName}
</p>
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<Users className="h-3 w-3" />
{requisition.vacanciesFilled}/{requisition.quantity}
</span>
<span className={cn(
'flex items-center gap-1',
isOverdue && 'text-red-600 dark:text-red-400',
isAtRisk && !isOverdue && 'text-amber-600 dark:text-amber-400'
)}>
<Clock className="h-3 w-3" />
{isOverdue ? `${Math.abs(daysLeft)}d vencido` : `${daysLeft}d restantes`}
</span>
</div>
</div>
<ArrowRight className="h-4 w-4 text-muted-foreground" />
</Link>
)
}
export function DashboardPage() {
const [selectedCountry, setSelectedCountry] = React.useState('all')
const stats = getDashboardStats()
const filteredRequisitions = selectedCountry === 'all'
? requisitions
: requisitions.filter(r => r.countryId === selectedCountry)
const openRequisitions = filteredRequisitions.filter(r => !['cerrado', 'cancelado'].includes(r.status))
const urgentRequisitions = openRequisitions.filter(r => {
const daysLeft = getDaysUntilDeadline(r.hardDeadline)
return daysLeft <= 7
}).sort((a, b) => new Date(a.hardDeadline).getTime() - new Date(b.hardDeadline).getTime())
return (
<div className="p-6 space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight">Dashboard</h1>
<p className="text-muted-foreground">
Resumen ejecutivo de requisiciones y reclutamiento
</p>
</div>
<div className="flex items-center gap-3 w-full sm:w-auto">
<Select value={selectedCountry} onValueChange={setSelectedCountry}>
<SelectTrigger className="w-full sm:w-[220px]">
<SelectValue placeholder="Filtrar por país" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los países</SelectItem>
{countries.map((country) => (
<SelectItem key={country.id} value={country.id}>
{country.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Stats Grid */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<StatCard
title="Requisiciones Abiertas"
value={stats.totalOpen}
subtitle={`${stats.recruiting} en reclutamiento activo`}
icon={FileText}
iconColor="text-sky-600"
iconBgColor="bg-sky-100 dark:bg-sky-900/30"
/>
<StatCard
title="Pendientes de Aprobación"
value={stats.pendingApproval}
subtitle="Requieren acción inmediata"
icon={Clock}
iconColor="text-amber-600"
iconBgColor="bg-amber-100 dark:bg-amber-900/30"
/>
<StatCard
title="SLA Vencido / En Riesgo"
value={`${stats.overdueCount} / ${stats.atRiskCount}`}
subtitle="Casos que requieren atención"
icon={AlertTriangle}
iconColor="text-red-600"
iconBgColor="bg-red-100 dark:bg-red-900/30"
/>
<StatCard
title="TTF Promedio"
value={`${stats.avgTTF} días`}
subtitle={`vs ${stats.avgTTF + 5} días mes anterior`}
icon={Target}
trend={{ value: 15, positive: true }}
iconColor="text-emerald-600"
iconBgColor="bg-emerald-100 dark:bg-emerald-900/30"
/>
</div>
{/* Charts Row */}
<div className="grid gap-6 lg:grid-cols-2">
{/* Status Distribution */}
<Card>
<CardHeader>
<CardTitle className="text-base font-semibold">Distribución por Estado</CardTitle>
<CardDescription>Estado actual de todas las requisiciones</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[280px]">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={statusDistribution}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
dataKey="value"
>
{statusDistribution.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
formatter={(value: number) => [value, 'Requisiciones']}
contentStyle={{
backgroundColor: 'hsl(var(--card))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
/>
<Legend
verticalAlign="bottom"
height={36}
formatter={(value) => <span className="text-xs text-foreground">{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
{/* Requisitions by Country */}
<Card>
<CardHeader>
<CardTitle className="text-base font-semibold">Requisiciones por País</CardTitle>
<CardDescription>Distribución geográfica de vacantes</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[280px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={requisitionsByCountry} layout="vertical" margin={{ left: 20, right: 20, top: 0, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="hsl(var(--border))" />
<XAxis type="number" tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
<YAxis dataKey="country" type="category" width={80} tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--card))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
/>
<Bar dataKey="abiertas" name="Abiertas" fill="var(--color-chart-1)" radius={[0, 4, 4, 0]} />
<Bar dataKey="cerradas" name="Cerradas" fill="var(--color-chart-2)" radius={[0, 4, 4, 0]} />
<Bar dataKey="canceladas" name="Canceladas" fill="var(--color-chart-4)" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
</div>
{/* TTF Trend & Stage Velocity */}
<div className="grid gap-6 lg:grid-cols-2">
{/* TTF Trend */}
<Card>
<CardHeader>
<CardTitle className="text-base font-semibold">Tendencia TTF</CardTitle>
<CardDescription>Tiempo promedio para cubrir vacantes (días)</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[240px]">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={ttfTrend}>
<defs>
<linearGradient id="ttfGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#6ec1e4" stopOpacity={0.3}/>
<stop offset="95%" stopColor="#6ec1e4" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="mes" tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
<YAxis tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
formatter={(value: number) => [`${value} días`, 'TTF Promedio']}
contentStyle={{
backgroundColor: 'hsl(var(--card))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
/>
<Area type="monotone" dataKey="dias" stroke="var(--color-chart-1)" strokeWidth={2} fill="url(#ttfGradient)" />
</AreaChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
{/* Stage Velocity */}
<Card>
<CardHeader>
<CardTitle className="text-base font-semibold">Velocidad por Etapa</CardTitle>
<CardDescription>Días promedio en cada fase del proceso</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[240px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={stageVelocity}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="stage" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
formatter={(value: number) => [`${value} días`, 'Promedio']}
contentStyle={{
backgroundColor: 'hsl(var(--card))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
/>
<Bar dataKey="promedio" fill="var(--color-chart-1)" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
</div>
{/* Bottom Row */}
<div className="grid gap-6 lg:grid-cols-3">
{/* Urgent Cases */}
<Card className="lg:col-span-2">
<CardHeader className="flex flex-row items-center justify-between pb-2">
<div>
<CardTitle className="text-base font-semibold">Casos Urgentes</CardTitle>
<CardDescription>Requisiciones con SLA en riesgo o vencido</CardDescription>
</div>
<Button variant="ghost" size="sm" asChild>
<Link href="/requisiciones?filter=urgent">Ver todos</Link>
</Button>
</CardHeader>
<CardContent>
<ScrollArea className="h-[320px] pr-4">
{urgentRequisitions.length > 0 ? (
<div className="space-y-1">
{urgentRequisitions.map((req) => (
<RequisitionRow key={req.id} requisition={req} />
))}
</div>
) : (
<div className="flex h-full flex-col items-center justify-center py-8 text-center">
<CheckCircle2 className="h-12 w-12 text-emerald-500 mb-3" />
<p className="text-sm font-medium">Sin casos urgentes</p>
<p className="text-xs text-muted-foreground">Todas las requisiciones están dentro del SLA</p>
</div>
)}
</ScrollArea>
</CardContent>
</Card>
{/* Recruiter Capacity */}
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<div>
<CardTitle className="text-base font-semibold">Carga de Reclutadores</CardTitle>
<CardDescription>Capacidad actual del equipo</CardDescription>
</div>
<Button variant="ghost" size="sm" asChild>
<Link href="/reclutadores">Ver todos</Link>
</Button>
</CardHeader>
<CardContent>
<ScrollArea className="h-[320px] pr-4">
<div className="space-y-4">
{recruiterCapacity.map((recruiter) => {
const capacityStatus = getCapacityStatus(recruiter.currentScore, recruiter.maxThreshold)
const percentage = Math.min((recruiter.currentScore / recruiter.maxThreshold) * 100, 100)
return (
<div key={recruiter.recruiterId} className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Avatar className="h-8 w-8">
<AvatarFallback className="text-xs bg-muted">
{getInitials(recruiter.recruiterName)}
</AvatarFallback>
</Avatar>
<div>
<p className="text-sm font-medium">{recruiter.recruiterName}</p>
<p className="text-xs text-muted-foreground">{recruiter.countryFocus.join(', ')}</p>
</div>
</div>
<Badge variant="outline" className={cn('text-xs', capacityStatus.color, capacityStatus.bgColor)}>
{capacityStatus.label}
</Badge>
</div>
<div className="space-y-1">
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">Score: {recruiter.currentScore}/{recruiter.maxThreshold}</span>
<span className="text-muted-foreground">{recruiter.openCases} casos</span>
</div>
<Progress
value={percentage}
className={cn(
'h-2',
percentage >= 90 && '[&>div]:bg-red-500',
percentage >= 60 && percentage < 90 && '[&>div]:bg-amber-500',
percentage < 60 && '[&>div]:bg-emerald-500'
)}
/>
</div>
</div>
)
})}
</div>
</ScrollArea>
</CardContent>
</Card>
</div>
</div>
)
}
+705
View File
@@ -0,0 +1,705 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Separator } from '@/components/ui/separator'
import {
ArrowLeft,
ArrowRight,
Save,
Send,
MapPin,
Building2,
Briefcase,
FileText,
DollarSign,
CheckCircle2,
AlertCircle,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { countries, cities, departments, positions, currentUser, getCitiesByCountry } from '@/lib/mock-data'
import { toast } from 'sonner'
type FormStep = 'ubicacion' | 'vacante' | 'justificacion' | 'compensacion' | 'revision'
const STEPS: { key: FormStep; label: string; icon: React.ElementType }[] = [
{ key: 'ubicacion', label: 'Ubicación', icon: MapPin },
{ key: 'vacante', label: 'Vacante', icon: Briefcase },
{ key: 'justificacion', label: 'Justificación', icon: FileText },
{ key: 'compensacion', label: 'Compensación', icon: DollarSign },
{ key: 'revision', label: 'Revisión', icon: CheckCircle2 },
]
interface FormData {
countryId: string
cityId: string
departmentId: string
positionId: string
quantity: number
modalidad: 'presencial' | 'remoto' | 'hibrido'
tipoContratacion: 'nuevo' | 'reemplazo' | 'temporal'
justification: string
urgency: 'normal' | 'alta' | 'critica'
salaryPackage: string
budget: string
currency: string
}
function StepIndicator({ currentStep }: { currentStep: FormStep }) {
const currentIndex = STEPS.findIndex(s => s.key === currentStep)
return (
<div className="flex items-center justify-between mb-8">
{STEPS.map((step, index) => {
const Icon = step.icon
const isCompleted = index < currentIndex
const isCurrent = step.key === currentStep
return (
<React.Fragment key={step.key}>
<div className="flex flex-col items-center gap-2">
<div className={cn(
'flex h-10 w-10 items-center justify-center rounded-full border-2 transition-colors',
isCompleted && 'border-emerald-500 bg-emerald-500 text-white',
isCurrent && 'border-primary bg-primary text-primary-foreground',
!isCompleted && !isCurrent && 'border-muted-foreground/30 bg-muted text-muted-foreground'
)}>
{isCompleted ? (
<CheckCircle2 className="h-5 w-5" />
) : (
<Icon className="h-5 w-5" />
)}
</div>
<span className={cn(
'text-xs font-medium hidden sm:block',
(isCompleted || isCurrent) && 'text-foreground',
!isCompleted && !isCurrent && 'text-muted-foreground'
)}>
{step.label}
</span>
</div>
{index < STEPS.length - 1 && (
<div className={cn(
'flex-1 h-0.5 mx-2',
index < currentIndex ? 'bg-emerald-500' : 'bg-muted-foreground/30'
)} />
)}
</React.Fragment>
)
})}
</div>
)
}
export function NewRequisitionPage() {
const router = useRouter()
const [currentStep, setCurrentStep] = React.useState<FormStep>('ubicacion')
const [errors, setErrors] = React.useState<Partial<Record<keyof FormData, string>>>({})
const [formData, setFormData] = React.useState<FormData>({
countryId: '',
cityId: '',
departmentId: '',
positionId: '',
quantity: 1,
modalidad: 'presencial',
tipoContratacion: 'nuevo',
justification: '',
urgency: 'normal',
salaryPackage: '',
budget: '',
currency: 'USD',
})
const availableCities = formData.countryId ? getCitiesByCountry(formData.countryId) : []
const updateFormData = (field: keyof FormData, value: string | number) => {
setFormData(prev => ({ ...prev, [field]: value }))
if (errors[field]) {
setErrors(prev => ({ ...prev, [field]: undefined }))
}
// Reset city when country changes
if (field === 'countryId') {
setFormData(prev => ({ ...prev, cityId: '' }))
}
}
const validateStep = (step: FormStep): boolean => {
const newErrors: Partial<Record<keyof FormData, string>> = {}
if (step === 'ubicacion') {
if (!formData.countryId) newErrors.countryId = 'Selecciona un país'
if (!formData.cityId) newErrors.cityId = 'Selecciona una ciudad'
if (!formData.departmentId) newErrors.departmentId = 'Selecciona un departamento'
}
if (step === 'vacante') {
if (!formData.positionId) newErrors.positionId = 'Selecciona una posición'
if (formData.quantity < 1) newErrors.quantity = 'La cantidad debe ser al menos 1'
}
if (step === 'justificacion') {
if (!formData.justification.trim()) newErrors.justification = 'La justificación es obligatoria'
if (formData.justification.length < 20) newErrors.justification = 'Proporciona una justificación más detallada (mín. 20 caracteres)'
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const goToNextStep = () => {
if (!validateStep(currentStep)) return
const currentIndex = STEPS.findIndex(s => s.key === currentStep)
if (currentIndex < STEPS.length - 1) {
setCurrentStep(STEPS[currentIndex + 1].key)
}
}
const goToPreviousStep = () => {
const currentIndex = STEPS.findIndex(s => s.key === currentStep)
if (currentIndex > 0) {
setCurrentStep(STEPS[currentIndex - 1].key)
}
}
const handleSaveDraft = () => {
toast.success('Borrador guardado', {
description: 'La requisición se ha guardado como borrador.',
})
}
const handleSubmit = () => {
toast.success('Requisición enviada', {
description: 'La requisición ha sido enviada para aprobación de RR.HH.',
})
router.push('/requisiciones')
}
const selectedCountry = countries.find(c => c.id === formData.countryId)
const selectedCity = cities.find(c => c.id === formData.cityId)
const selectedDepartment = departments.find(d => d.id === formData.departmentId)
const selectedPosition = positions.find(p => p.id === formData.positionId)
return (
<div className="p-6 max-w-4xl mx-auto">
{/* Header */}
<div className="flex items-center gap-4 mb-6">
<Button variant="ghost" size="icon" asChild>
<Link href="/requisiciones">
<ArrowLeft className="h-4 w-4" />
</Link>
</Button>
<div>
<h1 className="text-2xl font-bold tracking-tight">Nueva Requisición</h1>
<p className="text-muted-foreground">
Completa el formulario para solicitar una nueva vacante
</p>
</div>
</div>
{/* Step Indicator */}
<StepIndicator currentStep={currentStep} />
{/* Form Card */}
<Card>
<CardContent className="p-6">
{/* Step 1: Ubicación */}
{currentStep === 'ubicacion' && (
<div className="space-y-6">
<div>
<h2 className="text-lg font-semibold mb-1">Ubicación</h2>
<p className="text-sm text-muted-foreground">
Define el país, ciudad y departamento de la vacante
</p>
</div>
<div className="grid gap-6 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="country">País *</Label>
<Select value={formData.countryId} onValueChange={(v) => updateFormData('countryId', v)}>
<SelectTrigger className={cn(errors.countryId && 'border-destructive')}>
<SelectValue placeholder="Seleccionar país" />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem key={country.id} value={country.id}>
{country.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.countryId && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.countryId}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="city">Ciudad *</Label>
<Select
value={formData.cityId}
onValueChange={(v) => updateFormData('cityId', v)}
disabled={!formData.countryId}
>
<SelectTrigger className={cn(errors.cityId && 'border-destructive')}>
<SelectValue placeholder={formData.countryId ? "Seleccionar ciudad" : "Primero selecciona un país"} />
</SelectTrigger>
<SelectContent>
{availableCities.map((city) => (
<SelectItem key={city.id} value={city.id}>
{city.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.cityId && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.cityId}
</p>
)}
</div>
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="department">Departamento *</Label>
<Select value={formData.departmentId} onValueChange={(v) => updateFormData('departmentId', v)}>
<SelectTrigger className={cn(errors.departmentId && 'border-destructive')}>
<SelectValue placeholder="Seleccionar departamento" />
</SelectTrigger>
<SelectContent>
{departments.map((dept) => (
<SelectItem key={dept.id} value={dept.id}>
{dept.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.departmentId && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.departmentId}
</p>
)}
</div>
</div>
{/* Requester Info */}
<div className="rounded-lg bg-muted/50 p-4">
<p className="text-sm text-muted-foreground mb-2">Solicitante</p>
<p className="font-medium">{currentUser.name}</p>
<p className="text-sm text-muted-foreground">{currentUser.email}</p>
</div>
</div>
)}
{/* Step 2: Vacante */}
{currentStep === 'vacante' && (
<div className="space-y-6">
<div>
<h2 className="text-lg font-semibold mb-1">Información de la Vacante</h2>
<p className="text-sm text-muted-foreground">
Define la posición, cantidad y tipo de contratación
</p>
</div>
<div className="grid gap-6 sm:grid-cols-2">
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="position">Posición *</Label>
<Select value={formData.positionId} onValueChange={(v) => updateFormData('positionId', v)}>
<SelectTrigger className={cn(errors.positionId && 'border-destructive')}>
<SelectValue placeholder="Seleccionar posición" />
</SelectTrigger>
<SelectContent>
{positions.map((pos) => (
<SelectItem key={pos.id} value={pos.id}>
{pos.name}
</SelectItem>
))}
</SelectContent>
</Select>
{errors.positionId && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.positionId}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="quantity">Cantidad de Vacantes *</Label>
<Input
id="quantity"
type="number"
min={1}
value={formData.quantity}
onChange={(e) => updateFormData('quantity', parseInt(e.target.value) || 1)}
className={cn(errors.quantity && 'border-destructive')}
/>
{errors.quantity && (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.quantity}
</p>
)}
</div>
<div className="space-y-2">
<Label>Modalidad *</Label>
<RadioGroup
value={formData.modalidad}
onValueChange={(v) => updateFormData('modalidad', v)}
className="flex gap-4"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="presencial" id="presencial" />
<Label htmlFor="presencial" className="font-normal">Presencial</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="hibrido" id="hibrido" />
<Label htmlFor="hibrido" className="font-normal">Híbrido</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="remoto" id="remoto" />
<Label htmlFor="remoto" className="font-normal">Remoto</Label>
</div>
</RadioGroup>
</div>
<div className="space-y-2 sm:col-span-2">
<Label>Tipo de Contratación *</Label>
<RadioGroup
value={formData.tipoContratacion}
onValueChange={(v) => updateFormData('tipoContratacion', v)}
className="flex gap-4"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="nuevo" id="nuevo" />
<Label htmlFor="nuevo" className="font-normal">Nueva posición</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="reemplazo" id="reemplazo" />
<Label htmlFor="reemplazo" className="font-normal">Reemplazo</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="temporal" id="temporal" />
<Label htmlFor="temporal" className="font-normal">Temporal</Label>
</div>
</RadioGroup>
</div>
</div>
</div>
)}
{/* Step 3: Justificación */}
{currentStep === 'justificacion' && (
<div className="space-y-6">
<div>
<h2 className="text-lg font-semibold mb-1">Justificación</h2>
<p className="text-sm text-muted-foreground">
Explica el motivo de la requisición y su nivel de urgencia
</p>
</div>
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="justification">Justificación de la Requisición *</Label>
<Textarea
id="justification"
value={formData.justification}
onChange={(e) => updateFormData('justification', e.target.value)}
placeholder="Describe el motivo por el cual se necesita esta contratación, el impacto en el negocio y cualquier contexto relevante..."
rows={5}
className={cn(errors.justification && 'border-destructive')}
/>
<div className="flex items-center justify-between">
{errors.justification ? (
<p className="text-xs text-destructive flex items-center gap-1">
<AlertCircle className="h-3 w-3" />
{errors.justification}
</p>
) : (
<p className="text-xs text-muted-foreground">
Mínimo 20 caracteres
</p>
)}
<p className="text-xs text-muted-foreground">
{formData.justification.length} caracteres
</p>
</div>
</div>
<div className="space-y-2">
<Label>Nivel de Urgencia *</Label>
<RadioGroup
value={formData.urgency}
onValueChange={(v) => updateFormData('urgency', v)}
className="grid gap-3"
>
<div className="flex items-start space-x-3 rounded-lg border p-4 hover:bg-muted/50 transition-colors">
<RadioGroupItem value="normal" id="normal" className="mt-0.5" />
<div>
<Label htmlFor="normal" className="font-medium">Normal</Label>
<p className="text-sm text-muted-foreground">
Proceso estándar de reclutamiento según SLA definido
</p>
</div>
</div>
<div className="flex items-start space-x-3 rounded-lg border border-amber-200 bg-amber-50/50 p-4 dark:border-amber-800 dark:bg-amber-950/30">
<RadioGroupItem value="alta" id="alta" className="mt-0.5" />
<div>
<Label htmlFor="alta" className="font-medium">Alta</Label>
<p className="text-sm text-muted-foreground">
Requiere atención prioritaria, impacto operativo significativo
</p>
</div>
</div>
<div className="flex items-start space-x-3 rounded-lg border border-red-200 bg-red-50/50 p-4 dark:border-red-800 dark:bg-red-950/30">
<RadioGroupItem value="critica" id="critica" className="mt-0.5" />
<div>
<Label htmlFor="critica" className="font-medium">Crítica</Label>
<p className="text-sm text-muted-foreground">
Urgencia máxima, afecta operaciones críticas del negocio
</p>
</div>
</div>
</RadioGroup>
</div>
</div>
</div>
)}
{/* Step 4: Compensación */}
{currentStep === 'compensacion' && (
<div className="space-y-6">
<div>
<h2 className="text-lg font-semibold mb-1">Compensación</h2>
<p className="text-sm text-muted-foreground">
Define el paquete salarial y presupuesto (opcional, visible solo para roles autorizados)
</p>
</div>
<div className="grid gap-6 sm:grid-cols-2">
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="salaryPackage">Paquete Salarial</Label>
<Input
id="salaryPackage"
value={formData.salaryPackage}
onChange={(e) => updateFormData('salaryPackage', e.target.value)}
placeholder="Ej: $15,000 - $20,000 MXN mensual"
/>
<p className="text-xs text-muted-foreground">
Rango salarial propuesto para la posición
</p>
</div>
<div className="space-y-2">
<Label htmlFor="budget">Presupuesto Mensual</Label>
<Input
id="budget"
type="number"
value={formData.budget}
onChange={(e) => updateFormData('budget', e.target.value)}
placeholder="0"
/>
</div>
<div className="space-y-2">
<Label htmlFor="currency">Moneda</Label>
<Select value={formData.currency} onValueChange={(v) => updateFormData('currency', v)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="USD">USD - Dólar Estadounidense</SelectItem>
<SelectItem value="MXN">MXN - Peso Mexicano</SelectItem>
<SelectItem value="COP">COP - Peso Colombiano</SelectItem>
<SelectItem value="PEN">PEN - Sol Peruano</SelectItem>
<SelectItem value="CLP">CLP - Peso Chileno</SelectItem>
<SelectItem value="ARS">ARS - Peso Argentino</SelectItem>
<SelectItem value="DOP">DOP - Peso Dominicano</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground">
<p className="font-medium text-foreground mb-1">Nota de privacidad</p>
<p>
La información de compensación solo será visible para roles autorizados (RR.HH. y Administración).
</p>
</div>
</div>
)}
{/* Step 5: Revisión */}
{currentStep === 'revision' && (
<div className="space-y-6">
<div>
<h2 className="text-lg font-semibold mb-1">Revisión Final</h2>
<p className="text-sm text-muted-foreground">
Verifica que toda la información sea correcta antes de enviar
</p>
</div>
<div className="space-y-4">
{/* Location Summary */}
<div className="rounded-lg border p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="font-medium flex items-center gap-2">
<MapPin className="h-4 w-4 text-primary" />
Ubicación
</h3>
<Button variant="ghost" size="sm" onClick={() => setCurrentStep('ubicacion')}>
Editar
</Button>
</div>
<div className="grid gap-2 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">País:</span>
<span>{selectedCountry?.name || '-'}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Ciudad:</span>
<span>{selectedCity?.name || '-'}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Departamento:</span>
<span>{selectedDepartment?.name || '-'}</span>
</div>
</div>
</div>
{/* Vacancy Summary */}
<div className="rounded-lg border p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="font-medium flex items-center gap-2">
<Briefcase className="h-4 w-4 text-primary" />
Vacante
</h3>
<Button variant="ghost" size="sm" onClick={() => setCurrentStep('vacante')}>
Editar
</Button>
</div>
<div className="grid gap-2 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Posición:</span>
<span>{selectedPosition?.name || '-'}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Cantidad:</span>
<span>{formData.quantity}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Modalidad:</span>
<span className="capitalize">{formData.modalidad}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Tipo:</span>
<span className="capitalize">{formData.tipoContratacion}</span>
</div>
</div>
</div>
{/* Justification Summary */}
<div className="rounded-lg border p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="font-medium flex items-center gap-2">
<FileText className="h-4 w-4 text-primary" />
Justificación
</h3>
<Button variant="ghost" size="sm" onClick={() => setCurrentStep('justificacion')}>
Editar
</Button>
</div>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Urgencia:</span>
<span className="capitalize">{formData.urgency}</span>
</div>
<p className="text-muted-foreground mt-2">{formData.justification || '-'}</p>
</div>
</div>
{/* Compensation Summary */}
{(formData.salaryPackage || formData.budget) && (
<div className="rounded-lg border p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="font-medium flex items-center gap-2">
<DollarSign className="h-4 w-4 text-primary" />
Compensación
</h3>
<Button variant="ghost" size="sm" onClick={() => setCurrentStep('compensacion')}>
Editar
</Button>
</div>
<div className="grid gap-2 text-sm">
{formData.salaryPackage && (
<div className="flex justify-between">
<span className="text-muted-foreground">Paquete:</span>
<span>{formData.salaryPackage}</span>
</div>
)}
{formData.budget && (
<div className="flex justify-between">
<span className="text-muted-foreground">Presupuesto:</span>
<span>{formData.currency} {parseInt(formData.budget).toLocaleString()}</span>
</div>
)}
</div>
</div>
)}
</div>
</div>
)}
{/* Navigation Buttons */}
<Separator className="my-6" />
<div className="flex items-center justify-between">
<div>
{currentStep !== 'ubicacion' && (
<Button variant="outline" onClick={goToPreviousStep}>
<ArrowLeft className="mr-2 h-4 w-4" />
Anterior
</Button>
)}
</div>
<div className="flex items-center gap-2">
<Button variant="outline" onClick={handleSaveDraft}>
<Save className="mr-2 h-4 w-4" />
Guardar Borrador
</Button>
{currentStep !== 'revision' ? (
<Button onClick={goToNextStep}>
Siguiente
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
) : (
<Button onClick={handleSubmit}>
<Send className="mr-2 h-4 w-4" />
Enviar a Aprobación
</Button>
)}
</div>
</div>
</CardContent>
</Card>
</div>
)
}
+308
View File
@@ -0,0 +1,308 @@
"use client"
import { useState } from "react"
import { mockNotifications } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Bell,
CheckCircle2,
AlertCircle,
Info,
User,
FileText,
Calendar,
Clock,
Trash2,
Check,
MoreVertical,
Settings,
Filter
} from "lucide-react"
import { cn } from "@/lib/utils"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
export function NotificationsPage() {
const [notifications, setNotifications] = useState(mockNotifications)
const [filter, setFilter] = useState<string>("all")
const unreadCount = notifications.filter(n => !n.read).length
const filteredNotifications = notifications.filter(notification => {
if (filter === "all") return true
if (filter === "unread") return !notification.read
return notification.type === filter
})
const markAsRead = (id: string) => {
setNotifications(prev => prev.map(n =>
n.id === id ? { ...n, read: true } : n
))
}
const markAllAsRead = () => {
setNotifications(prev => prev.map(n => ({ ...n, read: true })))
}
const deleteNotification = (id: string) => {
setNotifications(prev => prev.filter(n => n.id !== id))
}
const getNotificationIcon = (type: string) => {
switch (type) {
case "requisition":
return <FileText className="h-5 w-5" />
case "approval":
return <CheckCircle2 className="h-5 w-5" />
case "candidate":
return <User className="h-5 w-5" />
case "interview":
return <Calendar className="h-5 w-5" />
case "reminder":
return <Clock className="h-5 w-5" />
case "alert":
return <AlertCircle className="h-5 w-5" />
default:
return <Info className="h-5 w-5" />
}
}
const getNotificationColor = (type: string, priority: string) => {
if (priority === "high") return "bg-destructive/10 text-destructive border-destructive/20"
switch (type) {
case "requisition":
return "bg-primary/10 text-primary border-primary/20"
case "approval":
return "bg-accent/10 text-accent border-accent/20"
case "candidate":
return "bg-blue-500/10 text-blue-500 border-blue-500/20"
case "interview":
return "bg-purple-500/10 text-purple-500 border-purple-500/20"
case "reminder":
return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20"
default:
return "bg-muted text-muted-foreground border-muted"
}
}
const formatDate = (dateString: string) => {
const date = new Date(dateString)
const now = new Date()
const diff = now.getTime() - date.getTime()
const hours = Math.floor(diff / (1000 * 60 * 60))
const days = Math.floor(hours / 24)
if (hours < 1) return "Hace menos de 1 hora"
if (hours < 24) return `Hace ${hours} hora${hours > 1 ? "s" : ""}`
if (days < 7) return `Hace ${days} dia${days > 1 ? "s" : ""}`
return date.toLocaleDateString("es-MX", { day: "numeric", month: "short" })
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Notificaciones</h1>
<p className="text-muted-foreground">
Tienes {unreadCount} notificaciones sin leer
</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" onClick={markAllAsRead} disabled={unreadCount === 0}>
<Check className="mr-2 h-4 w-4" />
Marcar todas como leidas
</Button>
<Button variant="outline" size="icon">
<Settings className="h-4 w-4" />
</Button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
<Card
className={cn("cursor-pointer transition-colors", filter === "all" && "ring-2 ring-primary")}
onClick={() => setFilter("all")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<Bell className="h-5 w-5 text-muted-foreground" />
<div>
<div className="text-2xl font-bold">{notifications.length}</div>
<div className="text-xs text-muted-foreground">Todas</div>
</div>
</div>
</CardContent>
</Card>
<Card
className={cn("cursor-pointer transition-colors", filter === "unread" && "ring-2 ring-primary")}
onClick={() => setFilter("unread")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<Badge className="h-5 w-5 flex items-center justify-center p-0 bg-destructive">
{unreadCount}
</Badge>
<div>
<div className="text-2xl font-bold">{unreadCount}</div>
<div className="text-xs text-muted-foreground">Sin leer</div>
</div>
</div>
</CardContent>
</Card>
<Card
className={cn("cursor-pointer transition-colors", filter === "approval" && "ring-2 ring-primary")}
onClick={() => setFilter("approval")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<CheckCircle2 className="h-5 w-5 text-accent" />
<div>
<div className="text-2xl font-bold">
{notifications.filter(n => n.type === "approval").length}
</div>
<div className="text-xs text-muted-foreground">Aprobaciones</div>
</div>
</div>
</CardContent>
</Card>
<Card
className={cn("cursor-pointer transition-colors", filter === "interview" && "ring-2 ring-primary")}
onClick={() => setFilter("interview")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<Calendar className="h-5 w-5 text-purple-500" />
<div>
<div className="text-2xl font-bold">
{notifications.filter(n => n.type === "interview").length}
</div>
<div className="text-xs text-muted-foreground">Entrevistas</div>
</div>
</div>
</CardContent>
</Card>
<Card
className={cn("cursor-pointer transition-colors", filter === "candidate" && "ring-2 ring-primary")}
onClick={() => setFilter("candidate")}
>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<User className="h-5 w-5 text-blue-500" />
<div>
<div className="text-2xl font-bold">
{notifications.filter(n => n.type === "candidate").length}
</div>
<div className="text-xs text-muted-foreground">Candidatos</div>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Notifications List */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">
{filter === "all" ? "Todas las notificaciones" :
filter === "unread" ? "Notificaciones sin leer" :
`Notificaciones de ${filter}`}
</CardTitle>
<Badge variant="secondary">{filteredNotifications.length}</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
{filteredNotifications.length > 0 ? (
<div className="divide-y">
{filteredNotifications.map(notification => (
<div
key={notification.id}
className={cn(
"flex items-start gap-4 p-4 hover:bg-muted/50 transition-colors cursor-pointer",
!notification.read && "bg-primary/5"
)}
onClick={() => markAsRead(notification.id)}
>
<div className={cn(
"w-10 h-10 rounded-full flex items-center justify-center border",
getNotificationColor(notification.type, notification.priority)
)}>
{getNotificationIcon(notification.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<div>
<h4 className={cn(
"text-sm",
!notification.read && "font-semibold"
)}>
{notification.title}
</h4>
<p className="text-sm text-muted-foreground mt-1">
{notification.message}
</p>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{!notification.read && (
<div className="w-2 h-2 rounded-full bg-primary" />
)}
{notification.priority === "high" && (
<Badge variant="destructive" className="text-xs">Urgente</Badge>
)}
</div>
</div>
<div className="flex items-center gap-4 mt-2">
<span className="text-xs text-muted-foreground">
{formatDate(notification.createdAt)}
</span>
{notification.actionUrl && (
<Button variant="link" size="sm" className="h-auto p-0 text-xs">
Ver detalle
</Button>
)}
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="icon" className="flex-shrink-0">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={(e) => {
e.stopPropagation()
markAsRead(notification.id)
}}>
<Check className="mr-2 h-4 w-4" />
Marcar como leida
</DropdownMenuItem>
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation()
deleteNotification(notification.id)
}}
className="text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Eliminar
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
))}
</div>
) : (
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
<Bell className="h-12 w-12 mb-4 opacity-50" />
<p>No hay notificaciones</p>
</div>
)}
</CardContent>
</Card>
</div>
)
}
@@ -0,0 +1,760 @@
"use client"
import { useState } from "react"
import { mockCandidates, mockRequisitions, mockUsers, pipelineStages } from "@/lib/mock-data"
import type { Candidate, PipelineStage } from "@/lib/types"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Search,
Filter,
Plus,
MoreVertical,
Mail,
Phone,
Calendar,
Star,
ChevronRight,
FileText,
MessageSquare,
Clock,
CheckCircle2,
XCircle,
ArrowRight,
GripVertical,
User,
Briefcase,
MapPin,
DollarSign,
ThumbsUp,
ThumbsDown,
Eye,
Download,
Send,
Video,
Linkedin
} from "lucide-react"
import { cn } from "@/lib/utils"
export function RecruitmentPipelinePage() {
const [candidates, setCandidates] = useState<Candidate[]>(mockCandidates)
const [selectedRequisition, setSelectedRequisition] = useState<string>("all")
const [searchQuery, setSearchQuery] = useState("")
const [selectedCandidate, setSelectedCandidate] = useState<Candidate | null>(null)
const [isDetailOpen, setIsDetailOpen] = useState(false)
const [isAddCandidateOpen, setIsAddCandidateOpen] = useState(false)
const [draggedCandidate, setDraggedCandidate] = useState<Candidate | null>(null)
const [viewMode, setViewMode] = useState<"kanban" | "list">("kanban")
const activeRequisitions = mockRequisitions.filter(r => r.status === "approved" || r.status === "published")
const filteredCandidates = candidates.filter(candidate => {
const matchesRequisition = selectedRequisition === "all" || candidate.requisitionId === selectedRequisition
const matchesSearch = candidate.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
candidate.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
candidate.currentPosition?.toLowerCase().includes(searchQuery.toLowerCase())
return matchesRequisition && matchesSearch
})
const getCandidatesByStage = (stageId: string) => {
return filteredCandidates.filter(c => c.currentStage === stageId)
}
const handleDragStart = (candidate: Candidate) => {
setDraggedCandidate(candidate)
}
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
}
const handleDrop = (stageId: string) => {
if (draggedCandidate) {
setCandidates(prev => prev.map(c =>
c.id === draggedCandidate.id
? { ...c, currentStage: stageId as PipelineStage }
: c
))
setDraggedCandidate(null)
}
}
const getStageColor = (stageId: string) => {
const colors: Record<string, string> = {
applied: "border-slate-300",
screening: "border-[var(--color-chart-1)]",
interview_rrhh: "border-[var(--color-chart-2)]",
interview_technical: "border-[var(--color-chart-3)]",
interview_manager: "border-[var(--color-chart-4)]",
offer: "border-[var(--color-status-recruiting)]",
hired: "border-[var(--color-status-closed)]",
rejected: "border-[var(--color-status-cancelled)]"
}
return colors[stageId] || "border-muted-foreground"
}
const getRatingStars = (rating: number) => {
return Array.from({ length: 5 }, (_, i) => (
<Star
key={i}
className={cn(
"h-3 w-3",
i < rating ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground/30"
)}
/>
))
}
const getSourceBadge = (source: string) => {
const sourceConfig: Record<string, { label: string; className: string }> = {
linkedin: { label: "LinkedIn", className: "bg-[var(--color-chart-2)] text-white" },
referral: { label: "Referido", className: "bg-accent text-accent-foreground" },
job_board: { label: "Portal Empleo", className: "bg-primary text-primary-foreground" },
website: { label: "Web", className: "bg-secondary text-secondary-foreground" },
agency: { label: "Agencia", className: "bg-[var(--color-chart-1)] text-white" }
}
const config = sourceConfig[source] || { label: source, className: "bg-muted text-muted-foreground" }
return <Badge className={config.className}>{config.label}</Badge>
}
const openCandidateDetail = (candidate: Candidate) => {
setSelectedCandidate(candidate)
setIsDetailOpen(true)
}
const getRequisitionTitle = (requisitionId: string) => {
const requisition = mockRequisitions.find(r => r.id === requisitionId)
return requisition?.position || "Sin asignar"
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Pipeline de Reclutamiento</h1>
<p className="text-muted-foreground">
Gestiona candidatos y su progreso en el proceso de seleccion
</p>
</div>
<Dialog open={isAddCandidateOpen} onOpenChange={setIsAddCandidateOpen}>
<DialogTrigger asChild>
<Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
<Plus className="mr-2 h-4 w-4" />
Agregar Candidato
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Agregar Nuevo Candidato</DialogTitle>
<DialogDescription>
Ingresa la informacion del candidato para agregarlo al pipeline
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="name">Nombre Completo</Label>
<Input id="name" placeholder="Juan Perez" />
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" placeholder="juan@email.com" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="phone">Telefono</Label>
<Input id="phone" placeholder="+52 55 1234 5678" />
</div>
<div className="space-y-2">
<Label htmlFor="linkedin">LinkedIn</Label>
<Input id="linkedin" placeholder="linkedin.com/in/usuario" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="position">Posicion Actual</Label>
<Input id="position" placeholder="Ingeniero de Software" />
</div>
<div className="space-y-2">
<Label htmlFor="company">Empresa Actual</Label>
<Input id="company" placeholder="Empresa ABC" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="requisition">Vacante</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar vacante" />
</SelectTrigger>
<SelectContent>
{activeRequisitions.map(req => (
<SelectItem key={req.id} value={req.id}>
{req.position} - {req.department}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="source">Fuente</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar fuente" />
</SelectTrigger>
<SelectContent>
<SelectItem value="linkedin">LinkedIn</SelectItem>
<SelectItem value="referral">Referido</SelectItem>
<SelectItem value="job_board">Portal de Empleo</SelectItem>
<SelectItem value="website">Sitio Web</SelectItem>
<SelectItem value="agency">Agencia</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="salary">Expectativa Salarial</Label>
<Input id="salary" placeholder="$50,000 MXN" />
</div>
<div className="space-y-2">
<Label htmlFor="availability">Disponibilidad</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar" />
</SelectTrigger>
<SelectContent>
<SelectItem value="immediate">Inmediata</SelectItem>
<SelectItem value="2_weeks">2 Semanas</SelectItem>
<SelectItem value="1_month">1 Mes</SelectItem>
<SelectItem value="negotiable">Negociable</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="notes">Notas</Label>
<Textarea id="notes" placeholder="Notas adicionales sobre el candidato..." />
</div>
<div className="space-y-2">
<Label htmlFor="cv">CV / Resume</Label>
<Input id="cv" type="file" accept=".pdf,.doc,.docx" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsAddCandidateOpen(false)}>
Cancelar
</Button>
<Button className="bg-accent hover:bg-accent/90" onClick={() => setIsAddCandidateOpen(false)}>
Agregar Candidato
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
{/* Filters */}
<Card>
<CardContent className="p-4">
<div className="flex flex-col gap-4 md:flex-row md:items-center">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Buscar candidatos por nombre, email o posicion..."
className="pl-10"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<Select value={selectedRequisition} onValueChange={setSelectedRequisition}>
<SelectTrigger className="w-full md:w-[280px]">
<SelectValue placeholder="Filtrar por vacante" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todas las vacantes</SelectItem>
{activeRequisitions.map(req => (
<SelectItem key={req.id} value={req.id}>
{req.position} - {req.department}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="flex gap-2">
<Button
variant={viewMode === "kanban" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("kanban")}
>
Kanban
</Button>
<Button
variant={viewMode === "list" ? "default" : "outline"}
size="sm"
onClick={() => setViewMode("list")}
>
Lista
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Pipeline Stats */}
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3">
{pipelineStages.map(stage => {
const count = getCandidatesByStage(stage.id).length
return (
<div
key={stage.id}
className={`p-4 rounded-xl border bg-white ${getStageColor(stage.id)} border-t-4 shadow-sm flex flex-col justify-center`}
>
<div className="text-2xl font-bold mb-1 text-card-foreground">{count}</div>
<div className="text-sm font-medium text-muted-foreground">{stage.name}</div>
</div>
)
})}
</div>
{/* Kanban Board */}
{viewMode === "kanban" ? (
<div className="flex gap-4 overflow-x-auto pb-4">
{pipelineStages.filter(s => s.id !== "rejected").map(stage => {
const columnCandidates = getCandidatesByStage(stage.id)
return (
<div
key={stage.id}
className="flex-shrink-0 w-[300px]"
onDragOver={handleDragOver}
onDrop={() => handleDrop(stage.id)}
>
<div className={`flex flex-col h-full min-h-[500px] rounded-lg border bg-white ${getStageColor(stage.id)} border-t-4`}>
<div className="flex items-center justify-between p-3 border-b border-border/50">
<h3 className="font-semibold text-sm text-card-foreground">
{stage.name}
</h3>
<Badge variant="secondary" className="bg-muted text-muted-foreground">{columnCandidates.length}</Badge>
</div>
<div className="space-y-3 p-3 max-h-[600px] overflow-y-auto">
{columnCandidates.map(candidate => (
<Card
key={candidate.id}
className="cursor-pointer hover:shadow-md transition-shadow"
draggable
onDragStart={() => handleDragStart(candidate)}
onClick={() => openCandidateDetail(candidate)}
>
<CardContent className="p-3">
<div className="flex items-start gap-3">
<Avatar className="h-10 w-10">
<AvatarImage src={candidate.avatar} />
<AvatarFallback className="bg-primary/10 text-primary">
{candidate.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<h4 className="font-medium text-sm truncate">{candidate.name}</h4>
<GripVertical className="h-3 w-3 text-muted-foreground/50" />
</div>
<p className="text-xs text-muted-foreground truncate">
{candidate.currentPosition}
</p>
<div className="flex items-center gap-1 mt-1">
{getRatingStars(candidate.rating || 0)}
</div>
</div>
</div>
<div className="flex items-center justify-between mt-3">
{getSourceBadge(candidate.source)}
<span className="text-xs text-muted-foreground">
{new Date(candidate.appliedDate).toLocaleDateString("es-MX", {
day: "numeric",
month: "short"
})}
</span>
</div>
</CardContent>
</Card>
))}
{columnCandidates.length === 0 && (
<div className="text-center py-8 text-muted-foreground text-sm">
Sin candidatos
</div>
)}
</div>
</div>
</div>
)})}
</div>
) : (
/* List View */
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b bg-muted/50">
<th className="text-left p-4 font-medium">Candidato</th>
<th className="text-left p-4 font-medium">Vacante</th>
<th className="text-left p-4 font-medium">Etapa</th>
<th className="text-left p-4 font-medium">Fuente</th>
<th className="text-left p-4 font-medium">Rating</th>
<th className="text-left p-4 font-medium">Fecha</th>
<th className="text-right p-4 font-medium">Acciones</th>
</tr>
</thead>
<tbody>
{filteredCandidates.map(candidate => {
const stage = pipelineStages.find(s => s.id === candidate.currentStage)
return (
<tr
key={candidate.id}
className="border-b hover:bg-muted/30 cursor-pointer"
onClick={() => openCandidateDetail(candidate)}
>
<td className="p-4">
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9">
<AvatarImage src={candidate.avatar} />
<AvatarFallback className="bg-primary/10 text-primary text-xs">
{candidate.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium">{candidate.name}</div>
<div className="text-sm text-muted-foreground">{candidate.email}</div>
</div>
</div>
</td>
<td className="p-4">
<span className="text-sm">{getRequisitionTitle(candidate.requisitionId)}</span>
</td>
<td className="p-4">
<Badge variant="outline" className={cn("border", getStageColor(candidate.currentStage))}>
{stage?.name}
</Badge>
</td>
<td className="p-4">
{getSourceBadge(candidate.source)}
</td>
<td className="p-4">
<div className="flex items-center gap-1">
{getRatingStars(candidate.rating || 0)}
</div>
</td>
<td className="p-4">
<span className="text-sm text-muted-foreground">
{new Date(candidate.appliedDate).toLocaleDateString("es-MX")}
</span>
</td>
<td className="p-4 text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="icon">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem>
<Eye className="mr-2 h-4 w-4" />
Ver Perfil
</DropdownMenuItem>
<DropdownMenuItem>
<Mail className="mr-2 h-4 w-4" />
Enviar Email
</DropdownMenuItem>
<DropdownMenuItem>
<Calendar className="mr-2 h-4 w-4" />
Agendar Entrevista
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>
<ArrowRight className="mr-2 h-4 w-4" />
Mover a siguiente etapa
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive">
<XCircle className="mr-2 h-4 w-4" />
Rechazar
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</CardContent>
</Card>
)}
{/* Candidate Detail Dialog */}
<Dialog open={isDetailOpen} onOpenChange={setIsDetailOpen}>
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
{selectedCandidate && (
<>
<DialogHeader>
<div className="flex items-start gap-4">
<Avatar className="h-16 w-16">
<AvatarImage src={selectedCandidate.avatar} />
<AvatarFallback className="bg-primary/10 text-primary text-xl">
{selectedCandidate.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<DialogTitle className="text-xl">{selectedCandidate.name}</DialogTitle>
<DialogDescription className="mt-1">
{selectedCandidate.currentPosition} en {selectedCandidate.currentCompany}
</DialogDescription>
<div className="flex items-center gap-3 mt-2">
{getSourceBadge(selectedCandidate.source)}
<Badge variant="outline">
{pipelineStages.find(s => s.id === selectedCandidate.currentStage)?.name}
</Badge>
<div className="flex items-center gap-1">
{getRatingStars(selectedCandidate.rating || 0)}
</div>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="icon">
<Linkedin className="h-4 w-4" />
</Button>
<Button variant="outline" size="icon">
<Mail className="h-4 w-4" />
</Button>
<Button variant="outline" size="icon">
<Phone className="h-4 w-4" />
</Button>
</div>
</div>
</DialogHeader>
<Tabs defaultValue="info" className="mt-4">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="info">Informacion</TabsTrigger>
<TabsTrigger value="timeline">Timeline</TabsTrigger>
<TabsTrigger value="evaluations">Evaluaciones</TabsTrigger>
<TabsTrigger value="documents">Documentos</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4 mt-4">
<div className="grid grid-cols-2 gap-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Contacto</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<Mail className="h-4 w-4 text-muted-foreground" />
{selectedCandidate.email}
</div>
<div className="flex items-center gap-2 text-sm">
<Phone className="h-4 w-4 text-muted-foreground" />
{selectedCandidate.phone}
</div>
{selectedCandidate.linkedin && (
<div className="flex items-center gap-2 text-sm">
<Linkedin className="h-4 w-4 text-muted-foreground" />
<a href={selectedCandidate.linkedin} className="text-primary hover:underline">
Ver perfil
</a>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Expectativas</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<DollarSign className="h-4 w-4 text-muted-foreground" />
{selectedCandidate.salaryExpectation || "No especificado"}
</div>
<div className="flex items-center gap-2 text-sm">
<Clock className="h-4 w-4 text-muted-foreground" />
Disponibilidad: {selectedCandidate.availability || "No especificada"}
</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Vacante Aplicada</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between">
<div>
<div className="font-medium">{getRequisitionTitle(selectedCandidate.requisitionId)}</div>
<div className="text-sm text-muted-foreground">
Aplicado el {new Date(selectedCandidate.appliedDate).toLocaleDateString("es-MX", {
day: "numeric",
month: "long",
year: "numeric"
})}
</div>
</div>
<Button variant="outline" size="sm">
Ver Requisicion
</Button>
</div>
</CardContent>
</Card>
{selectedCandidate.notes && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Notas</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">{selectedCandidate.notes}</p>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="timeline" className="mt-4">
<Card>
<CardContent className="p-4">
<div className="space-y-4">
{selectedCandidate.history?.map((event, index) => (
<div key={index} className="flex gap-4">
<div className="flex flex-col items-center">
<div className={cn(
"w-8 h-8 rounded-full flex items-center justify-center",
event.type === "stage_change" && "bg-primary/10 text-primary",
event.type === "note" && "bg-secondary/10 text-secondary",
event.type === "interview" && "bg-accent/10 text-accent",
event.type === "evaluation" && "bg-blue-500/10 text-blue-500"
)}>
{event.type === "stage_change" && <ArrowRight className="h-4 w-4" />}
{event.type === "note" && <MessageSquare className="h-4 w-4" />}
{event.type === "interview" && <Video className="h-4 w-4" />}
{event.type === "evaluation" && <Star className="h-4 w-4" />}
</div>
{index < (selectedCandidate.history?.length || 0) - 1 && (
<div className="w-px h-full bg-border mt-2" />
)}
</div>
<div className="flex-1 pb-4">
<div className="flex items-center justify-between">
<h4 className="font-medium text-sm">{event.title}</h4>
<span className="text-xs text-muted-foreground">
{new Date(event.date).toLocaleDateString("es-MX")}
</span>
</div>
<p className="text-sm text-muted-foreground mt-1">{event.description}</p>
{event.user && (
<p className="text-xs text-muted-foreground mt-1">Por: {event.user}</p>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="evaluations" className="mt-4">
<Card>
<CardContent className="p-4">
<div className="space-y-4">
{selectedCandidate.evaluations?.map((evaluation, index) => (
<Card key={index}>
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div>
<h4 className="font-medium">{evaluation.stage}</h4>
<p className="text-sm text-muted-foreground">
Evaluado por {evaluation.evaluator} - {new Date(evaluation.date).toLocaleDateString("es-MX")}
</p>
</div>
<div className="flex items-center gap-2">
<Badge variant={evaluation.recommendation === "hire" ? "default" : evaluation.recommendation === "reject" ? "destructive" : "secondary"}>
{evaluation.recommendation === "hire" ? "Contratar" : evaluation.recommendation === "reject" ? "Rechazar" : "Continuar"}
</Badge>
<div className="flex items-center gap-1">
{getRatingStars(evaluation.score)}
</div>
</div>
</div>
<p className="text-sm mt-3">{evaluation.comments}</p>
</CardContent>
</Card>
)) || (
<div className="text-center py-8 text-muted-foreground">
No hay evaluaciones registradas
</div>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="documents" className="mt-4">
<Card>
<CardContent className="p-4">
<div className="space-y-3">
{selectedCandidate.documents?.map((doc, index) => (
<div key={index} className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center">
<FileText className="h-5 w-5 text-primary" />
</div>
<div>
<div className="font-medium text-sm">{doc.name}</div>
<div className="text-xs text-muted-foreground">
Subido el {new Date(doc.uploadedAt).toLocaleDateString("es-MX")}
</div>
</div>
</div>
<Button variant="ghost" size="icon">
<Download className="h-4 w-4" />
</Button>
</div>
)) || (
<div className="text-center py-8 text-muted-foreground">
No hay documentos adjuntos
</div>
)}
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
<DialogFooter className="gap-2 mt-4">
<Button variant="outline">
<XCircle className="mr-2 h-4 w-4" />
Rechazar
</Button>
<Button variant="outline">
<Calendar className="mr-2 h-4 w-4" />
Agendar Entrevista
</Button>
<Button className="bg-accent hover:bg-accent/90">
<ArrowRight className="mr-2 h-4 w-4" />
Siguiente Etapa
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
</div>
)
}
+528
View File
@@ -0,0 +1,528 @@
"use client"
import { useState } from "react"
import { mockRequisitions, mockCandidates, mockDepartments } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import {
BarChart3,
TrendingUp,
TrendingDown,
Download,
Calendar,
Users,
Clock,
Target,
Building2,
Briefcase,
CheckCircle2,
XCircle,
PieChart,
Activity,
ArrowUpRight,
ArrowDownRight,
FileText,
Filter
} from "lucide-react"
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
LineChart,
Line,
PieChart as RechartsPieChart,
Pie,
Cell,
AreaChart,
Area
} from "recharts"
// Sample data for charts
const requisitionsByMonth = [
{ month: "Ene", creadas: 12, aprobadas: 10, cubiertas: 8 },
{ month: "Feb", creadas: 15, aprobadas: 13, cubiertas: 11 },
{ month: "Mar", creadas: 18, aprobadas: 16, cubiertas: 14 },
{ month: "Abr", creadas: 14, aprobadas: 12, cubiertas: 10 },
{ month: "May", creadas: 20, aprobadas: 18, cubiertas: 15 },
{ month: "Jun", creadas: 16, aprobadas: 14, cubiertas: 12 }
]
const candidatesBySource = [
{ name: "LinkedIn", value: 45, color: "#0077B5" },
{ name: "Referidos", value: 25, color: "#61ce70" },
{ name: "Portal Empleo", value: 18, color: "#6ec1e4" },
{ name: "Website", value: 8, color: "#4054b2" },
{ name: "Agencias", value: 4, color: "#54595f" }
]
const timeToHire = [
{ month: "Ene", dias: 35 },
{ month: "Feb", dias: 32 },
{ month: "Mar", dias: 28 },
{ month: "Abr", dias: 30 },
{ month: "May", dias: 25 },
{ month: "Jun", dias: 22 }
]
const requisitionsByDepartment = [
{ name: "Tecnologia", abiertas: 8, cubiertas: 15 },
{ name: "Ventas", abiertas: 5, cubiertas: 12 },
{ name: "Marketing", abiertas: 3, cubiertas: 8 },
{ name: "Operaciones", abiertas: 4, cubiertas: 10 },
{ name: "Finanzas", abiertas: 2, cubiertas: 6 },
{ name: "RR.HH.", abiertas: 1, cubiertas: 4 }
]
const pipelineConversion = [
{ stage: "Aplicados", count: 500, percentage: 100 },
{ stage: "Screening", count: 250, percentage: 50 },
{ stage: "Entrevista RH", count: 120, percentage: 24 },
{ stage: "Entrevista Tec", count: 60, percentage: 12 },
{ stage: "Entrevista Ger", count: 30, percentage: 6 },
{ stage: "Oferta", count: 15, percentage: 3 },
{ stage: "Contratados", count: 12, percentage: 2.4 }
]
export function ReportsPage() {
const [dateRange, setDateRange] = useState("6m")
const [selectedDepartment, setSelectedDepartment] = useState("all")
// Calculate stats
const totalRequisitions = mockRequisitions.length
const openRequisitions = mockRequisitions.filter(r =>
["draft", "pending", "approved", "published"].includes(r.status)
).length
const closedRequisitions = mockRequisitions.filter(r =>
["filled", "cancelled"].includes(r.status)
).length
const totalCandidates = mockCandidates.length
const hiredCandidates = mockCandidates.filter(c => c.currentStage === "hired").length
const avgTimeToHire = 27 // days
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Reportes y Analitica</h1>
<p className="text-muted-foreground">
Metricas y estadisticas del proceso de reclutamiento
</p>
</div>
<div className="flex items-center gap-3">
<Select value={dateRange} onValueChange={setDateRange}>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Periodo" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1m">Ultimo mes</SelectItem>
<SelectItem value="3m">Ultimos 3 meses</SelectItem>
<SelectItem value="6m">Ultimos 6 meses</SelectItem>
<SelectItem value="1y">Ultimo ano</SelectItem>
</SelectContent>
</Select>
<Button variant="outline">
<Download className="mr-2 h-4 w-4" />
Exportar
</Button>
</div>
</div>
{/* KPIs */}
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<Briefcase className="h-5 w-5 text-primary" />
<Badge variant="secondary" className="text-xs">
<ArrowUpRight className="h-3 w-3 mr-1" />
12%
</Badge>
</div>
<div className="text-2xl font-bold">{totalRequisitions}</div>
<div className="text-xs text-muted-foreground">Total Requisiciones</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<Target className="h-5 w-5 text-accent" />
<Badge className="bg-accent/10 text-accent text-xs">Activas</Badge>
</div>
<div className="text-2xl font-bold">{openRequisitions}</div>
<div className="text-xs text-muted-foreground">Vacantes Abiertas</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<Users className="h-5 w-5 text-blue-500" />
<Badge variant="secondary" className="text-xs">
<ArrowUpRight className="h-3 w-3 mr-1" />
8%
</Badge>
</div>
<div className="text-2xl font-bold">{totalCandidates}</div>
<div className="text-xs text-muted-foreground">Total Candidatos</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<CheckCircle2 className="h-5 w-5 text-accent" />
<Badge className="bg-accent/10 text-accent text-xs">
<ArrowUpRight className="h-3 w-3 mr-1" />
15%
</Badge>
</div>
<div className="text-2xl font-bold">{hiredCandidates}</div>
<div className="text-xs text-muted-foreground">Contratados</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<Clock className="h-5 w-5 text-secondary" />
<Badge variant="secondary" className="text-xs">
<ArrowDownRight className="h-3 w-3 mr-1 text-accent" />
-5 dias
</Badge>
</div>
<div className="text-2xl font-bold">{avgTimeToHire}d</div>
<div className="text-xs text-muted-foreground">Tiempo Promedio</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between mb-2">
<Activity className="h-5 w-5 text-purple-500" />
</div>
<div className="text-2xl font-bold">2.4%</div>
<div className="text-xs text-muted-foreground">Tasa Conversion</div>
</CardContent>
</Card>
</div>
<Tabs defaultValue="overview" className="space-y-6">
<TabsList>
<TabsTrigger value="overview">Vision General</TabsTrigger>
<TabsTrigger value="requisitions">Requisiciones</TabsTrigger>
<TabsTrigger value="candidates">Candidatos</TabsTrigger>
<TabsTrigger value="pipeline">Pipeline</TabsTrigger>
</TabsList>
<TabsContent value="overview" className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Requisitions Trend */}
<Card>
<CardHeader>
<CardTitle className="text-base">Tendencia de Requisiciones</CardTitle>
<CardDescription>Requisiciones creadas, aprobadas y cubiertas</CardDescription>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={requisitionsByMonth}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis dataKey="month" className="text-xs" />
<YAxis className="text-xs" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px"
}}
/>
<Legend />
<Bar dataKey="creadas" fill="#6ec1e4" name="Creadas" radius={[4, 4, 0, 0]} />
<Bar dataKey="aprobadas" fill="#4054b2" name="Aprobadas" radius={[4, 4, 0, 0]} />
<Bar dataKey="cubiertas" fill="#61ce70" name="Cubiertas" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
{/* Candidates by Source */}
<Card>
<CardHeader>
<CardTitle className="text-base">Candidatos por Fuente</CardTitle>
<CardDescription>Distribucion de fuentes de reclutamiento</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-center">
<ResponsiveContainer width="100%" height={300}>
<RechartsPieChart>
<Pie
data={candidatesBySource}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
paddingAngle={2}
dataKey="value"
label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
>
{candidatesBySource.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip />
</RechartsPieChart>
</ResponsiveContainer>
</div>
<div className="flex flex-wrap justify-center gap-4 mt-4">
{candidatesBySource.map((source) => (
<div key={source.name} className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: source.color }} />
<span className="text-sm">{source.name}</span>
</div>
))}
</div>
</CardContent>
</Card>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Time to Hire */}
<Card>
<CardHeader>
<CardTitle className="text-base">Tiempo Promedio de Contratacion</CardTitle>
<CardDescription>Dias promedio desde aplicacion hasta contratacion</CardDescription>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={250}>
<AreaChart data={timeToHire}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis dataKey="month" className="text-xs" />
<YAxis className="text-xs" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px"
}}
/>
<Area
type="monotone"
dataKey="dias"
stroke="#6ec1e4"
fill="#6ec1e4"
fillOpacity={0.3}
name="Dias"
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
{/* Requisitions by Department */}
<Card>
<CardHeader>
<CardTitle className="text-base">Requisiciones por Departamento</CardTitle>
<CardDescription>Vacantes abiertas vs cubiertas por area</CardDescription>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={250}>
<BarChart data={requisitionsByDepartment} layout="vertical">
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis type="number" className="text-xs" />
<YAxis dataKey="name" type="category" className="text-xs" width={80} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px"
}}
/>
<Legend />
<Bar dataKey="abiertas" fill="#6ec1e4" name="Abiertas" radius={[0, 4, 4, 0]} />
<Bar dataKey="cubiertas" fill="#61ce70" name="Cubiertas" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
</div>
</TabsContent>
<TabsContent value="requisitions" className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<Card className="lg:col-span-2">
<CardHeader>
<CardTitle className="text-base">Estado de Requisiciones</CardTitle>
<CardDescription>Distribucion por estado actual</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{[
{ status: "Borrador", count: 3, color: "bg-muted" },
{ status: "Pendiente Aprobacion", count: 5, color: "bg-yellow-500" },
{ status: "Aprobada", count: 8, color: "bg-blue-500" },
{ status: "Publicada", count: 12, color: "bg-primary" },
{ status: "En Proceso", count: 15, color: "bg-purple-500" },
{ status: "Cubierta", count: 25, color: "bg-accent" },
{ status: "Cancelada", count: 2, color: "bg-destructive" }
].map(item => (
<div key={item.status} className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium">{item.status}</span>
<span className="text-sm text-muted-foreground">{item.count}</span>
</div>
<Progress
value={(item.count / 70) * 100}
className="h-2"
/>
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Prioridad de Vacantes</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between p-3 bg-destructive/10 rounded-lg">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-destructive" />
<span className="text-sm font-medium">Urgente</span>
</div>
<span className="font-bold">5</span>
</div>
<div className="flex items-center justify-between p-3 bg-yellow-500/10 rounded-lg">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-yellow-500" />
<span className="text-sm font-medium">Alta</span>
</div>
<span className="font-bold">12</span>
</div>
<div className="flex items-center justify-between p-3 bg-primary/10 rounded-lg">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-primary" />
<span className="text-sm font-medium">Media</span>
</div>
<span className="font-bold">18</span>
</div>
<div className="flex items-center justify-between p-3 bg-muted rounded-lg">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-muted-foreground" />
<span className="text-sm font-medium">Baja</span>
</div>
<span className="font-bold">8</span>
</div>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
<TabsContent value="candidates" className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle className="text-base">Candidatos por Etapa</CardTitle>
<CardDescription>Distribucion actual en el pipeline</CardDescription>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={pipelineConversion}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis dataKey="stage" className="text-xs" angle={-45} textAnchor="end" height={80} />
<YAxis className="text-xs" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px"
}}
/>
<Bar dataKey="count" fill="#6ec1e4" name="Candidatos" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Metricas de Candidatos</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm">Tasa de Respuesta</span>
<span className="font-bold">78%</span>
</div>
<Progress value={78} className="h-2" />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm">Tasa de Entrevista</span>
<span className="font-bold">45%</span>
</div>
<Progress value={45} className="h-2" />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm">Tasa de Oferta</span>
<span className="font-bold">12%</span>
</div>
<Progress value={12} className="h-2" />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm">Tasa de Aceptacion</span>
<span className="font-bold">85%</span>
</div>
<Progress value={85} className="h-2" />
</div>
</CardContent>
</Card>
</div>
</TabsContent>
<TabsContent value="pipeline" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base">Funnel de Conversion</CardTitle>
<CardDescription>Conversion de candidatos a traves del pipeline</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{pipelineConversion.map((stage, index) => (
<div key={stage.stage} className="relative">
<div className="flex items-center gap-4">
<div className="w-24 text-sm font-medium">{stage.stage}</div>
<div className="flex-1">
<div
className="h-10 bg-primary/20 rounded-lg flex items-center px-4 transition-all"
style={{ width: `${stage.percentage}%`, minWidth: "80px" }}
>
<span className="font-bold text-primary">{stage.count}</span>
</div>
</div>
<div className="w-16 text-right text-sm text-muted-foreground">
{stage.percentage}%
</div>
</div>
{index < pipelineConversion.length - 1 && (
<div className="ml-12 pl-4 border-l-2 border-dashed border-muted h-4" />
)}
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
)
}
@@ -0,0 +1,706 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
ArrowLeft,
Edit,
Clock,
Users,
MapPin,
Building2,
Calendar,
AlertTriangle,
CheckCircle2,
XCircle,
Send,
RefreshCw,
UserPlus,
FileText,
History,
MessageSquare,
Briefcase,
DollarSign,
Target,
ChevronRight,
Ban,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { requisitions, auditLog, users, recruiterCapacity } from '@/lib/mock-data'
import {
STATUS_CONFIG,
URGENCY_CONFIG,
STAGE_CONFIG,
type Requisition,
type CandidateStage
} from '@/lib/types'
import { toast } from 'sonner'
function getInitials(name: string): string {
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
}
function getDaysUntilDeadline(deadline: string): number {
const now = new Date()
const deadlineDate = new Date(deadline)
return Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
}
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString('es-ES', {
day: '2-digit',
month: 'long',
year: 'numeric',
})
}
function formatDateTime(dateString: string): string {
return new Date(dateString).toLocaleString('es-ES', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
// Status flow visualization component
function StatusFlow({ currentStatus }: { currentStatus: Requisition['status'] }) {
const steps = [
{ key: 'borrador', label: 'Borrador', icon: FileText },
{ key: 'pendiente_rrhh', label: 'RR.HH.', icon: Users },
{ key: 'pendiente_admin', label: 'Admin', icon: Building2 },
{ key: 'reclutando', label: 'Reclutando', icon: Briefcase },
{ key: 'cerrado', label: 'Cerrado', icon: CheckCircle2 },
]
const currentIndex = steps.findIndex(s => s.key === currentStatus)
const isCancelled = currentStatus === 'cancelado'
const isCorrection = currentStatus === 'correccion_requerida'
return (
<div className="relative overflow-x-auto pb-4">
<div className="flex items-center justify-between min-w-[500px]">
{steps.map((step, index) => {
const Icon = step.icon
const isCompleted = index < currentIndex && !isCancelled
const isCurrent = step.key === currentStatus
const isPending = index > currentIndex
return (
<React.Fragment key={step.key}>
<div className="flex flex-col items-center gap-2">
<div className={cn(
'flex h-10 w-10 items-center justify-center rounded-full border-2 transition-colors',
isCompleted && 'border-emerald-500 bg-emerald-500 text-white',
isCurrent && !isCancelled && 'border-primary bg-primary text-primary-foreground',
isPending && 'border-muted-foreground/30 bg-muted text-muted-foreground',
isCancelled && 'border-red-500 bg-red-500 text-white',
isCorrection && isCurrent && 'border-amber-500 bg-amber-500 text-white'
)}>
{isCompleted ? (
<CheckCircle2 className="h-5 w-5" />
) : isCancelled ? (
<XCircle className="h-5 w-5" />
) : (
<Icon className="h-5 w-5" />
)}
</div>
<span className={cn(
'text-xs font-medium',
(isCompleted || isCurrent) && 'text-foreground',
isPending && 'text-muted-foreground'
)}>
{step.label}
</span>
</div>
{index < steps.length - 1 && (
<div className={cn(
'flex-1 h-0.5 mx-2 -mt-6',
index < currentIndex ? 'bg-emerald-500' : 'bg-muted-foreground/30'
)} />
)}
</React.Fragment>
)
})}
</div>
{isCorrection && (
<div className="mt-4 flex items-center justify-center gap-2 text-amber-600">
<AlertTriangle className="h-4 w-4" />
<span className="text-sm font-medium">Corrección requerida - Regresado a solicitante</span>
</div>
)}
</div>
)
}
// Recruitment stages component
function RecruitmentStages({ currentStage }: { currentStage?: CandidateStage }) {
if (!currentStage) return null
const stages: CandidateStage[] = ['reclutando', 'primera_entrevista', 'segunda_entrevista', 'referencias', 'examenes_medicos', 'seleccionado']
const currentIndex = stages.indexOf(currentStage)
return (
<div className="space-y-3">
{stages.map((stage, index) => {
const config = STAGE_CONFIG[stage]
const isCompleted = index < currentIndex
const isCurrent = stage === currentStage
return (
<div key={stage} className="flex items-center gap-3">
<div className={cn(
'flex h-8 w-8 items-center justify-center rounded-full text-xs font-medium',
isCompleted && 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
isCurrent && 'bg-primary text-primary-foreground',
!isCompleted && !isCurrent && 'bg-muted text-muted-foreground'
)}>
{isCompleted ? <CheckCircle2 className="h-4 w-4" /> : index + 1}
</div>
<span className={cn(
'text-sm',
isCurrent && 'font-medium text-foreground',
isCompleted && 'text-muted-foreground line-through',
!isCompleted && !isCurrent && 'text-muted-foreground'
)}>
{config.label}
</span>
</div>
)
})}
</div>
)
}
interface RequisitionDetailPageProps {
requisitionId: string
}
export function RequisitionDetailPage({ requisitionId }: RequisitionDetailPageProps) {
const router = useRouter()
const [cancelDialogOpen, setCancelDialogOpen] = React.useState(false)
const [assignDialogOpen, setAssignDialogOpen] = React.useState(false)
const [cancelReason, setCancelReason] = React.useState('')
const [selectedRecruiter, setSelectedRecruiter] = React.useState('')
const requisition = requisitions.find(r => r.id === requisitionId)
if (!requisition) {
return (
<div className="flex flex-col items-center justify-center h-[60vh]">
<AlertTriangle className="h-12 w-12 text-muted-foreground mb-4" />
<h2 className="text-lg font-semibold">Requisición no encontrada</h2>
<p className="text-muted-foreground mb-4">La requisición {requisitionId} no existe.</p>
<Button asChild>
<Link href="/requisiciones">Volver a requisiciones</Link>
</Button>
</div>
)
}
const status = STATUS_CONFIG[requisition.status]
const urgency = URGENCY_CONFIG[requisition.urgency]
const daysLeft = getDaysUntilDeadline(requisition.hardDeadline)
const isOverdue = daysLeft < 0
const isAtRisk = daysLeft >= 0 && daysLeft <= 7
const progress = (requisition.vacanciesFilled / requisition.quantity) * 100
const relatedAuditLog = auditLog.filter(log => log.entityId === requisitionId)
const recruiters = users.filter(u => u.role === 'reclutador' && u.active)
const handleCancel = () => {
toast.success('Requisición cancelada', {
description: `${requisition.id} ha sido cancelada.`,
})
setCancelDialogOpen(false)
router.push('/requisiciones')
}
const handleAssignRecruiter = () => {
const recruiter = recruiters.find(r => r.id === selectedRecruiter)
toast.success('Reclutador asignado', {
description: `${recruiter?.name} ha sido asignado a ${requisition.id}.`,
})
setAssignDialogOpen(false)
}
return (
<div className="p-6 space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="flex items-start gap-4">
<Button variant="ghost" size="icon" asChild>
<Link href="/requisiciones">
<ArrowLeft className="h-4 w-4" />
</Link>
</Button>
<div>
<div className="flex items-center gap-3 mb-1">
<h1 className="text-2xl font-bold tracking-tight">{requisition.id}</h1>
<Badge variant="outline" className={cn(status.color, status.bgColor, status.borderColor)}>
{status.label}
</Badge>
<Badge variant="outline" className={cn('text-xs', urgency.color, urgency.bgColor)}>
{urgency.label}
</Badge>
</div>
<p className="text-muted-foreground">
{requisition.positionName} - {requisition.quantity} vacante{requisition.quantity > 1 ? 's' : ''}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{requisition.status === 'borrador' && (
<>
<Button variant="outline" asChild>
<Link href={`/requisiciones/${requisition.id}/editar`}>
<Edit className="mr-2 h-4 w-4" />
Editar
</Link>
</Button>
<Button>
<Send className="mr-2 h-4 w-4" />
Enviar a Aprobación
</Button>
</>
)}
{requisition.status === 'correccion_requerida' && (
<Button asChild>
<Link href={`/requisiciones/${requisition.id}/editar`}>
<RefreshCw className="mr-2 h-4 w-4" />
Corregir y Reenviar
</Link>
</Button>
)}
{requisition.status === 'reclutando' && !requisition.recruiterId && (
<Dialog open={assignDialogOpen} onOpenChange={setAssignDialogOpen}>
<DialogTrigger asChild>
<Button>
<UserPlus className="mr-2 h-4 w-4" />
Asignar Reclutador
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Asignar Reclutador</DialogTitle>
<DialogDescription>
Selecciona el reclutador que gestionará esta requisición.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Reclutador</Label>
<Select value={selectedRecruiter} onValueChange={setSelectedRecruiter}>
<SelectTrigger>
<SelectValue placeholder="Seleccionar reclutador" />
</SelectTrigger>
<SelectContent>
{recruiters.map((recruiter) => {
const capacity = recruiterCapacity.find(c => c.recruiterId === recruiter.id)
return (
<SelectItem key={recruiter.id} value={recruiter.id}>
<div className="flex items-center gap-2">
<span>{recruiter.name}</span>
{capacity && (
<span className="text-xs text-muted-foreground">
(Score: {capacity.currentScore}/{capacity.maxThreshold})
</span>
)}
</div>
</SelectItem>
)
})}
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setAssignDialogOpen(false)}>
Cancelar
</Button>
<Button onClick={handleAssignRecruiter} disabled={!selectedRecruiter}>
Asignar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
{!['cerrado', 'cancelado'].includes(requisition.status) && (
<Dialog open={cancelDialogOpen} onOpenChange={setCancelDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" className="text-destructive hover:text-destructive">
<Ban className="mr-2 h-4 w-4" />
Cancelar
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Cancelar Requisición</DialogTitle>
<DialogDescription>
Esta acción no se puede deshacer. La requisición quedará marcada como cancelada.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="cancelReason">Motivo de cancelación *</Label>
<Textarea
id="cancelReason"
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder="Describe el motivo de la cancelación..."
rows={3}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCancelDialogOpen(false)}>
Volver
</Button>
<Button variant="destructive" onClick={handleCancel} disabled={!cancelReason.trim()}>
Confirmar Cancelación
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</div>
</div>
{/* Status Flow */}
<Card>
<CardHeader>
<CardTitle className="text-base">Estado del Proceso</CardTitle>
</CardHeader>
<CardContent>
<StatusFlow currentStatus={requisition.status} />
</CardContent>
</Card>
{/* Main Content */}
<div className="grid gap-6 lg:grid-cols-3">
{/* Left Column - Details */}
<div className="lg:col-span-2 space-y-6">
{/* Rejection Comment */}
{requisition.rejectionComment && (
<Card className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/30">
<CardContent className="p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
<div>
<p className="font-medium text-amber-800 dark:text-amber-200">Corrección Requerida</p>
<p className="text-sm text-amber-700 dark:text-amber-300 mt-1">
{requisition.rejectionComment}
</p>
</div>
</div>
</CardContent>
</Card>
)}
{/* Info Tabs */}
<Tabs defaultValue="detalles">
<TabsList>
<TabsTrigger value="detalles">Detalles</TabsTrigger>
<TabsTrigger value="historial">Historial</TabsTrigger>
{requisition.status === 'reclutando' && (
<TabsTrigger value="pipeline">Pipeline</TabsTrigger>
)}
</TabsList>
<TabsContent value="detalles" className="mt-4">
<Card>
<CardContent className="p-6 space-y-6">
{/* Basic Info */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
Información de la Vacante
</h3>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Posición</p>
<p className="font-medium">{requisition.positionName}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Departamento</p>
<p className="font-medium">{requisition.departmentName}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Ubicación</p>
<p className="font-medium">{requisition.cityName}, {requisition.countryName}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Modalidad</p>
<p className="font-medium capitalize">{requisition.modalidad}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Tipo de Contratación</p>
<p className="font-medium capitalize">{requisition.tipoContratacion}</p>
</div>
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Cantidad de Vacantes</p>
<p className="font-medium">{requisition.quantity}</p>
</div>
</div>
</div>
<Separator />
{/* Justification */}
<div>
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
Justificación
</h3>
<p className="text-sm leading-relaxed">{requisition.justification}</p>
</div>
{/* Compensation (if visible) */}
{(requisition.salaryPackage || requisition.budget) && (
<>
<Separator />
<div>
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
Compensación
</h3>
<div className="grid gap-4 sm:grid-cols-2">
{requisition.salaryPackage && (
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Paquete Salarial</p>
<p className="font-medium">{requisition.salaryPackage}</p>
</div>
)}
{requisition.budget && (
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Presupuesto</p>
<p className="font-medium">
{requisition.currency} {requisition.budget.toLocaleString()}
</p>
</div>
)}
</div>
</div>
</>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="historial" className="mt-4">
<Card>
<CardContent className="p-6">
<ScrollArea className="h-[400px] pr-4">
<div className="relative pl-6 border-l-2 border-muted space-y-6">
{relatedAuditLog.map((log, index) => (
<div key={log.id} className="relative">
<div className="absolute -left-[25px] h-3 w-3 rounded-full bg-primary" />
<div className="space-y-1">
<div className="flex items-center justify-between">
<p className="font-medium text-sm">{log.action}</p>
<span className="text-xs text-muted-foreground">
{formatDateTime(log.createdAt)}
</span>
</div>
<p className="text-sm text-muted-foreground">Por {log.userName}</p>
{log.oldValue && log.newValue && (
<div className="flex items-center gap-2 text-xs mt-1">
<Badge variant="outline" className="text-muted-foreground">
{log.oldValue}
</Badge>
<ChevronRight className="h-3 w-3 text-muted-foreground" />
<Badge variant="outline">
{log.newValue}
</Badge>
</div>
)}
</div>
</div>
))}
</div>
</ScrollArea>
</CardContent>
</Card>
</TabsContent>
{requisition.status === 'reclutando' && (
<TabsContent value="pipeline" className="mt-4">
<Card>
<CardHeader>
<CardTitle className="text-base">Etapas de Reclutamiento</CardTitle>
<CardDescription>Progreso del proceso de selección</CardDescription>
</CardHeader>
<CardContent>
<RecruitmentStages currentStage={requisition.currentStage} />
</CardContent>
</Card>
</TabsContent>
)}
</Tabs>
</div>
{/* Right Column - Summary */}
<div className="space-y-6">
{/* SLA Card */}
<Card className={cn(
isOverdue && 'border-red-200 dark:border-red-800',
isAtRisk && !isOverdue && 'border-amber-200 dark:border-amber-800'
)}>
<CardHeader className="pb-2">
<CardTitle className="text-base flex items-center gap-2">
<Target className="h-4 w-4" />
SLA
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Fecha límite</span>
<span className="font-medium">{formatDate(requisition.hardDeadline)}</span>
</div>
<div className={cn(
'flex items-center justify-between',
isOverdue && 'text-red-600 dark:text-red-400',
isAtRisk && !isOverdue && 'text-amber-600 dark:text-amber-400'
)}>
<span className="text-sm">Días restantes</span>
<span className="font-semibold text-lg">
{isOverdue ? `${Math.abs(daysLeft)} días vencido` : `${daysLeft} días`}
</span>
</div>
{(isOverdue || isAtRisk) && (
<div className={cn(
'flex items-center gap-2 rounded-lg p-3 text-sm',
isOverdue && 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
isAtRisk && !isOverdue && 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
)}>
<AlertTriangle className="h-4 w-4 shrink-0" />
<span>
{isOverdue ? 'SLA vencido - Acción inmediata requerida' : 'SLA en riesgo - Priorizar'}
</span>
</div>
)}
</CardContent>
</Card>
{/* Progress Card */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base flex items-center gap-2">
<Users className="h-4 w-4" />
Progreso de Vacantes
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-end justify-between">
<div>
<span className="text-3xl font-bold">{requisition.vacanciesFilled}</span>
<span className="text-muted-foreground"> / {requisition.quantity}</span>
</div>
<span className="text-sm text-muted-foreground">
{Math.round(progress)}% completado
</span>
</div>
<Progress value={progress} className="h-2" />
<p className="text-xs text-muted-foreground">
{requisition.quantity - requisition.vacanciesFilled} vacante{(requisition.quantity - requisition.vacanciesFilled) !== 1 ? 's' : ''} pendiente{(requisition.quantity - requisition.vacanciesFilled) !== 1 ? 's' : ''}
</p>
</CardContent>
</Card>
{/* Requester Card */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base">Solicitante</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-3">
<Avatar>
<AvatarFallback>{getInitials(requisition.requesterName)}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{requisition.requesterName}</p>
<p className="text-sm text-muted-foreground">{requisition.departmentName}</p>
</div>
</div>
<Separator className="my-4" />
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Fecha de creación</span>
<span>{formatDate(requisition.createdAt)}</span>
</div>
</div>
</CardContent>
</Card>
{/* Recruiter Card */}
{requisition.recruiterId && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base">Reclutador Asignado</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center gap-3">
<Avatar>
<AvatarFallback>{getInitials(requisition.recruiterName || '')}</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">{requisition.recruiterName}</p>
<p className="text-sm text-muted-foreground">Reclutador</p>
</div>
</div>
</CardContent>
</Card>
)}
{/* Approvals Card */}
{(requisition.approvedByHrAt || requisition.approvedByAdminAt) && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base">Aprobaciones</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{requisition.approvedByHrAt && (
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
<span>RR.HH. - {formatDate(requisition.approvedByHrAt)}</span>
</div>
)}
{requisition.approvedByAdminAt && (
<div className="flex items-center gap-2 text-sm">
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
<span>Administración - {formatDate(requisition.approvedByAdminAt)}</span>
</div>
)}
</CardContent>
</Card>
)}
</div>
</div>
</div>
)
}
+384
View File
@@ -0,0 +1,384 @@
'use client'
import * as React from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
PlusCircle,
Search,
Filter,
MoreHorizontal,
Eye,
Edit,
Clock,
Users,
MapPin,
Building2,
AlertTriangle,
CheckCircle2,
XCircle,
ArrowUpDown,
Download,
RefreshCw,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { requisitions, countries } from '@/lib/mock-data'
import { STATUS_CONFIG, URGENCY_CONFIG, type Requisition, type RequisitionStatus } from '@/lib/types'
function getDaysUntilDeadline(deadline: string): number {
const now = new Date()
const deadlineDate = new Date(deadline)
return Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
}
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString('es-ES', {
day: '2-digit',
month: 'short',
year: 'numeric',
})
}
interface RequisitionRowProps {
requisition: Requisition
}
function RequisitionTableRow({ requisition }: RequisitionRowProps) {
const status = STATUS_CONFIG[requisition.status]
const urgency = URGENCY_CONFIG[requisition.urgency]
const daysLeft = getDaysUntilDeadline(requisition.hardDeadline)
const isOverdue = daysLeft < 0
const isAtRisk = daysLeft >= 0 && daysLeft <= 7
return (
<TableRow className="group">
<TableCell className="font-medium">
<Link href={`/requisiciones/${requisition.id}`} className="hover:text-primary hover:underline">
{requisition.id}
</Link>
</TableCell>
<TableCell>
<div className="space-y-1">
<p className="font-medium text-sm">{requisition.positionName}</p>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<MapPin className="h-3 w-3" />
{requisition.cityName}, {requisition.countryName}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{requisition.vacanciesFilled}</span>
<span className="text-muted-foreground">/ {requisition.quantity}</span>
</div>
</TableCell>
<TableCell>
<Badge variant="outline" className={cn('text-xs', status.color, status.bgColor, status.borderColor)}>
{status.label}
</Badge>
</TableCell>
<TableCell>
<Badge variant="outline" className={cn('text-xs', urgency.color, urgency.bgColor)}>
{urgency.label}
</Badge>
</TableCell>
<TableCell>
<div className="flex items-center gap-2 text-sm">
<Building2 className="h-4 w-4 text-muted-foreground" />
{requisition.departmentName}
</div>
</TableCell>
<TableCell>
<div className={cn(
'flex items-center gap-1.5 text-sm',
isOverdue && 'text-red-600 dark:text-red-400',
isAtRisk && !isOverdue && 'text-amber-600 dark:text-amber-400'
)}>
{isOverdue ? (
<AlertTriangle className="h-4 w-4" />
) : isAtRisk ? (
<Clock className="h-4 w-4" />
) : (
<Clock className="h-4 w-4 text-muted-foreground" />
)}
<span>
{isOverdue
? `${Math.abs(daysLeft)}d vencido`
: `${daysLeft}d`
}
</span>
</div>
</TableCell>
<TableCell>
<span className="text-sm text-muted-foreground">{formatDate(requisition.createdAt)}</span>
</TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Acciones</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href={`/requisiciones/${requisition.id}`}>
<Eye className="mr-2 h-4 w-4" />
Ver detalles
</Link>
</DropdownMenuItem>
{requisition.status === 'borrador' && (
<DropdownMenuItem asChild>
<Link href={`/requisiciones/${requisition.id}/editar`}>
<Edit className="mr-2 h-4 w-4" />
Editar
</Link>
</DropdownMenuItem>
)}
{requisition.status === 'correccion_requerida' && (
<DropdownMenuItem asChild>
<Link href={`/requisiciones/${requisition.id}/editar`}>
<RefreshCw className="mr-2 h-4 w-4" />
Corregir y reenviar
</Link>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
)
}
export function RequisitionsListPage() {
const router = useRouter()
const searchParams = useSearchParams()
const [searchTerm, setSearchTerm] = React.useState('')
const [statusFilter, setStatusFilter] = React.useState<string>('all')
const [countryFilter, setCountryFilter] = React.useState<string>('all')
const [activeTab, setActiveTab] = React.useState('todas')
// Check for filter param
React.useEffect(() => {
const filter = searchParams.get('filter')
if (filter === 'urgent') {
setActiveTab('urgentes')
}
}, [searchParams])
const filteredRequisitions = React.useMemo(() => {
let filtered = [...requisitions]
// Search filter
if (searchTerm) {
const term = searchTerm.toLowerCase()
filtered = filtered.filter(r =>
r.id.toLowerCase().includes(term) ||
r.positionName.toLowerCase().includes(term) ||
r.cityName.toLowerCase().includes(term) ||
r.requesterName.toLowerCase().includes(term)
)
}
// Status filter
if (statusFilter !== 'all') {
filtered = filtered.filter(r => r.status === statusFilter)
}
// Country filter
if (countryFilter !== 'all') {
filtered = filtered.filter(r => r.countryId === countryFilter)
}
// Tab filter
if (activeTab === 'abiertas') {
filtered = filtered.filter(r => !['cerrado', 'cancelado'].includes(r.status))
} else if (activeTab === 'urgentes') {
filtered = filtered.filter(r => {
const daysLeft = getDaysUntilDeadline(r.hardDeadline)
return !['cerrado', 'cancelado'].includes(r.status) && daysLeft <= 7
})
} else if (activeTab === 'cerradas') {
filtered = filtered.filter(r => ['cerrado', 'cancelado'].includes(r.status))
}
// Sort by date (newest first)
filtered.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
return filtered
}, [searchTerm, statusFilter, countryFilter, activeTab])
const stats = React.useMemo(() => {
const open = requisitions.filter(r => !['cerrado', 'cancelado'].includes(r.status))
const urgent = open.filter(r => getDaysUntilDeadline(r.hardDeadline) <= 7)
const closed = requisitions.filter(r => ['cerrado', 'cancelado'].includes(r.status))
return {
all: requisitions.length,
open: open.length,
urgent: urgent.length,
closed: closed.length,
}
}, [])
return (
<div className="p-6 space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight">Requisiciones</h1>
<p className="text-muted-foreground">
Gestiona y da seguimiento a todas las requisiciones de vacantes
</p>
</div>
<Button asChild>
<Link href="/requisiciones/nueva">
<PlusCircle className="mr-2 h-4 w-4" />
Nueva Requisición
</Link>
</Button>
</div>
{/* Tabs */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-4 lg:w-[400px]">
<TabsTrigger value="todas" className="text-xs sm:text-sm">
Todas ({stats.all})
</TabsTrigger>
<TabsTrigger value="abiertas" className="text-xs sm:text-sm">
Abiertas ({stats.open})
</TabsTrigger>
<TabsTrigger value="urgentes" className="text-xs sm:text-sm">
<AlertTriangle className="mr-1 h-3 w-3" />
Urgentes ({stats.urgent})
</TabsTrigger>
<TabsTrigger value="cerradas" className="text-xs sm:text-sm">
Cerradas ({stats.closed})
</TabsTrigger>
</TabsList>
<Card className="mt-4">
<CardHeader className="pb-4">
{/* Filters */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Buscar por ID, posición, ciudad..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-9"
/>
</div>
<div className="flex items-center gap-2">
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger className="w-[180px] sm:w-[220px]">
<Filter className="mr-2 h-4 w-4" />
<SelectValue placeholder="Estado" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los estados</SelectItem>
{Object.entries(STATUS_CONFIG).map(([key, config]) => (
<SelectItem key={key} value={key}>
{config.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select value={countryFilter} onValueChange={setCountryFilter}>
<SelectTrigger className="w-[160px] sm:w-[200px]">
<SelectValue placeholder="País" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los países</SelectItem>
{countries.map((country) => (
<SelectItem key={country.id} value={country.id}>
{country.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="outline" size="icon">
<Download className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<TabsContent value={activeTab} className="mt-0">
{filteredRequisitions.length > 0 ? (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[120px]">ID</TableHead>
<TableHead>Posición</TableHead>
<TableHead className="w-[100px]">Vacantes</TableHead>
<TableHead className="w-[160px]">Estado</TableHead>
<TableHead className="w-[100px]">Urgencia</TableHead>
<TableHead>Departamento</TableHead>
<TableHead className="w-[110px]">
<div className="flex items-center gap-1">
SLA
<ArrowUpDown className="h-3 w-3" />
</div>
</TableHead>
<TableHead className="w-[110px]">Creada</TableHead>
<TableHead className="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredRequisitions.map((requisition) => (
<RequisitionTableRow key={requisition.id} requisition={requisition} />
))}
</TableBody>
</Table>
</div>
) : (
<div className="flex flex-col items-center justify-center py-12 text-center">
<div className="rounded-full bg-muted p-3 mb-4">
<Search className="h-6 w-6 text-muted-foreground" />
</div>
<h3 className="text-lg font-medium">No se encontraron requisiciones</h3>
<p className="text-sm text-muted-foreground mt-1">
Intenta ajustar los filtros de búsqueda
</p>
</div>
)}
</TabsContent>
</CardContent>
</Card>
</Tabs>
</div>
)
}
+550
View File
@@ -0,0 +1,550 @@
"use client"
import { useState } from "react"
import { mockDepartments, pipelineStages } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Separator } from "@/components/ui/separator"
import {
Settings,
Building2,
Users,
Bell,
Mail,
Shield,
Workflow,
Palette,
Globe,
Clock,
Plus,
Edit,
Trash2,
GripVertical,
CheckCircle2,
AlertCircle,
Save,
RefreshCw
} from "lucide-react"
import { cn } from "@/lib/utils"
export function SettingsPage() {
const [departments, setDepartments] = useState(mockDepartments)
const [isAddDeptOpen, setIsAddDeptOpen] = useState(false)
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Configuracion</h1>
<p className="text-muted-foreground">
Administra la configuracion del sistema
</p>
</div>
<Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
<Save className="mr-2 h-4 w-4" />
Guardar Cambios
</Button>
</div>
<Tabs defaultValue="general" className="space-y-6">
<TabsList className="grid w-full grid-cols-2 md:grid-cols-6 gap-2">
<TabsTrigger value="general">General</TabsTrigger>
<TabsTrigger value="departments">Departamentos</TabsTrigger>
<TabsTrigger value="workflow">Flujos</TabsTrigger>
<TabsTrigger value="notifications">Notificaciones</TabsTrigger>
<TabsTrigger value="templates">Plantillas</TabsTrigger>
<TabsTrigger value="integrations">Integraciones</TabsTrigger>
</TabsList>
{/* General Settings */}
<TabsContent value="general" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Building2 className="h-5 w-5 text-primary" />
Informacion de la Empresa
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Nombre de la Empresa</Label>
<Input defaultValue="Gomez Lee Marketing" />
</div>
<div className="space-y-2">
<Label>RFC</Label>
<Input defaultValue="GLM123456ABC" />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Email de Contacto</Label>
<Input defaultValue="rrhh@gomezlee.com" />
</div>
<div className="space-y-2">
<Label>Telefono</Label>
<Input defaultValue="+52 55 1234 5678" />
</div>
</div>
<div className="space-y-2">
<Label>Direccion</Label>
<Textarea defaultValue="Av. Insurgentes Sur 1234, Col. Del Valle, CDMX" />
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Globe className="h-5 w-5 text-primary" />
Configuracion Regional
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label>Idioma</Label>
<Select defaultValue="es">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="es">Espanol (Mexico)</SelectItem>
<SelectItem value="en">English (US)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Zona Horaria</Label>
<Select defaultValue="america_mexico">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="america_mexico">America/Mexico_City (GMT-6)</SelectItem>
<SelectItem value="america_monterrey">America/Monterrey (GMT-6)</SelectItem>
<SelectItem value="america_tijuana">America/Tijuana (GMT-8)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Formato de Fecha</Label>
<Select defaultValue="dd_mm_yyyy">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="dd_mm_yyyy">DD/MM/YYYY</SelectItem>
<SelectItem value="mm_dd_yyyy">MM/DD/YYYY</SelectItem>
<SelectItem value="yyyy_mm_dd">YYYY-MM-DD</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Shield className="h-5 w-5 text-primary" />
Seguridad
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Autenticacion de Dos Factores (2FA)</Label>
<p className="text-sm text-muted-foreground">
Requerir 2FA para todos los administradores
</p>
</div>
<Switch />
</div>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Expiracion de Sesion</Label>
<p className="text-sm text-muted-foreground">
Cerrar sesion automaticamente despues de inactividad
</p>
</div>
<Select defaultValue="30">
<SelectTrigger className="w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="15">15 minutos</SelectItem>
<SelectItem value="30">30 minutos</SelectItem>
<SelectItem value="60">1 hora</SelectItem>
<SelectItem value="120">2 horas</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Politica de Contrasenas</Label>
<p className="text-sm text-muted-foreground">
Requerir contrasenas fuertes (min 8 caracteres, mayusculas, numeros)
</p>
</div>
<Switch defaultChecked />
</div>
</CardContent>
</Card>
</TabsContent>
{/* Departments */}
<TabsContent value="departments" className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">Departamentos</CardTitle>
<CardDescription>Gestiona los departamentos de la organizacion</CardDescription>
</div>
<Dialog open={isAddDeptOpen} onOpenChange={setIsAddDeptOpen}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="mr-2 h-4 w-4" />
Agregar
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Nuevo Departamento</DialogTitle>
<DialogDescription>
Agrega un nuevo departamento a la organizacion
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Nombre</Label>
<Input placeholder="Ej: Recursos Humanos" />
</div>
<div className="space-y-2">
<Label>Codigo</Label>
<Input placeholder="Ej: RRHH" />
</div>
<div className="space-y-2">
<Label>Responsable</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar responsable" />
</SelectTrigger>
<SelectContent>
<SelectItem value="user1">Maria Garcia</SelectItem>
<SelectItem value="user2">Carlos Lopez</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Centro de Costo</Label>
<Input placeholder="Ej: CC-001" />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsAddDeptOpen(false)}>
Cancelar
</Button>
<Button onClick={() => setIsAddDeptOpen(false)}>
Crear
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{departments.map(dept => (
<div
key={dept.id}
className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
<Building2 className="h-5 w-5 text-primary" />
</div>
<div>
<div className="font-medium">{dept.name}</div>
<div className="text-sm text-muted-foreground">
Codigo: {dept.code} | CC: {dept.costCenter}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant={dept.isActive ? "default" : "secondary"}>
{dept.isActive ? "Activo" : "Inactivo"}
</Badge>
<Button variant="ghost" size="icon">
<Edit className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="text-destructive">
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
{/* Workflow Settings */}
<TabsContent value="workflow" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Workflow className="h-5 w-5 text-primary" />
Flujo de Aprobacion de Requisiciones
</CardTitle>
<CardDescription>
Configura los pasos de aprobacion para nuevas requisiciones
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-3">
{[
{ step: 1, name: "Gerente de Area", description: "Primera aprobacion por el solicitante" },
{ step: 2, name: "Recursos Humanos", description: "Validacion de perfil y compensacion" },
{ step: 3, name: "Administracion/Finanzas", description: "Aprobacion de presupuesto" },
{ step: 4, name: "Direccion General", description: "Aprobacion final (montos > $50,000)" }
].map((item, index) => (
<div key={item.step} className="flex items-center gap-4 p-4 border rounded-lg">
<div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary text-primary-foreground font-bold text-sm">
{item.step}
</div>
<div className="flex-1">
<div className="font-medium">{item.name}</div>
<div className="text-sm text-muted-foreground">{item.description}</div>
</div>
<div className="flex items-center gap-2">
<Switch defaultChecked />
<Button variant="ghost" size="icon">
<GripVertical className="h-4 w-4 text-muted-foreground" />
</Button>
</div>
</div>
))}
</div>
<Button variant="outline" className="w-full">
<Plus className="mr-2 h-4 w-4" />
Agregar Paso
</Button>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Etapas del Pipeline de Reclutamiento</CardTitle>
<CardDescription>
Configura las etapas del proceso de seleccion
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
{pipelineStages.map((stage, index) => (
<div key={stage.id} className="flex items-center gap-4 p-3 border rounded-lg">
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-muted text-muted-foreground text-xs font-bold">
{index + 1}
</div>
<div className="flex-1">
<Input defaultValue={stage.name} className="h-8" />
</div>
<div className="flex items-center gap-2">
<Switch defaultChecked />
<Button variant="ghost" size="icon">
<Trash2 className="h-4 w-4 text-muted-foreground" />
</Button>
<Button variant="ghost" size="icon">
<GripVertical className="h-4 w-4 text-muted-foreground" />
</Button>
</div>
</div>
))}
</div>
<Button variant="outline" className="w-full">
<Plus className="mr-2 h-4 w-4" />
Agregar Etapa
</Button>
</CardContent>
</Card>
</TabsContent>
{/* Notifications */}
<TabsContent value="notifications" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Bell className="h-5 w-5 text-primary" />
Notificaciones por Email
</CardTitle>
<CardDescription>
Configura cuando se envian notificaciones por email
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{[
{ title: "Nueva requisicion creada", description: "Notificar a RR.HH. cuando se crea una nueva requisicion" },
{ title: "Requisicion pendiente de aprobacion", description: "Recordatorio a aprobadores de requisiciones pendientes" },
{ title: "Requisicion aprobada", description: "Notificar al solicitante cuando su requisicion es aprobada" },
{ title: "Requisicion rechazada", description: "Notificar al solicitante cuando su requisicion es rechazada" },
{ title: "Nuevo candidato aplicado", description: "Notificar al reclutador cuando un candidato aplica" },
{ title: "Entrevista programada", description: "Recordatorio de entrevistas proximas" },
{ title: "Candidato cambia de etapa", description: "Notificar cuando un candidato avanza en el pipeline" }
].map(item => (
<div key={item.title} className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>{item.title}</Label>
<p className="text-sm text-muted-foreground">{item.description}</p>
</div>
<Switch defaultChecked />
</div>
))}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Clock className="h-5 w-5 text-primary" />
Recordatorios Automaticos
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Recordatorio de requisiciones pendientes</Label>
<p className="text-sm text-muted-foreground">
Enviar recordatorio despues de X dias sin accion
</p>
</div>
<Select defaultValue="3">
<SelectTrigger className="w-[120px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 dia</SelectItem>
<SelectItem value="2">2 dias</SelectItem>
<SelectItem value="3">3 dias</SelectItem>
<SelectItem value="5">5 dias</SelectItem>
<SelectItem value="7">7 dias</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Recordatorio de entrevistas</Label>
<p className="text-sm text-muted-foreground">
Enviar recordatorio antes de la entrevista
</p>
</div>
<Select defaultValue="24">
<SelectTrigger className="w-[120px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 hora</SelectItem>
<SelectItem value="2">2 horas</SelectItem>
<SelectItem value="24">24 horas</SelectItem>
<SelectItem value="48">48 horas</SelectItem>
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
</TabsContent>
{/* Email Templates */}
<TabsContent value="templates" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
Plantillas de Email
</CardTitle>
<CardDescription>
Personaliza las plantillas de correo electronico
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{[
{ name: "Confirmacion de Aplicacion", description: "Enviado a candidatos al aplicar" },
{ name: "Invitacion a Entrevista", description: "Invitacion para agendar entrevista" },
{ name: "Rechazo de Candidato", description: "Notificacion de rechazo" },
{ name: "Oferta de Trabajo", description: "Carta de oferta formal" },
{ name: "Bienvenida a Nuevo Empleado", description: "Email de onboarding" },
{ name: "Solicitud de Aprobacion", description: "Notificacion a aprobadores" }
].map(template => (
<div key={template.name} className="flex items-center justify-between p-4 border rounded-lg">
<div>
<div className="font-medium">{template.name}</div>
<div className="text-sm text-muted-foreground">{template.description}</div>
</div>
<Button variant="outline" size="sm">
<Edit className="mr-2 h-4 w-4" />
Editar
</Button>
</div>
))}
</CardContent>
</Card>
</TabsContent>
{/* Integrations */}
<TabsContent value="integrations" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base">Integraciones Disponibles</CardTitle>
<CardDescription>
Conecta con servicios externos para mejorar tu flujo de trabajo
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{[
{ name: "LinkedIn Recruiter", description: "Importar candidatos desde LinkedIn", connected: true },
{ name: "Google Calendar", description: "Sincronizar entrevistas con Google Calendar", connected: true },
{ name: "Microsoft Teams", description: "Crear reuniones de Teams automaticamente", connected: false },
{ name: "Zoom", description: "Generar links de Zoom para entrevistas", connected: false },
{ name: "Slack", description: "Notificaciones en canales de Slack", connected: false },
{ name: "Indeed", description: "Publicar vacantes en Indeed", connected: false }
].map(integration => (
<div key={integration.name} className="flex items-center justify-between p-4 border rounded-lg">
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center">
<Globe className="h-5 w-5" />
</div>
<div>
<div className="font-medium">{integration.name}</div>
<div className="text-sm text-muted-foreground">{integration.description}</div>
</div>
</div>
<div className="flex items-center gap-3">
{integration.connected && (
<Badge variant="outline" className="text-accent border-accent">
<CheckCircle2 className="mr-1 h-3 w-3" />
Conectado
</Badge>
)}
<Button variant={integration.connected ? "outline" : "default"} size="sm">
{integration.connected ? "Configurar" : "Conectar"}
</Button>
</div>
</div>
))}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
)
}
+487
View File
@@ -0,0 +1,487 @@
"use client"
import { useState } from "react"
import { mockUsers, mockDepartments } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
Search,
Plus,
MoreVertical,
Mail,
Phone,
Shield,
User,
Users,
Building2,
Edit,
Trash2,
Key,
CheckCircle2,
XCircle,
UserPlus,
Settings
} from "lucide-react"
import { cn } from "@/lib/utils"
import type { User, UserRole } from "@/lib/types"
const roleLabels: Record<UserRole, string> = {
admin_sistema: "Administrador",
director_rrhh: "Director RR.HH.",
rrhh_regional: "RR.HH. Regional",
rrhh_local: "RR.HH. Local",
reclutador: "Reclutador",
administracion: "Administración",
country_lead: "Country Lead",
solicitante: "Solicitante"
}
const roleColors: Record<UserRole, string> = {
admin_sistema: "bg-purple-500 text-white",
director_rrhh: "bg-primary text-primary-foreground",
rrhh_regional: "bg-blue-500 text-white",
rrhh_local: "bg-blue-400 text-white",
reclutador: "bg-accent text-accent-foreground",
administracion: "bg-secondary text-secondary-foreground",
country_lead: "bg-orange-500 text-white",
solicitante: "bg-muted text-muted-foreground"
}
export function UsersManagementPage() {
const [users, setUsers] = useState(mockUsers)
const [searchQuery, setSearchQuery] = useState("")
const [filterRole, setFilterRole] = useState<string>("all")
const [filterDepartment, setFilterDepartment] = useState<string>("all")
const [filterStatus, setFilterStatus] = useState<string>("all")
const [isNewUserOpen, setIsNewUserOpen] = useState(false)
const [selectedUser, setSelectedUser] = useState<User | null>(null)
const [isEditOpen, setIsEditOpen] = useState(false)
const filteredUsers = users.filter(user => {
const matchesSearch = user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
user.email.toLowerCase().includes(searchQuery.toLowerCase())
const matchesRole = filterRole === "all" || user.role === filterRole
const matchesDepartment = filterDepartment === "all" || user.departmentId === filterDepartment
const matchesStatus = filterStatus === "all" ||
(filterStatus === "active" && user.active) ||
(filterStatus === "inactive" && !user.active)
return matchesSearch && matchesRole && matchesDepartment && matchesStatus
})
const userStats = {
total: users.length,
active: users.filter(u => u.active).length,
inactive: users.filter(u => !u.active).length,
byRole: Object.keys(roleLabels).reduce((acc, role) => {
acc[role] = users.filter(u => u.role === role).length
return acc
}, {} as Record<string, number>)
}
const handleToggleStatus = (userId: string) => {
u.id === userId ? { ...u, active: !u.active } : u
}
const openEditDialog = (user: User) => {
setSelectedUser(user)
setIsEditOpen(true)
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Gestion de Usuarios</h1>
<p className="text-muted-foreground">
Administra los usuarios del sistema y sus permisos
</p>
</div>
<Dialog open={isNewUserOpen} onOpenChange={setIsNewUserOpen}>
<DialogTrigger asChild>
<Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
<UserPlus className="mr-2 h-4 w-4" />
Nuevo Usuario
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Crear Nuevo Usuario</DialogTitle>
<DialogDescription>
Ingresa la informacion del nuevo usuario
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="name">Nombre Completo</Label>
<Input id="name" placeholder="Juan Perez" />
</div>
<div className="space-y-2">
<Label htmlFor="email">Email Corporativo</Label>
<Input id="email" type="email" placeholder="juan@gomezlee.com" />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="role">Rol</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar rol" />
</SelectTrigger>
<SelectContent>
{Object.entries(roleLabels).map(([role, label]) => (
<SelectItem key={role} value={role}>{label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="department">Departamento</Label>
<Select>
<SelectTrigger>
<SelectValue placeholder="Seleccionar departamento" />
</SelectTrigger>
<SelectContent>
{mockDepartments.map(dept => (
<SelectItem key={dept.id} value={dept.id}>{dept.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="position">Cargo</Label>
<Input id="position" placeholder="Ej: Gerente de Operaciones" />
</div>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Enviar Invitacion por Email</Label>
<p className="text-sm text-muted-foreground">
El usuario recibira un email para configurar su contrasena
</p>
</div>
<Switch defaultChecked />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsNewUserOpen(false)}>
Cancelar
</Button>
<Button className="bg-accent hover:bg-accent/90" onClick={() => setIsNewUserOpen(false)}>
Crear Usuario
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
{/* Stats */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
<Users className="h-5 w-5 text-primary" />
</div>
<div>
<div className="text-2xl font-bold">{userStats.total}</div>
<div className="text-sm text-muted-foreground">Total Usuarios</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-accent/10 flex items-center justify-center">
<CheckCircle2 className="h-5 w-5 text-accent" />
</div>
<div>
<div className="text-2xl font-bold">{userStats.active}</div>
<div className="text-sm text-muted-foreground">Activos</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-destructive/10 flex items-center justify-center">
<XCircle className="h-5 w-5 text-destructive" />
</div>
<div>
<div className="text-2xl font-bold">{userStats.inactive}</div>
<div className="text-sm text-muted-foreground">Inactivos</div>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-purple-500/10 flex items-center justify-center">
<Shield className="h-5 w-5 text-purple-500" />
</div>
<div>
<div className="text-2xl font-bold">{userStats.byRole["admin_sistema"] || 0}</div>
<div className="text-sm text-muted-foreground">Administradores</div>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Filters */}
<Card>
<CardContent className="p-4">
<div className="flex flex-col gap-4 md:flex-row md:items-center">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Buscar usuarios por nombre o email..."
className="pl-10"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<Select value={filterRole} onValueChange={setFilterRole}>
<SelectTrigger className="w-full md:w-[180px]">
<SelectValue placeholder="Filtrar por rol" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos los roles</SelectItem>
{Object.entries(roleLabels).map(([role, label]) => (
<SelectItem key={role} value={role}>{label}</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filterDepartment} onValueChange={setFilterDepartment}>
<SelectTrigger className="w-full md:w-[180px]">
<SelectValue placeholder="Departamento" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
{mockDepartments.map(dept => (
<SelectItem key={dept.id} value={dept.id}>{dept.name}</SelectItem>
))}
</SelectContent>
</Select>
<Select value={filterStatus} onValueChange={setFilterStatus}>
<SelectTrigger className="w-full md:w-[140px]">
<SelectValue placeholder="Estado" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="active">Activos</SelectItem>
<SelectItem value="inactive">Inactivos</SelectItem>
</SelectContent>
</Select>
</div>
</CardContent>
</Card>
{/* Users Table */}
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b bg-muted/50">
<th className="text-left p-4 font-medium">Usuario</th>
<th className="text-left p-4 font-medium">Rol</th>
<th className="text-left p-4 font-medium">Departamento</th>
<th className="text-left p-4 font-medium">Estado</th>
<th className="text-left p-4 font-medium">Ultimo Acceso</th>
<th className="text-right p-4 font-medium">Acciones</th>
</tr>
</thead>
<tbody>
{filteredUsers.map(user => {
const dept = mockDepartments.find(d => d.id === user.departmentId)
return (
<tr key={user.id} className="border-b hover:bg-muted/30">
<td className="p-4">
<div className="flex items-center gap-3">
<Avatar className="h-10 w-10">
<AvatarImage src={user.avatar} />
<AvatarFallback className="bg-primary/10 text-primary">
{user.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<div>
<div className="font-medium">{user.name}</div>
<div className="text-sm text-muted-foreground">{user.email}</div>
</div>
</div>
</td>
<td className="p-4">
<Badge className={roleColors[user.role]}>
{roleLabels[user.role]}
</Badge>
</td>
<td className="p-4">
<span className="text-sm">{dept?.name || "-"}</span>
</td>
<td className="p-4">
<div className="flex items-center gap-2">
<div className={cn(
"w-2 h-2 rounded-full",
user.active ? "bg-accent" : "bg-destructive"
)} />
<span className="text-sm">
{user.active ? "Activo" : "Inactivo"}
</span>
</div>
</td>
<td className="p-4">
<span className="text-sm text-muted-foreground">
{user.lastLogin ? new Date(user.lastLogin).toLocaleDateString("es-MX") : "Nunca"}
</span>
</td>
<td className="p-4 text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => openEditDialog(user)}>
<Edit className="mr-2 h-4 w-4" />
Editar
</DropdownMenuItem>
<DropdownMenuItem>
<Key className="mr-2 h-4 w-4" />
Restablecer Contrasena
</DropdownMenuItem>
<DropdownMenuItem>
<Shield className="mr-2 h-4 w-4" />
Gestionar Permisos
</DropdownMenuItem>
<DropdownMenuItem onClick={() => handleToggleStatus(user.id)}>
{user.active ? (
<>
<XCircle className="mr-2 h-4 w-4" />
Desactivar
</>
) : (
<>
<CheckCircle2 className="mr-2 h-4 w-4" />
Activar
</>
)}
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
Eliminar
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</CardContent>
</Card>
{/* Edit User Dialog */}
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
<DialogContent className="max-w-lg">
{selectedUser && (
<>
<DialogHeader>
<DialogTitle>Editar Usuario</DialogTitle>
<DialogDescription>
Modifica la informacion del usuario
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="flex items-center gap-4">
<Avatar className="h-16 w-16">
<AvatarImage src={selectedUser.avatar} />
<AvatarFallback className="bg-primary/10 text-primary text-xl">
{selectedUser.name.split(" ").map(n => n[0]).join("")}
</AvatarFallback>
</Avatar>
<Button variant="outline" size="sm">Cambiar Foto</Button>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Nombre</Label>
<Input defaultValue={selectedUser.name} />
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input defaultValue={selectedUser.email} />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Rol</Label>
<Select defaultValue={selectedUser.role}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Object.entries(roleLabels).map(([role, label]) => (
<SelectItem key={role} value={role}>{label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Departamento</Label>
<Select defaultValue={selectedUser.departmentId}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{mockDepartments.map(dept => (
<SelectItem key={dept.id} value={dept.id}>{dept.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label>Cargo</Label>
<Input defaultValue={selectedUser.position || ""} />
</div>
<div className="flex items-center justify-between p-4 border rounded-lg">
<div>
<Label>Usuario Activo</Label>
<p className="text-sm text-muted-foreground">
Los usuarios inactivos no pueden acceder al sistema
</p>
</div>
<Switch defaultChecked={selectedUser.active} />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsEditOpen(false)}>
Cancelar
</Button>
<Button className="bg-accent hover:bg-accent/90" onClick={() => setIsEditOpen(false)}>
Guardar Cambios
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
</div>
)
}