All files / src/pages Dashboard.tsx

83.47% Statements 96/115
94.66% Branches 71/75
63.88% Functions 23/36
85.58% Lines 95/111

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                                                      1x   1x 46x 46x 46x 46x 46x 46x   46x 46x 46x 38x 38x 2x 2x   1x     36x       46x 38x     46x     46x         62x 62x 62x 62x 62x   62x   62x 120x 120x     62x 120x 120x     62x 120x 120x     62x 120x 120x     62x 62x   62x             46x 38x 7x               61x   31x             61x               46x 38x 3x     35x 35x 35x   35x                   35x 68x   68x 68x 68x   68x 68x     35x 35x 245x 245x         46x               46x                                                             46x               46x         46x 431x         431x   40x                     40x                     39x                     39x                     39x                       39x                     39x               39x                 39x                 39x               39x                       46x 6x               24x                     40x 197x 197x             40x                   4x                     3x                                                               431x                   1x                    
import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import GridLayout, { Layout } from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import { Settings, Calendar, Users, Briefcase, ClipboardList, Edit2, Check } from 'lucide-react';
import { useServices } from '../hooks/useServices';
import { useResources } from '../hooks/useResources';
import { useAppointments } from '../hooks/useAppointments';
import { useCustomers } from '../hooks/useCustomers';
import { useTickets } from '../hooks/useTickets';
import { subDays, subMonths, isAfter, startOfWeek, endOfWeek, isWithinInterval } from 'date-fns';
import {
  MetricWidget,
  ChartWidget,
  OpenTicketsWidget,
  RecentActivityWidget,
  CapacityWidget,
  NoShowRateWidget,
  CustomerBreakdownWidget,
  WidgetConfigModal,
  WIDGET_DEFINITIONS,
  DEFAULT_LAYOUT,
  DashboardLayout,
  WidgetType,
} from '../components/dashboard';
 
const STORAGE_KEY = 'dashboard_layout';
 
