All files / src/layouts BusinessLayout.tsx

86.56% Statements 58/67
93.47% Branches 43/46
71.42% Functions 15/21
86.56% Lines 58/67

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                                                                  2x 56x   56x                 2x 60x 60x 60x 60x 60x 60x 60x 60x   60x     60x   60x 3x     60x 1x       60x 47x           47x 47x 47x         60x   46x         46x 1x         60x 60x   60x 46x 46x 4x 4x   1x         60x   2x 2x       60x 60x 47x   1x   47x     60x     60x                         60x                       60x 46x 46x       60x 56x     56x         60x           60x           60x                                                                                 1x                                                                 2x 48x              
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Outlet, useLocation, useSearchParams, useNavigate } from 'react-router-dom';
import Sidebar from '../components/Sidebar';
import TopBar from '../components/TopBar';
import TrialBanner from '../components/TrialBanner';
import SandboxBanner from '../components/SandboxBanner';
import QuotaWarningBanner from '../components/QuotaWarningBanner';
import QuotaOverageModal, { resetQuotaOverageModalDismissal } from '../components/QuotaOverageModal';
import { Business, User } from '../types';
import MasqueradeBanner from '../components/MasqueradeBanner';
import OnboardingWizard from '../components/OnboardingWizard';
import TicketModal from '../components/TicketModal';
import FloatingHelpButton from '../components/FloatingHelpButton';
import { useStopMasquerade } from '../hooks/useAuth';
import { useNotificationWebSocket } from '../hooks/useNotificationWebSocket';
import { useTicket } from '../hooks/useTickets';
import { MasqueradeStackEntry } from '../api/auth';
import { useScrollToTop } from '../hooks/useScrollToTop';
import { SandboxProvider, useSandbox } from '../contexts/SandboxContext';
import { applyColorPalette, applyBrandColors, defaultColorPalette } from '../utils/colorUtils';
 
interface BusinessLayoutProps {
  business: Business;
  user: User;
  darkMode: boolean;
  toggleTheme: () => void;
  onSignOut: () => void;
  updateBusiness: (updates: Partial<Business>) => void;
}
 
/**
 * Wrapper component for SandboxBanner that uses the sandbox context
 */
const SandboxBannerWrapper: React.FC = () => {
  const { isSandbox, toggleSandbox, isToggling } = useSandbox();
 
  return (
    <SandboxBanner
      isSandbox={isSandbox}
      onSwitchToLive={() => toggleSandbox(false)}
      isSwitching={isToggling}
    />
  );
};
 
