All files / src/components/features/admin/dev/DevTicketHierarchyTree index.tsx

0% Statements 0/456
100% Branches 0/0
0% Functions 0/1
0% Lines 0/456

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { clientLogger } from '@/lib/logging/clientLogger';
import {
  DEV_TICKET_CATEGORY_CONFIG,
  DEV_TICKET_STATUS_CONFIG,
  DEV_TICKET_PRIORITY_CONFIG } from '@/constants/dev-ticket';
import { Icon } from '@/components/ui/icons';
import type {
  DevTicketCategory,
  DevTicketStatus,
  DevTicketPriority } from '@/types/dev-ticket';

interface HierarchyTicket {
  id: string;
  ticketNumber: string;
  title: string;
  status: DevTicketStatus;
  category: DevTicketCategory;
  priority: DevTicketPriority;
  childCount: number;
  completedChildCount: number;
  assignee: {
    id: number;
    name: string | null;
    email: string;
    image: string | null;
  } | null;
  children?: HierarchyTicket[];
}

interface DevTicketHierarchyTreeProps {
  ticketId?: string;
  projectId?: string;
  onTicketSelect?: (ticketId: string) => void;
  selectedTicketId?: string;
  showEpicsOnly?: boolean;
  maxDepth?: number;
}

interface TreeNodeProps {
  ticket: HierarchyTicket;
  depth: number;
  expandedIds: Set<string>;
  onToggle: (id: string) => void;
  onSelect?: (id: string) => void;
  selectedId?: string;
  maxDepth: number;
}

