All files / src/hooks useTickets.ts

98.66% Statements 74/75
78.94% Branches 30/38
100% Functions 30/30
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                                2x 14x       8x 8x 8x 8x 8x 8x   8x   7x                                                             2x 7x     6x 5x                                                               2x 10x 10x     5x           5x 4x     4x               2x 10x 10x   5x           5x 4x     4x 4x               2x 8x 8x   4x 3x     3x               2x 7x     3x 3x 2x                                 2x 10x 10x   5x           5x 4x     4x 4x               2x 6x     3x 2x                                       2x 5x     2x 1x                                         2x 8x     4x 3x                                   2x 10x 10x       4x 2x          
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as ticketsApi from '../api/tickets'; // Import all functions from the API service
import { Ticket, TicketComment, TicketTemplate, CannedResponse, TicketStatus, TicketPriority, TicketCategory, TicketType } from '../types';
 
// Define interfaces for filters and mutation payloads if necessary
interface TicketFilters {
  status?: TicketStatus;
  priority?: TicketPriority;
  category?: TicketCategory;
  ticketType?: TicketType;
  assignee?: string;
}
 
/**
 * Hook to fetch a list of tickets with optional filters
 */
export const useTickets = (filters?: TicketFilters) => {
  return useQuery<Ticket[]>({
    queryKey: ['tickets', filters],
    queryFn: async () => {
      // Use the API filters
      const apiFilters: ticketsApi.TicketFilters = {};
      if (filters?.status) apiFilters.status = filters.status;
      if (filters?.priority) apiFilters.priority = filters.priority;
      if (filters?.category) apiFilters.category = filters.category;
      if (filters?.ticketType) apiFilters.ticketType = filters.ticketType;
      if (filters?.assignee) apiFilters.assignee = filters.assignee;
 
      const data = await ticketsApi.getTickets(apiFilters);
      // Transform data to match frontend types if necessary (e.g., snake_case to camelCase)
      return data.map((ticket: any) => ({
        id: String(ticket.id),
        tenant: ticket.tenant ? String(ticket.tenant) : undefined,
        creator: String(ticket.creator),
        creatorEmail: ticket.creator_email,
        creatorFullName: ticket.creator_full_name,
        assignee: ticket.assignee ? String(ticket.assignee) : undefined,
        assigneeEmail: ticket.assignee_email,
        assigneeFullName: ticket.assignee_full_name,
        ticketType: ticket.ticket_type,
        status: ticket.status,
        priority: ticket.priority,
        subject: ticket.subject,
        description: ticket.description,
        category: ticket.category,
        relatedAppointmentId: ticket.related_appointment_id || undefined,
        dueAt: ticket.due_at,
        firstResponseAt: ticket.first_response_at,
        isOverdue: ticket.is_overdue,
        createdAt: ticket.created_at,
        updatedAt: ticket.updated_at,
        resolvedAt: ticket.resolved_at,
        comments: ticket.comments,
      }));
    },
  });
};
 
/**
 * Hook to fetch a single ticket by ID
 */
export const useTicket = (id: string | undefined) => {
  return useQuery<Ticket>({
    queryKey: ['tickets', id],
    queryFn: async () => {
      const ticket: any = await ticketsApi.getTicket(id as string);
      return {
        id: String(ticket.id),
        tenant: ticket.tenant ? String(ticket.tenant) : undefined,
        creator: String(ticket.creator),
        creatorEmail: ticket.creator_email,
        creatorFullName: ticket.creator_full_name,
        assignee: ticket.assignee ? String(ticket.assignee) : undefined,
        assigneeEmail: ticket.assignee_email,
        assigneeFullName: ticket.assignee_full_name,
        ticketType: ticket.ticket_type,
        status: ticket.status,
        priority: ticket.priority,
        subject: ticket.subject,
        description: ticket.description,
        category: ticket.category,
        relatedAppointmentId: ticket.related_appointment_id || undefined,
        dueAt: ticket.due_at,
        firstResponseAt: ticket.first_response_at,
        isOverdue: ticket.is_overdue,
        createdAt: ticket.created_at,
        updatedAt: ticket.updated_at,
        resolvedAt: ticket.resolved_at,
        comments: ticket.comments,
      };
    },
    enabled: !!id, // Only run query if ID is provided
  });
};
 
/**
 * Hook to create a new ticket
 */
export const useCreateTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (ticketData: Partial<Omit<Ticket, 'id' | 'comments' | 'creator' | 'creatorEmail' | 'creatorFullName' | 'createdAt' | 'updatedAt' | 'resolvedAt'>>) => {
      // Map frontend naming to backend naming
      const dataToSend = {
        ...ticketData,
        ticket_type: ticketData.ticketType,
        assignee: ticketData.assignee || null,
        // No need to send creator or tenant, backend serializer handles it
      };
      const response = await ticketsApi.createTicket(dataToSend);
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tickets'] }); // Invalidate tickets list to refetch
    },
  });
};
 