const BusinessLayoutContent: React.FC<BusinessLayoutProps> = ({ business, user, darkMode, toggleTheme, onSignOut, updateBusiness }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [ticketModalId, setTicketModalId] = useState<string | null>(null);
  const mainContentRef = useRef<HTMLElement>(null);
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
 
  useScrollToTop(mainContentRef);
 
  // Fetch ticket data when modal is opened from notification
  const { data: ticketFromNotification } = useTicket(ticketModalId || undefined);
 
  const handleTicketClick = (ticketId: string) => {
    setTicketModalId(ticketId);
  };
 
  const closeTicketModal = () => {
    setTicketModalId(null);
  };
 
  // Set CSS custom properties for brand colors (primary palette + secondary color)
  useEffect(() => {
    applyBrandColors(
      business.primaryColor || '#2563eb',
      business.secondaryColor || business.primaryColor || '#2563eb'
    );
 
    // Cleanup: reset to defaults when component unmounts
    return () => {
      applyColorPalette(defaultColorPalette);
      document.documentElement.style.setProperty('--color-brand-secondary', '#0ea5e9');
    };
  }, [business.primaryColor, business.secondaryColor]);
 
  // Check for trial expiration and redirect
  useEffect(() => {
    // Don't check if already on trial-expired page
    Iif (location.pathname === '/trial-expired') {
      return;
    }
 
    // Redirect to trial-expired page if trial has expired
    if (business.isTrialExpired && business.status === 'Trial') {
      navigate('/trial-expired', { replace: true });
    }
  }, [business.isTrialExpired, business.status, location.pathname, navigate]);
 
  // Masquerade logic - now using the stack system
  const [masqueradeStack, setMasqueradeStack] = useState<MasqueradeStackEntry[]>([]);
  const stopMasqueradeMutation = useStopMasquerade();
 
  useEffect(() => {
    const stackJson = localStorage.getItem('masquerade_stack');
    if (stackJson) {
      try {
        setMasqueradeStack(JSON.parse(stackJson));
      } catch (e) {
        console.error('Failed to parse masquerade stack data', e);
      }
    }
  }, []);
 
  const handleStopMasquerade = () => {
    // Reset quota modal dismissal when returning from masquerade
    resetQuotaOverageModalDismissal();
    stopMasqueradeMutation.mutate();
  };
 
  // Reset quota modal when user changes (masquerade start)
  const prevUserIdRef = useRef<string | undefined>(undefined);
  useEffect(() => {
    if (prevUserIdRef.current !== undefined && prevUserIdRef.current !== user.id) {
      // User changed (masquerade started or changed) - reset modal
      resetQuotaOverageModalDismissal();
    }
    prevUserIdRef.current = user.id;
  }, [user.id]);
 
  useNotificationWebSocket(); // Activate the notification WebSocket listener
 
  // Get the previous user from the stack (the one we'll return to)
  const previousUser = masqueradeStack.length > 0
    ? {
        id: masqueradeStack[masqueradeStack.length - 1].user_id,
        username: masqueradeStack[masqueradeStack.length - 1].username,
        name: masqueradeStack[masqueradeStack.length - 1].username,
        role: masqueradeStack[masqueradeStack.length - 1].role,
        email: '',
        is_staff: false,
        is_superuser: false,
      } as User
    : null;
 
  // Get the original user (first in the stack)
  const originalUser = masqueradeStack.length > 0
    ? {
        id: masqueradeStack[0].user_id,
        username: masqueradeStack[0].username,
        name: masqueradeStack[0].username,
        role: masqueradeStack[0].role,
        email: '',
        is_staff: false,
        is_superuser: false,
      } as User
    : null;
 
  useEffect(() => {
    mainContentRef.current?.focus();
    setIsMobileMenuOpen(false);
  }, [location.pathname]);
 
  // Check if returning from Stripe Connect onboarding
  useEffect(() => {
    const isOnboardingReturn = searchParams.get('onboarding') === 'true';
 
    // Only show onboarding if returning from Stripe Connect
    Iif (isOnboardingReturn) {
      setShowOnboarding(true);
    }
  }, [searchParams]);
 
  const handleOnboardingComplete = () => {
    setShowOnboarding(false);
    // Update local state immediately so wizard doesn't re-appear
    updateBusiness({ initialSetupComplete: true });
  };
 
  const handleOnboardingSkip = () => {
    setShowOnboarding(false);
    // If they skip Stripe setup, disable payments
    updateBusiness({ paymentsEnabled: false });
  };
 
  return (
    <div className="flex h-full bg-gray-50 dark:bg-gray-900 transition-colors duration-200">
      {/* Floating Help Button */}
      <FloatingHelpButton />
 
      <div className={`fixed inset-y-0 left-0 z-40 transform ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'} transition-transform duration-300 ease-in-out md:hidden`}>
        <Sidebar business={business} user={user} isCollapsed={false} toggleCollapse={() => { }} />
      </div>
      {isMobileMenuOpen && <div className="fixed inset-0 z-30 bg-black/50 md:hidden" onClick={() => setIsMobileMenuOpen(false)}></div>}
 
      <div className="hidden md:flex md:flex-shrink-0">
        <Sidebar business={business} user={user} isCollapsed={isCollapsed} toggleCollapse={() => setIsCollapsed(!isCollapsed)} />
      </div>
 
      <div className="flex flex-col flex-1 min-w-0 overflow-hidden">
        {originalUser && (
          <MasqueradeBanner
            effectiveUser={user}
            originalUser={originalUser}
            previousUser={null}
            onStop={handleStopMasquerade}
          />
        )}
        {/* Quota overage warning banner - show for owners and managers */}
        {user.quota_overages && user.quota_overages.length > 0 && (
          <QuotaWarningBanner overages={user.quota_overages} />
        )}
        {/* Quota overage modal - shows once per session on login/masquerade */}
        {user.quota_overages && user.quota_overages.length > 0 && (
          <QuotaOverageModal overages={user.quota_overages} onDismiss={() => {}} />
        )}
        {/* Sandbox mode banner */}
        <SandboxBannerWrapper />
        {/* Show trial banner if trial is active and payments not yet enabled */}
        {business.isTrialActive && !business.paymentsEnabled && business.plan !== 'Free' && (
          <TrialBanner business={business} />
        )}
        <TopBar
          user={user}
          isDarkMode={darkMode}
          toggleTheme={toggleTheme}
          onMenuClick={() => setIsMobileMenuOpen(true)}
          onTicketClick={handleTicketClick}
        />
 
        <main ref={mainContentRef} tabIndex={-1} className="flex-1 overflow-auto focus:outline-none">
          {/* Pass all necessary context down to child routes */}
          <Outlet context={{ user, business, updateBusiness }} />
        </main>
      </div>
 
      {/* Onboarding wizard for paid-tier businesses */}
      {showOnboarding && (
        <OnboardingWizard
          business={business}
          onComplete={handleOnboardingComplete}
          onSkip={handleOnboardingSkip}
        />
      )}
 
      {/* Ticket modal opened from notification */}
      {ticketModalId && ticketFromNotification && (
        <TicketModal
          ticket={ticketFromNotification}
          onClose={closeTicketModal}
        />
      )}
    </div>
  );
};
 
/**
 * Business Layout with Sandbox Provider
 */
const BusinessLayout: React.FC<BusinessLayoutProps> = (props) => {
  return (
    <SandboxProvider>
      <BusinessLayoutContent {...props} />
    </SandboxProvider>
  );
};
 
export default BusinessLayout;