Files
service_manager/frontend-client/src/routes/tickets/[id]/+page.svelte
2026-03-24 08:27:13 -06:00

611 lines
23 KiB
Svelte

<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import IssueDetailModal from '$lib/components/IssueDetailModal.svelte';
import IssueModal from '$lib/components/IssueModal.svelte';
import { auth } from '$lib/stores/auth.js';
import { tickets } from '$lib/stores/tickets.js';
import { toast } from '$lib/stores/toast.js';
import { onMount } from 'svelte';
let ticketId: string;
let newComment = '';
let isSubmittingComment = false;
let isClosingTicket = false;
let showCloseDialog = false;
let closeResolution = '';
let fileInput: HTMLInputElement;
let isUploading = false;
let showAttachments = true;
let showIssueModal = false;
let selectedIssue = null;
let pollingInterval: any = null;
async function loadComments() {
try {
await tickets.reloadComments(ticketId);
} catch (error) {
console.error('Error recargando comentarios:', error);
}
}
onMount(() => {
if (!$auth.isAuthenticated) {
goto('/login');
return;
}
ticketId = $page.params.id;
if (ticketId) {
tickets.loadTicket(ticketId);
pollingInterval = setInterval(() => {
loadComments();
}, 3000);
}
return () => {
if (pollingInterval) clearInterval(pollingInterval);
};
});
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleString('es-ES', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
const statusConfig: Record<string, { label: string; class: string }> = {
NEW: { label: 'Nuevo', class: 'badge-new' },
IN_PROGRESS: { label: 'En Progreso', class: 'badge-in-progress' },
WAITING_FOR_CLIENT: { label: 'Esperando Cliente', class: 'badge-waiting' },
WAITING_CUSTOMER: { label: 'Esperando Cliente', class: 'badge-waiting' },
RESOLVED: { label: 'Resuelto', class: 'badge-resolved' },
CLOSED: { label: 'Cerrado', class: 'badge-closed' },
REOPENED: { label: 'Reabierto', class: 'badge-reopened' }
};
const fallbackStatus = { label: 'Desconocido', class: 'badge-new' };
const priorityConfig: Record<string, { label: string; class: string }> = {
LOW: { label: 'Baja', class: 'badge-priority-low' },
MEDIUM: { label: 'Media', class: 'badge-priority-medium' },
HIGH: { label: 'Alta', class: 'badge-priority-high' },
URGENT: { label: 'Urgente', class: 'badge-priority-urgent' }
};
const fallbackPriority = { label: 'Normal', class: 'badge-priority-medium' };
async function handleAddComment() {
if (!newComment.trim()) return;
isSubmittingComment = true;
try {
await tickets.addComment(ticketId, newComment.trim());
newComment = '';
toast.success('Comentario agregado');
} catch (error: any) {
toast.error(error.message || 'Error al agregar comentario');
} finally {
isSubmittingComment = false;
}
}
async function handleFileUpload(event: Event) {
const target = event.target as HTMLInputElement;
const file = target.files?.[0];
if (!file) return;
if (file.size > 10 * 1024 * 1024) {
toast.error('El archivo es demasiado grande. Máximo 10MB');
target.value = '';
return;
}
const allowedTypes = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'application/pdf',
'text/plain',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (!allowedTypes.includes(file.type)) {
toast.error('Tipo de archivo no permitido');
target.value = '';
return;
}
isUploading = true;
try {
await tickets.uploadAttachment(ticketId, file);
toast.success('Archivo adjuntado correctamente');
target.value = '';
} catch (error: any) {
toast.error(error.message || 'Error al subir archivo');
} finally {
isUploading = false;
}
}
async function handleDownloadAttachment(attachment: any) {
try {
await tickets.downloadAttachment(ticketId, attachment.id, attachment.original_filename);
toast.success('Descarga iniciada');
} catch (error: any) {
toast.error(error.message || 'Error al descargar el archivo');
}
}
function handleCloseTicket() {
showCloseDialog = true;
}
async function confirmCloseTicket() {
isClosingTicket = true;
try {
await tickets.closeTicket(ticketId, closeResolution.trim() || undefined);
showCloseDialog = false;
closeResolution = '';
toast.success('Ticket cerrado exitosamente');
} catch (error: any) {
toast.error(error.message || 'Error al cerrar ticket');
} finally {
isClosingTicket = false;
}
}
function cancelCloseTicket() {
showCloseDialog = false;
closeResolution = '';
}
$: canClose =
$tickets.currentTicket &&
['RESOLVED', 'WAITING_CUSTOMER'].includes($tickets.currentTicket.status);
</script>
<svelte:head>
<title>
{$tickets.currentTicket ? `Ticket: ${$tickets.currentTicket.title}` : 'Cargando...'} - ServiceManager
</title>
</svelte:head>
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{#if $tickets.isLoading}
<div class="text-center py-12">
<div class="spinner w-8 h-8 mx-auto mb-4" />
<p class="text-gray-600">Cargando ticket...</p>
</div>
{:else if $tickets.error}
<div class="text-center py-12">
<h3 class="text-lg font-medium text-gray-900 mb-2">Error al cargar ticket</h3>
<p class="text-gray-600 mb-4">{$tickets.error}</p>
<button on:click={() => tickets.loadTicket(ticketId)} class="btn-primary px-4 py-2">
Reintentar
</button>
</div>
{:else if $tickets.currentTicket}
<!-- Breadcrumb -->
<div class="flex items-center space-x-2 text-sm text-gray-500 mb-6">
<a href="/tickets" class="hover:text-primary-600">Mis Tickets</a>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
<span>#{$tickets.currentTicket.id.substring(0, 8)}</span>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
<!-- Main Content -->
<div class="lg:col-span-2 space-y-6">
<!-- Ticket Header -->
<div class="card">
<div class="card-header">
<div class="flex justify-between items-start">
<div class="flex-1">
<h1 class="text-2xl font-bold text-gray-900 mb-2">
{$tickets.currentTicket.title}
</h1>
<div class="flex items-center space-x-3">
<span
class={(statusConfig[$tickets.currentTicket.status] ?? fallbackStatus).class}
>
{(statusConfig[$tickets.currentTicket.status] ?? fallbackStatus).label}
</span>
<span
class={(priorityConfig[$tickets.currentTicket.priority] ?? fallbackPriority)
.class}
>
{(priorityConfig[$tickets.currentTicket.priority] ?? fallbackPriority).label}
</span>
<span class="text-sm text-gray-500">
Creado {formatDate($tickets.currentTicket.created_at)}
</span>
</div>
</div>
{#if canClose}
<button
on:click={handleCloseTicket}
class="btn-success px-4 py-2"
disabled={isClosingTicket}
>
Cerrar Ticket
</button>
{/if}
</div>
</div>
<div class="card-content">
<p class="whitespace-pre-wrap text-gray-700">{$tickets.currentTicket.description}</p>
{#if $tickets.currentTicket.resolution}
<div class="mt-6 p-4 bg-green-50 border border-green-200 rounded-lg">
<h4 class="font-medium text-green-900 mb-2">Resolución:</h4>
<p class="text-green-800 whitespace-pre-wrap">
{$tickets.currentTicket.resolution}
</p>
</div>
{/if}
</div>
</div>
<!-- Attachments -->
{#if $tickets.attachments.length > 0}
<div class="card">
<div class="card-header">
<div class="flex items-center justify-between">
<h3 class="text-lg font-semibold text-gray-900 flex items-center space-x-2">
<span>Archivos Adjuntos</span>
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
>
{$tickets.attachments.length}
</span>
</h3>
<button
class="text-sm text-gray-500 hover:text-gray-700"
on:click={() => (showAttachments = !showAttachments)}
>
{showAttachments ? 'Ocultar' : 'Ver'} archivos
</button>
</div>
</div>
{#if showAttachments}
<div class="card-content space-y-3">
{#each $tickets.attachments as attachment}
<div
class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100"
>
<div>
<p class="text-sm font-medium text-gray-900">
{attachment.original_filename}
</p>
<p class="text-xs text-gray-500">
{Math.round(attachment.size_bytes / 1024)} KB • {attachment.uploaded_by_name}
</p>
</div>
<button
on:click={() => handleDownloadAttachment(attachment)}
class="btn-ghost p-2"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
</button>
</div>
{/each}
</div>
{/if}
</div>
{/if}
<!-- Comments -->
<div class="card">
<div class="card-header">
<h3 class="text-lg font-semibold text-gray-900">Conversación</h3>
</div>
<div class="card-content">
{#if $tickets.comments.length === 0}
<p class="text-gray-500 text-center py-4">No hay comentarios aún.</p>
{:else}
<div class="space-y-4">
{#each $tickets.comments as comment}
<div class="flex space-x-3">
<div
class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0"
>
<span class="text-primary-600 text-xs font-medium">
{comment.author_name
?.split(' ')
.map(n => n[0])
.join('') ?? '??'}
</span>
</div>
<div class="flex-1 min-w-0">
<div class="flex items-center space-x-2 mb-1">
<span class="text-sm font-medium text-gray-900">{comment.author_name}</span>
<span class="text-xs text-gray-500">{formatDate(comment.created_at)}</span>
{#if comment.is_internal}
<span class="bg-red-100 text-red-700 text-xs px-2 py-0.5 rounded"
>Interno</span
>
{/if}
</div>
<p class="text-gray-700 whitespace-pre-wrap">{comment.content}</p>
</div>
</div>
{/each}
</div>
{/if}
<div class="mt-6 pt-6 border-t border-gray-200 space-y-4">
<textarea
rows="4"
class="form-input"
placeholder="Escribe tu comentario..."
bind:value={newComment}
disabled={isSubmittingComment}
/>
<div class="flex justify-between items-center">
<div>
<input
type="file"
bind:this={fileInput}
on:change={handleFileUpload}
class="hidden"
accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.txt,.doc,.docx,.xls,.xlsx"
disabled={isUploading}
/>
<button
type="button"
on:click={() => fileInput.click()}
class="btn-ghost p-2 flex items-center space-x-2"
disabled={isUploading}
>
{#if isUploading}
<div class="spinner w-4 h-4" />
{:else}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
/>
</svg>
{/if}
<span class="text-sm">Adjuntar</span>
</button>
</div>
<button
on:click={handleAddComment}
class="btn-primary px-4 py-2"
disabled={isSubmittingComment || !newComment.trim()}
>
{#if isSubmittingComment}
<div class="flex items-center space-x-2">
<div class="spinner w-4 h-4" />
<span>Enviando...</span>
</div>
{:else}
Enviar
{/if}
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Sidebar -->
<div class="space-y-6">
<!-- Ticket Info -->
<div class="card">
<div class="card-header">
<h3 class="text-lg font-semibold text-gray-900">Información</h3>
</div>
<div class="card-content space-y-4">
<div>
<dt class="text-sm font-medium text-gray-500">ID del Ticket</dt>
<dd class="text-sm text-gray-900 font-mono">
#{$tickets.currentTicket.id.substring(0, 8)}
</dd>
</div>
<div>
<dt class="text-sm font-medium text-gray-500">Categoría</dt>
<dd class="text-sm text-gray-900">
{$tickets.currentTicket.category_name || 'Sin categoría'}
</dd>
</div>
{#if $tickets.currentTicket.assigned_to_name}
<div>
<dt class="text-sm font-medium text-gray-500">Asignado a</dt>
<dd class="text-sm text-gray-900">{$tickets.currentTicket.assigned_to_name}</dd>
</div>
{/if}
<div>
<dt class="text-sm font-medium text-gray-500">Creado</dt>
<dd class="text-sm text-gray-900">{formatDate($tickets.currentTicket.created_at)}</dd>
</div>
<div>
<dt class="text-sm font-medium text-gray-500">Última actualización</dt>
<dd class="text-sm text-gray-900">{formatDate($tickets.currentTicket.updated_at)}</dd>
</div>
{#if $tickets.currentTicket.sla_response_due || $tickets.currentTicket.sla_resolution_due}
<div class="pt-3 border-t border-gray-100">
<dt class="text-sm font-medium text-gray-500 mb-2">Tiempos de SLA</dt>
{#if $tickets.currentTicket.sla_response_due}
{@const respDue = new Date($tickets.currentTicket.sla_response_due)}
{@const respVencido =
respDue < new Date() && !$tickets.currentTicket.first_response_at}
<div class="mb-2">
<dt class="text-xs text-gray-400">Respuesta límite</dt>
<dd
class="text-sm {respVencido ? 'text-red-600 font-medium' : 'text-gray-900'}"
>
{formatDate($tickets.currentTicket.sla_response_due)}
{#if respVencido}
<span class="block text-xs text-red-500">¡Vencido!</span>
{:else if $tickets.currentTicket.first_response_at}
<span class="block text-xs text-green-600">✓ Respondido</span>
{/if}
</dd>
</div>
{/if}
{#if $tickets.currentTicket.sla_resolution_due}
{@const resDue = new Date($tickets.currentTicket.sla_resolution_due)}
{@const resVencido = resDue < new Date() && !$tickets.currentTicket.resolved_at}
<div>
<dt class="text-xs text-gray-400">Resolución límite</dt>
<dd class="text-sm {resVencido ? 'text-red-600 font-medium' : 'text-gray-900'}">
{formatDate($tickets.currentTicket.sla_resolution_due)}
{#if resVencido}
<span class="block text-xs text-red-500">¡Vencido!</span>
{:else if $tickets.currentTicket.resolved_at}
<span class="block text-xs text-green-600">✓ Resuelto</span>
{/if}
</dd>
</div>
{/if}
</div>
{/if}
</div>
</div>
<!-- Asuntos -->
<div class="card">
<div class="card-header flex justify-between items-center">
<h3 class="text-lg font-semibold text-gray-900">
Asuntos
{#if $tickets.issues.length > 0}
<span class="text-gray-400 font-normal text-sm ml-1"
>({$tickets.issues.length})</span
>
{/if}
</h3>
<button
type="button"
on:click={() => (showIssueModal = true)}
class="text-sm text-blue-600 hover:text-blue-700 font-medium"
>
+ Crear
</button>
</div>
{#if $tickets.issues.length > 0}
<div class="divide-y divide-gray-100">
{#each $tickets.issues as issue}
<button
type="button"
on:click={() => (selectedIssue = issue)}
class="w-full text-left card-content py-3 hover:bg-gray-50 transition-colors"
>
<div class="flex items-start justify-between gap-2">
<p class="text-sm text-gray-700 line-clamp-2">{issue.content}</p>
<span
class="text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 shrink-0"
>
{issue.priority}
</span>
</div>
{#if issue.tagged_users?.length > 0}
<div class="mt-1 flex flex-wrap gap-1">
{#each issue.tagged_users as u}
<span class="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full"
>{u.full_name}</span
>
{/each}
</div>
{/if}
<p class="text-xs text-gray-400 mt-1">{issue.created_by_name}</p>
</button>
{/each}
</div>
{:else}
<div class="card-content">
<p class="text-sm text-gray-500">No hay asuntos creados.</p>
</div>
{/if}
</div>
</div>
</div>
{/if}
</div>
<!-- Modals -->
{#if showIssueModal && $tickets.currentTicket}
<IssueModal
ticketId={$tickets.currentTicket.id}
on:close={() => (showIssueModal = false)}
on:created={() => {
showIssueModal = false;
tickets.loadTicket(ticketId);
}}
/>
{/if}
{#if selectedIssue && $tickets.currentTicket}
<IssueDetailModal
issue={selectedIssue}
ticketId={$tickets.currentTicket.id}
on:close={() => (selectedIssue = null)}
on:updated={e => {
selectedIssue = e.detail;
}}
on:deleted={() => {
selectedIssue = null;
tickets.loadTicket(ticketId);
}}
/>
{/if}
{#if showCloseDialog}
<div class="fixed inset-0 z-50 overflow-y-auto">
<div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20">
<div
class="fixed inset-0 bg-gray-500 opacity-75"
role="dialog"
tabindex="0"
on:click={cancelCloseTicket}
on:keydown={e => e.key === 'Escape' && cancelCloseTicket()}
/>
<div class="relative bg-white rounded-lg shadow-xl sm:max-w-lg w-full z-10 p-6">
<h3 class="text-lg font-medium text-gray-900 mb-2">Cerrar Ticket</h3>
<p class="text-sm text-gray-500 mb-4">¿Estás seguro de que quieres cerrar este ticket?</p>
<textarea
rows="3"
class="form-input w-full mb-4"
placeholder="Comentario de cierre (opcional)..."
bind:value={closeResolution}
disabled={isClosingTicket}
/>
<div class="flex justify-end gap-3">
<button
class="btn-secondary px-4 py-2"
disabled={isClosingTicket}
on:click={cancelCloseTicket}
>
Cancelar
</button>
<button
class="btn-success px-4 py-2 disabled:opacity-50"
disabled={isClosingTicket}
on:click={confirmCloseTicket}
>
{#if isClosingTicket}
<div class="flex items-center gap-2">
<div class="spinner w-4 h-4" />
<span>Cerrando...</span>
</div>
{:else}
Cerrar Ticket
{/if}
</button>
</div>
</div>
</div>
</div>
{/if}