function TreeNode({
  ticket,
  depth,
  expandedIds,
  onToggle,
  onSelect,
  selectedId,
  maxDepth}: TreeNodeProps) {
  const isExpanded = expandedIds.has(ticket.id);
  const hasChildren = ticket.childCount > 0;
  const isSelected = selectedId === ticket.id;

  const categoryConfig = DEV_TICKET_CATEGORY_CONFIG[ticket.category];
  const statusConfig = DEV_TICKET_STATUS_CONFIG[ticket.status];
  const priorityConfig = DEV_TICKET_PRIORITY_CONFIG[ticket.priority];

  const progress =
    ticket.childCount > 0
      ? Math.round((ticket.completedChildCount / ticket.childCount) * 100)
      : ticket.status === 'COMPLETED'
        ? 100
        : 0;

  const handleToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggle(ticket.id);
  };

  const handleSelect = () => {
    if (onSelect) {
      onSelect(ticket.id);
    }
  };

  return (
    <div className="select-none">
      <div
        className={`flex items-center gap-2 py-2 px-2 rounded-lg cursor-pointer transition-colors ${
          isSelected
            ? 'bg-indigo-50 border border-indigo-200'
            : 'hover:bg-gray-50 border border-transparent'
        }`}
        style={{ paddingLeft: `${depth * 20 + 8}px` }}
        onClick={handleSelect}
      >
        {/* Expand/Collapse Button */}
        <button
          onClick={handleToggle}
          className={`w-5 h-5 flex items-center justify-center text-gray-400 hover:text-gray-600 ${
            !hasChildren ? 'invisible' : ''
          }`}
        >
          {hasChildren && (
            <Icon
              name="chevron-right"
              size={16}
              className={`transition-transform ${isExpanded ? 'rotate-90' : ''}`}
            />
          )}
        </button>

        {/* Category Icon */}
        <span className={`${categoryConfig.color} text-sm`}>
          {categoryConfig.icon}
        </span>

        {/* Ticket Number */}
        <Link
          href={`/admin/dev/tickets/${ticket.id}`}
          className="text-sm font-medium text-gray-600 hover:text-indigo-600"
          onClick={(e) => e.stopPropagation()}
        >
          {ticket.ticketNumber}
        </Link>

        {/* Title */}
        <span className="flex-1 text-sm text-gray-900 truncate" title={ticket.title}>
          {ticket.title}
        </span>

        {/* Priority */}
        <span className={`text-xs ${priorityConfig.color}`} title={priorityConfig.label}>
          {priorityConfig.icon}
        </span>

        {/* Status Badge */}
        <span
          className={`px-2 py-0.5 text-xs rounded ${statusConfig.bgColor} ${statusConfig.color}`}
        >
          {statusConfig.label}
        </span>

        {/* Progress Bar */}
        {ticket.childCount > 0 && (
          <div className="flex items-center gap-1.5 min-w-[80px]">
            <div className="flex-1 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
              <div
                className={`h-full rounded-full transition-all ${
                  progress === 100
                    ? 'bg-green-500'
                    : progress > 50
                      ? 'bg-blue-500'
                      : progress > 0
                        ? 'bg-yellow-500'
                        : 'bg-gray-300 dark:bg-gray-600'
                }`}
                style={{ width: `${progress}%` }}
              />
            </div>
            <span className="text-xs text-gray-500 dark:text-gray-400 w-8">{progress}%</span>
          </div>
        )}

        {/* Assignee Avatar */}
        {ticket.assignee && (
          <div
            className="w-6 h-6 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center text-xs text-gray-600 dark:text-gray-300"
            title={ticket.assignee.name || ticket.assignee.email}
          >
            {(ticket.assignee.name || ticket.assignee.email).charAt(0).toUpperCase()}
          </div>
        )}
      </div>

      {/* Children */}
      {isExpanded && hasChildren && ticket.children && depth < maxDepth && (
        <div className="ml-2 border-l border-gray-200 dark:border-gray-700">
          {ticket.children.map((child) => (
            <TreeNode
              key={child.id}
              ticket={child}
              depth={depth + 1}
              expandedIds={expandedIds}
              onToggle={onToggle}
              onSelect={onSelect}
              selectedId={selectedId}
              maxDepth={maxDepth}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export default function DevTicketHierarchyTree({
  ticketId,
  projectId,
  onTicketSelect,
  selectedTicketId,
  showEpicsOnly = false,
  maxDepth = 5}: DevTicketHierarchyTreeProps) {
  const [tickets, setTickets] = useState<HierarchyTicket[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());

  const fetchHierarchy = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      let url: string;
      if (ticketId) {
        // Fetch hierarchy for a specific ticket
        url = `/api/dev/tickets/${ticketId}/hierarchy?tree=true`;
      } else if (showEpicsOnly) {
        // Fetch all epics
        url = `/api/dev/tickets/epics${projectId ? `?projectId=${projectId}&progress=true` : '?progress=true'}`;
      } else {
        // Fetch all root-level tickets
        url = `/api/dev/tickets?parentId=null&limit=100${projectId ? `&projectId=${projectId}` : ''}`;
      }

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Failed to fetch hierarchy');
      }

      const data = await response.json();

      if (ticketId && data.data?.tree) {
        // Single ticket hierarchy
        setTickets([data.data.tree]);
        // Auto-expand the root
        setExpandedIds(new Set([data.data.tree.id]));
      } else {
        // List of epics or root tickets
        setTickets(data.data || []);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load hierarchy');
      clientLogger.error('Error fetching hierarchy', err instanceof Error ? err : new Error(String(err)), {
        ticketId,
        projectId,
        showEpicsOnly
      });
    } finally {
      setLoading(false);
    }
  }, [ticketId, projectId, showEpicsOnly]);

  useEffect(() => {
    fetchHierarchy();
  }, [fetchHierarchy]);

  const handleToggle = useCallback(async (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });

    // Fetch children if not already loaded
    const ticket = findTicket(tickets, id);
    if (ticket && ticket.childCount > 0 && !ticket.children) {
      try {
        const response = await fetch(`/api/dev/tickets/${id}/hierarchy?tree=true&depth=1`);
        if (response.ok) {
          const data = await response.json();
          if (data.data?.tree?.children) {
            setTickets((prev) => updateTicketChildren(prev, id, data.data.tree.children));
          }
        }
      } catch (err) {
        clientLogger.error('Error fetching children', err instanceof Error ? err : new Error(String(err)), { id });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tickets]);

  const handleSelect = useCallback(
    (id: string) => {
      if (onTicketSelect) {
        onTicketSelect(id);
      }
    },
    [onTicketSelect]
  );

  // Helper to find a ticket in the tree
  const findTicket = (list: HierarchyTicket[], id: string): HierarchyTicket | null => {
    for (const ticket of list) {
      if (ticket.id === id) return ticket;
      if (ticket.children) {
        const found = findTicket(ticket.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  // Helper to update children for a ticket
  const updateTicketChildren = (
    list: HierarchyTicket[],
    parentId: string,
    children: HierarchyTicket[]
  ): HierarchyTicket[] => {
    return list.map((ticket) => {
      if (ticket.id === parentId) {
        return { ...ticket, children };
      }
      if (ticket.children) {
        return {
          ...ticket,
          children: updateTicketChildren(ticket.children, parentId, children)};
      }
      return ticket;
    });
  };

  // Expand all nodes
  const expandAll = useCallback(() => {
    const collectIds = (list: HierarchyTicket[]): string[] => {
      const ids: string[] = [];
      for (const ticket of list) {
        if (ticket.childCount > 0) {
          ids.push(ticket.id);
          if (ticket.children) {
            ids.push(...collectIds(ticket.children));
          }
        }
      }
      return ids;
    };
    setExpandedIds(new Set(collectIds(tickets)));
  }, [tickets]);

  // Collapse all nodes
  const collapseAll = useCallback(() => {
    setExpandedIds(new Set());
  }, []);

  if (loading) {
    return (
      <div className="p-4">
        <div className="animate-pulse space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="flex items-center gap-3">
              <div className="w-5 h-5 bg-gray-200 dark:bg-gray-700 rounded" />
              <div className="w-8 h-4 bg-gray-200 dark:bg-gray-700 rounded" />
              <div className="flex-1 h-4 bg-gray-200 dark:bg-gray-700 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
        <p className="text-red-700 dark:text-red-300 text-sm">{error}</p>
        <button
          onClick={fetchHierarchy}
          className="mt-2 text-sm text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 font-medium"
        >
          Try again
        </button>
      </div>
    );
  }

  if (tickets.length === 0) {
    return (
      <div className="p-6 text-center text-gray-500">
        <p className="mb-2">No tickets found</p>
        {showEpicsOnly && (
          <Link
            href="/admin/dev/tickets/new?category=EPIC"
            className="text-sm text-indigo-600 hover:text-indigo-800 font-medium"
          >
            Create your first Epic
          </Link>
        )}
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg border border-gray-200">
      {/* Header */}
      <div className="px-4 py-3 border-b border-gray-200 flex items-center justify-between">
        <h3 className="text-sm font-medium text-gray-900">
          {showEpicsOnly ? 'Epics' : 'Ticket Hierarchy'}
        </h3>
        <div className="flex items-center gap-2">
          <button
            onClick={expandAll}
            className="text-xs text-gray-500 hover:text-gray-700"
          >
            Expand All
          </button>
          <span className="text-gray-300">|</span>
          <button
            onClick={collapseAll}
            className="text-xs text-gray-500 hover:text-gray-700"
          >
            Collapse All
          </button>
          <button
            onClick={fetchHierarchy}
            className="ml-2 p-1 text-gray-400 hover:text-gray-600"
            title="Refresh"
          >
            <Icon name="arrow-right" size={16} />
          </button>
        </div>
      </div>

      {/* Tree */}
      <div className="p-2 max-h-[600px] overflow-y-auto">
        {tickets.map((ticket) => (
          <TreeNode
            key={ticket.id}
            ticket={ticket}
            depth={0}
            expandedIds={expandedIds}
            onToggle={handleToggle}
            onSelect={handleSelect}
            selectedId={selectedTicketId}
            maxDepth={maxDepth}
          />
        ))}
      </div>

      {/* Legend */}
      <div className="px-4 py-3 border-t border-gray-200 bg-gray-50">
        <div className="flex flex-wrap gap-3 text-xs text-gray-500">
          {Object.entries(DEV_TICKET_CATEGORY_CONFIG).map(([key, config]) => (
            <span key={key} className="flex items-center gap-1">
              <span className={config.color}>{config.icon}</span>
              <span>{config.label}</span>
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}