const Dashboard: React.FC = () => {
  const { t } = useTranslation();
  const { data: services, isLoading: servicesLoading } = useServices();
  const { data: resources, isLoading: resourcesLoading } = useResources();
  const { data: appointments, isLoading: appointmentsLoading } = useAppointments();
  const { data: customers, isLoading: customersLoading } = useCustomers();
  const { data: tickets, isLoading: ticketsLoading } = useTickets();
 
  const [isEditing, setIsEditing] = useState(false);
  const [showConfig, setShowConfig] = useState(false);
  const [dashboardLayout, setDashboardLayout] = useState<DashboardLayout>(() => {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      try {
        return JSON.parse(saved);
      } catch {
        return DEFAULT_LAYOUT;
      }
    }
    return DEFAULT_LAYOUT;
  });
 
  // Save layout to localStorage when it changes
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(dashboardLayout));
  }, [dashboardLayout]);
 
  const isLoading = servicesLoading || resourcesLoading || appointmentsLoading || customersLoading || ticketsLoading;
 
  // Calculate growth percentages
  const calculateGrowth = useCallback((
    items: any[],
    dateField: string,
    filterFn?: (item: any) => boolean
  ) => {
    const now = new Date();
    const oneWeekAgo = subDays(now, 7);
    const twoWeeksAgo = subDays(now, 14);
    const oneMonthAgo = subMonths(now, 1);
    const twoMonthsAgo = subMonths(now, 2);
 
    const filteredItems = filterFn ? items.filter(filterFn) : items;
 
    const thisWeek = filteredItems.filter(item => {
      const date = new Date(item[dateField]);
      return isAfter(date, oneWeekAgo);
    }).length;
 
    const lastWeek = filteredItems.filter(item => {
      const date = new Date(item[dateField]);
      return isAfter(date, twoWeeksAgo) && !isAfter(date, oneWeekAgo);
    }).length;
 
    const thisMonth = filteredItems.filter(item => {
      const date = new Date(item[dateField]);
      return isAfter(date, oneMonthAgo);
    }).length;
 
    const lastMonth = filteredItems.filter(item => {
      const date = new Date(item[dateField]);
      return isAfter(date, twoMonthsAgo) && !isAfter(date, oneMonthAgo);
    }).length;
 
    const weeklyChange = lastWeek !== 0 ? ((thisWeek - lastWeek) / lastWeek) * 100 : (thisWeek > 0 ? 100 : 0);
    const monthlyChange = lastMonth !== 0 ? ((thisMonth - lastMonth) / lastMonth) * 100 : (thisMonth > 0 ? 100 : 0);
 
    return {
      weekly: { value: thisWeek, change: weeklyChange },
      monthly: { value: thisMonth, change: monthlyChange },
    };
  }, []);
 
  // Calculate metrics with real growth data
  const metrics = useMemo(() => {
    if (!appointments || !customers || !services || !resources) {
      return {
        appointments: { count: 0, growth: { weekly: { value: 0, change: 0 }, monthly: { value: 0, change: 0 } } },
        customers: { count: 0, growth: { weekly: { value: 0, change: 0 }, monthly: { value: 0, change: 0 } } },
        services: { count: 0 },
        resources: { count: 0 },
      };
    }
 
    const activeCustomers = customers.filter(c => c.status === 'Active');
 
    return {
      appointments: {
        count: appointments.length,
        growth: calculateGrowth(appointments, 'startTime'),
      },
      customers: {
        count: activeCustomers.length,
        growth: calculateGrowth(customers, 'lastVisit', c => c.status === 'Active' && c.lastVisit),
      },
      services: { count: services.length },
      resources: { count: resources.length },
    };
  }, [appointments, customers, services, resources, calculateGrowth]);
 
  // Calculate weekly chart data
  const weeklyData = useMemo(() => {
    if (!appointments) {
      return { revenue: [], appointments: [] };
    }
 
    const now = new Date();
    const weekStart = startOfWeek(now, { weekStartsOn: 1 });
    const weekEnd = endOfWeek(now, { weekStartsOn: 1 });
 
    const dayMap: Record<string, { revenue: number; count: number }> = {
      Mon: { revenue: 0, count: 0 },
      Tue: { revenue: 0, count: 0 },
      Wed: { revenue: 0, count: 0 },
      Thu: { revenue: 0, count: 0 },
      Fri: { revenue: 0, count: 0 },
      Sat: { revenue: 0, count: 0 },
      Sun: { revenue: 0, count: 0 },
    };
 
    appointments
      .filter(appt => isWithinInterval(new Date(appt.startTime), { start: weekStart, end: weekEnd }))
      .forEach(appt => {
        const date = new Date(appt.startTime);
        const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        const dayName = dayNames[date.getDay()];
 
        dayMap[dayName].count++;
        dayMap[dayName].revenue += (appt as any).price || 0;
      });
 
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return {
      revenue: days.map(day => ({ name: day, value: dayMap[day].revenue })),
      appointments: days.map(day => ({ name: day, value: dayMap[day].count })),
    };
  }, [appointments]);
 
  // Handle layout change
  const onLayoutChange = useCallback((newLayout: Layout[]) => {
    setDashboardLayout(prev => ({
      ...prev,
      layout: newLayout,
    }));
  }, []);
 
  // Toggle widget visibility
  const toggleWidget = useCallback((widgetId: string) => {
    setDashboardLayout(prev => {
      const isActive = prev.widgets.includes(widgetId);
      if (isActive) {
        return {
          widgets: prev.widgets.filter(id => id !== widgetId),
          layout: prev.layout.filter(l => l.i !== widgetId),
        };
      } else {
        const widgetDef = WIDGET_DEFINITIONS[widgetId as WidgetType];
        const maxY = Math.max(0, ...prev.layout.map(l => l.y + l.h));
        return {
          widgets: [...prev.widgets, widgetId],
          layout: [
            ...prev.layout,
            {
              i: widgetId,
              x: 0,
              y: maxY,
              w: widgetDef.defaultSize.w,
              h: widgetDef.defaultSize.h,
              minW: widgetDef.minSize?.w,
              minH: widgetDef.minSize?.h,
            },
          ],
        };
      }
    });
  }, []);
 
  // Remove widget
  const removeWidget = useCallback((widgetId: string) => {
    setDashboardLayout(prev => ({
      widgets: prev.widgets.filter(id => id !== widgetId),
      layout: prev.layout.filter(l => l.i !== widgetId),
    }));
  }, []);
 
  // Reset to default layout
  const resetLayout = useCallback(() => {
    setDashboardLayout(DEFAULT_LAYOUT);
  }, []);
 
  // Render individual widget
  const renderWidget = useCallback((widgetId: string) => {
    const widgetProps = {
      isEditing,
      onRemove: () => removeWidget(widgetId),
    };
 
    switch (widgetId) {
      case 'appointments-metric':
        return (
          <MetricWidget
            key={widgetId}
            title={t('dashboard.totalAppointments')}
            value={metrics.appointments.count}
            growth={metrics.appointments.growth}
            icon={<Calendar size={18} />}
            {...widgetProps}
          />
        );
      case 'customers-metric':
        return (
          <MetricWidget
            key={widgetId}
            title={t('customers.title')}
            value={metrics.customers.count}
            growth={metrics.customers.growth}
            icon={<Users size={18} />}
            {...widgetProps}
          />
        );
      case 'services-metric':
        return (
          <MetricWidget
            key={widgetId}
            title={t('services.title')}
            value={metrics.services.count}
            growth={{ weekly: { value: 0, change: 0 }, monthly: { value: 0, change: 0 } }}
            icon={<Briefcase size={18} />}
            {...widgetProps}
          />
        );
      case 'resources-metric':
        return (
          <MetricWidget
            key={widgetId}
            title={t('resources.title')}
            value={metrics.resources.count}
            growth={{ weekly: { value: 0, change: 0 }, monthly: { value: 0, change: 0 } }}
            icon={<ClipboardList size={18} />}
            {...widgetProps}
          />
        );
      case 'revenue-chart':
        return (
          <ChartWidget
            key={widgetId}
            title={t('dashboard.totalRevenue')}
            data={weeklyData.revenue}
            type="bar"
            color="#3b82f6"
            valuePrefix="$"
            {...widgetProps}
          />
        );
      case 'appointments-chart':
        return (
          <ChartWidget
            key={widgetId}
            title={t('dashboard.upcomingAppointments')}
            data={weeklyData.appointments}
            type="line"
            color="#10b981"
            {...widgetProps}
          />
        );
      case 'open-tickets':
        return (
          <OpenTicketsWidget
            key={widgetId}
            tickets={tickets || []}
            {...widgetProps}
          />
        );
      case 'recent-activity':
        return (
          <RecentActivityWidget
            key={widgetId}
            appointments={appointments || []}
            customers={customers || []}
            {...widgetProps}
          />
        );
      case 'capacity-utilization':
        return (
          <CapacityWidget
            key={widgetId}
            appointments={appointments || []}
            resources={resources || []}
            {...widgetProps}
          />
        );
      case 'no-show-rate':
        return (
          <NoShowRateWidget
            key={widgetId}
            appointments={appointments || []}
            {...widgetProps}
          />
        );
      case 'customer-breakdown':
        return (
          <CustomerBreakdownWidget
            key={widgetId}
            customers={customers || []}
            {...widgetProps}
          />
        );
      default:
        return null;
    }
  }, [t, metrics, weeklyData, tickets, appointments, customers, resources, isEditing, removeWidget]);
 
  if (isLoading) {
    return (
      <div className="p-8 space-y-8">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('dashboard.title')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('common.loading')}</p>
        </div>
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="p-6 bg-white dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-xl shadow-sm animate-pulse">
              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
              <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }
 
  // Get layout with min sizes
  const layoutWithConstraints = dashboardLayout.layout.map(l => {
    const widgetDef = WIDGET_DEFINITIONS[l.i as WidgetType];
    return {
      ...l,
      minW: widgetDef?.minSize?.w || 2,
      minH: widgetDef?.minSize?.h || 2,
    };
  });
 
  return (
    <div className="p-8 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('dashboard.title')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('dashboard.todayOverview')}</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setIsEditing(!isEditing)}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors ${
              isEditing
                ? 'bg-brand-600 text-white'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            {isEditing ? <Check size={16} /> : <Edit2 size={16} />}
            <span className="text-sm">{isEditing ? 'Done' : 'Edit Layout'}</span>
          </button>
          <button
            onClick={() => setShowConfig(true)}
            className="flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            <Settings size={16} />
            <span className="text-sm">Widgets</span>
          </button>
        </div>
      </div>
 
      {/* Edit mode hint */}
      {isEditing && (
        <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3 text-sm text-blue-700 dark:text-blue-300">
          Drag widgets to reposition them. Drag the corner to resize. Hover over a widget and click the X to remove it.
        </div>
      )}
 
      {/* Grid Layout */}
      <div className="max-w-[1200px] mx-auto">
        <GridLayout
          className="layout"
          layout={layoutWithConstraints}
          cols={12}
          rowHeight={60}
          width={1200}
          isDraggable={isEditing}
          isResizable={isEditing}
          onLayoutChange={onLayoutChange}
          draggableHandle=".drag-handle"
          compactType="vertical"
          preventCollision={false}
        >
          {dashboardLayout.widgets.map(widgetId => (
            <div key={widgetId} className="widget-container">
              {renderWidget(widgetId)}
            </div>
          ))}
        </GridLayout>
      </div>
 
      {/* Widget Config Modal */}
      <WidgetConfigModal
        isOpen={showConfig}
        onClose={() => setShowConfig(false)}
        activeWidgets={dashboardLayout.widgets}
        onToggleWidget={toggleWidget}
        onResetLayout={resetLayout}
      />
    </div>
  );
};
 
export default Dashboard;