/**
 * Hook to update an existing ticket
 */
export const useUpdateTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ id, updates }: { id: string; updates: Partial<Ticket> }) => {
      const dataToSend = {
        ...updates,
        ticket_type: updates.ticketType,
        assignee: updates.assignee || null,
        // creator, tenant, comments are read-only on update
      };
      const response = await ticketsApi.updateTicket(id, dataToSend);
      return response;
    },
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['tickets'] });
      queryClient.invalidateQueries({ queryKey: ['tickets', variables.id] }); // Invalidate specific ticket
    },
  });
};
 
/**
 * Hook to delete a ticket
 */
export const useDeleteTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (id: string) => {
      await ticketsApi.deleteTicket(id);
      return id;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tickets'] });
    },
  });
};
 
/**
 * Hook to fetch comments for a specific ticket
 */
export const useTicketComments = (ticketId: string | undefined) => {
  return useQuery<TicketComment[]>({
    queryKey: ['ticketComments', ticketId],
    queryFn: async () => {
      Iif (!ticketId) return [];
      const comments = await ticketsApi.getTicketComments(ticketId);
      return comments.map((comment: any) => ({
        ...comment,
        id: String(comment.id),
        ticket: String(comment.ticket),
        author: String(comment.author),
        createdAt: new Date(comment.created_at).toISOString(),
        commentText: comment.comment_text, // Map backend 'comment_text'
        isInternal: comment.is_internal, // Map backend 'is_internal'
      }));
    },
    enabled: !!ticketId, // Only run query if ticketId is provided
  });
};
 
/**
 * Hook to add a new comment to a ticket
 */
export const useCreateTicketComment = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ ticketId, commentData }: { ticketId: string; commentData: Partial<TicketComment> }) => {
      const dataToSend = {
        ...commentData,
        comment_text: commentData.commentText,
        is_internal: commentData.isInternal,
        // ticket and author are handled by backend serializer
      };
      const response = await ticketsApi.createTicketComment(ticketId, dataToSend);
      return response;
    },
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['ticketComments', variables.ticketId] }); // Invalidate comments for this ticket
      queryClient.invalidateQueries({ queryKey: ['tickets', variables.ticketId] }); // Ticket might have a new comment count
    },
  });
};
 
/**
 * Hook to fetch ticket templates
 */
export const useTicketTemplates = () => {
  return useQuery<TicketTemplate[]>({
    queryKey: ['ticketTemplates'],
    queryFn: async () => {
      const data = await ticketsApi.getTicketTemplates();
      return data.map((template: any) => ({
        id: String(template.id),
        tenant: template.tenant ? String(template.tenant) : undefined,
        name: template.name,
        description: template.description,
        ticketType: template.ticket_type,
        category: template.category,
        defaultPriority: template.default_priority,
        subjectTemplate: template.subject_template,
        descriptionTemplate: template.description_template,
        isActive: template.is_active,
        createdAt: template.created_at,
      }));
    },
  });
};
 
/**
 * Hook to fetch a single ticket template by ID
 */
export const useTicketTemplate = (id: string | undefined) => {
  return useQuery<TicketTemplate>({
    queryKey: ['ticketTemplates', id],
    queryFn: async () => {
      const template: any = await ticketsApi.getTicketTemplate(id as string);
      return {
        id: String(template.id),
        tenant: template.tenant ? String(template.tenant) : undefined,
        name: template.name,
        description: template.description,
        ticketType: template.ticket_type,
        category: template.category,
        defaultPriority: template.default_priority,
        subjectTemplate: template.subject_template,
        descriptionTemplate: template.description_template,
        isActive: template.is_active,
        createdAt: template.created_at,
      };
    },
    enabled: !!id,
  });
};
 
/**
 * Hook to fetch canned responses
 */
export const useCannedResponses = () => {
  return useQuery<CannedResponse[]>({
    queryKey: ['cannedResponses'],
    queryFn: async () => {
      const data = await ticketsApi.getCannedResponses();
      return data.map((response: any) => ({
        id: String(response.id),
        tenant: response.tenant ? String(response.tenant) : undefined,
        title: response.title,
        content: response.content,
        category: response.category,
        isActive: response.is_active,
        useCount: response.use_count,
        createdBy: response.created_by ? String(response.created_by) : undefined,
        createdAt: response.created_at,
      }));
    },
  });
};
 
/**
 * Hook to manually refresh/check for new ticket emails
 */
export const useRefreshTicketEmails = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ticketsApi.refreshTicketEmails,
    onSuccess: (data) => {
      // Refresh tickets list if any emails were processed
      if (data.processed > 0) {
        queryClient.invalidateQueries({ queryKey: ['tickets'] });
      }
    },
  });
};