All files / src/components/organizer/PartnerManagement PartnerDetailScreen.tsx

60.71% Statements 34/56
61.53% Branches 40/65
53.84% Functions 7/13
60.37% Lines 32/53

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                                                                                                    4x                                                                                                                                                                             4x 49x 49x   49x 49x 49x 49x 65x 65x     49x 49x                     49x   49x             49x         49x 47x                     49x 3x       49x 6x                             43x 2x                     41x 2x                     39x                     39x     39x                 39x 49x     49x                                                                                                                                                       259x                        
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
  Box,
  Container,
  Alert,
  AlertTitle,
  Skeleton,
  Stack,
  Paper,
  BottomNavigation,
  BottomNavigationAction,
  useTheme,
  useMediaQuery,
} from '@mui/material';
import {
  Dashboard as OverviewIcon,
  Contacts as ContactsIcon,
  Event as MeetingsIcon,
  BarChart as AnalyticsIcon,
  Note as NotesIcon,
  Lightbulb as TopicsIcon,
  Settings as SettingsIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { usePartnerDetail } from '@/hooks/usePartnerDetail';
import { usePartnerDetailStore } from '@/stores/partnerDetailStore';
import { useAuth } from '@/hooks/useAuth';
import { PartnerDetailHeader } from './PartnerDetailHeader';
import { PartnerTabNavigation } from './PartnerTabNavigation';
import { PartnerOverviewTab } from './PartnerOverviewTab';
import { PartnerMeetingsTab } from './PartnerMeetingsTab';
import PartnerNotesTab from './PartnerNotesTab';
import { PartnerTopicsTab } from './PartnerTopicsTab';
import { PartnerSettingsTab } from './PartnerSettingsTab';
import { PartnerAttendanceDashboard } from '@/components/partner/PartnerAttendanceDashboard';
import { PartnerCreateEditModal } from './PartnerCreateEditModal';
import { Breadcrumbs } from '@/components/shared/Breadcrumbs';
import type { BreadcrumbItem } from '@/components/shared/Breadcrumbs';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { useUserList } from '@/hooks/useUserManagement';
import { useNavigate, useLocation } from 'react-router-dom';
import UserCard from '@/components/organizer/UserManagement/UserCard';
import UserTable from '@/components/organizer/UserManagement/UserTable';
import UserPagination from '@/components/organizer/UserManagement/UserPagination';
import type { User } from '@/types/user.types';
 
// ─── Partner Contacts Panel ────────────────────────────────────────────────────
 
const PartnerContactsPanel: React.FC<{
  companyName: string;
  isMobile: boolean;
  isOrganizer: boolean;
}> = ({ companyName, isMobile, isOrganizer }) => {
  const { t: tPartners } = useTranslation('partners');
  const navigate = useNavigate();
  const location = useLocation();
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
 
  const { data, isLoading, isError } = useUserList({
    filters: { company: companyName, role: ['PARTNER'] },
    pagination: { page, limit },
  });
 
  if (isLoading) return <Skeleton variant="rectangular" height={300} />;
  if (isError)
    return <Alert severity="error">{tPartners('detail.errors.failedToLoadContacts')}</Alert>;
 
  const users = data?.data ?? [];
  const paginationData = data?.pagination;
 
  if (users.length === 0) {
    return (
      <Alert severity="info" sx={{ mt: 2 }}>
        {tPartners('detail.errors.noContactsAssigned')}
      </Alert>
    );
  }
 
  return (
    <Box sx={{ mt: 2 }}>
      {isMobile ? (
        <Stack spacing={2}>
          {users.map((user) => (
            <UserCard
              key={user.id}
              user={user}
              onClick={(u: User) =>
                navigate(`/organizer/users/${u.id}`, {
                  state: { from: location.pathname, fromLabel: companyName },
                })
              }
            />
          ))}
        </Stack>
      ) : (
        <UserTable
          users={users}
          onRowClick={(user: User) =>
            navigate(`/organizer/users/${user.id}`, {
              state: { from: location.pathname, fromLabel: companyName },
            })
          }
          onAction={(action, user: User) => {
            if (action === 'view')
              navigate(`/organizer/users/${user.id}`, {
                state: { from: location.pathname, fromLabel: companyName },
              });
          }}
          showAdminActions={isOrganizer}
        />
      )}
      {paginationData && (
        <UserPagination
          page={paginationData.page}
          totalPages={paginationData.totalPages}
          limit={paginationData.limit}
          onPageChange={setPage}
          onLimitChange={setLimit}
        />
      )}
    </Box>
  );
};
 
// ──────────────────────────────────────────────────────────────────────────────
 
interface PartnerDetailScreenProps {
  companyName?: string; // Story 8.0: provided by partner portal; organizer falls back to useParams()
}
 
/**
 * PartnerDetailScreen Component
 * Main screen integrating all partner detail components with tabbed interface
 */
export const PartnerDetailScreen: React.FC<PartnerDetailScreenProps> = (props) => {
  const { companyName: urlCompanyName } = useParams<{ companyName: string }>();
  const resolvedCompanyName = props.companyName ?? urlCompanyName ?? '';
 
  const { t } = useTranslation('organizer');
  const { t: tPartners } = useTranslation('partners');
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const activeTab = usePartnerDetailStore((state) => state.activeTab);
  const setActiveTab = usePartnerDetailStore((state) => state.setActiveTab);
 
  // Story 8.0: Get role from auth context (replaces hardcoded mock)
  const { user } = useAuth();
  const currentUser = {
    username: user?.username ?? '',
    role: (user?.role?.toUpperCase() ?? 'ORGANIZER') as
      | 'ORGANIZER'
      | 'PARTNER'
      | 'SPEAKER'
      | 'ATTENDEE',
  };
 
  // Story 8.0 H2: Clamp activeTab so stale ORGANIZER state cannot expose hidden tabs to PARTNER.
  // Story 8.4: Notes (4) and Settings (5) are not visible for PARTNER
  const PARTNER_MAX_TAB = 3; // Analytics (3) is the last visible tab for PARTNER
  const effectiveTab =
    currentUser.role === 'PARTNER' && activeTab > PARTNER_MAX_TAB ? 0 : activeTab;
 
  // Fetch partner detail with enriched data
  const {
    data: partner,
    isLoading,
    isError,
    error,
  } = usePartnerDetail(resolvedCompanyName, 'company,contacts,votes,meetings,activity');
 
  // Build breadcrumb items (memoized to prevent re-renders)
  // Story 8.0 M1: breadcrumb path is role-aware — partners cannot access /organizer/partners
  const breadcrumbItems: BreadcrumbItem[] = useMemo(
    () => [
      {
        label: t('common:navigation.partners'),
        path: currentUser.role === 'PARTNER' ? '/partners' : '/organizer/partners',
      },
      { label: partner?.companyName || resolvedCompanyName || t('common.loading', 'Loading...') },
    ],
    [partner?.companyName, resolvedCompanyName, t, currentUser.role]
  );
 
  // Handle tab change
  const handleTabChange = (newTab: number) => {
    setActiveTab(newTab);
  };
 
  // Loading state
  if (isLoading) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <BATbernLoader size={96} />
        </Box>
        <Stack spacing={2} sx={{ mt: 4 }}>
          <Skeleton variant="rectangular" height={200} />
          <Skeleton variant="rectangular" height={100} />
          <Skeleton variant="rectangular" height={400} />
        </Stack>
      </Container>
    );
  }
 
  // Error state - 404
  if (isError && (error as any)?.response?.status === 404) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Alert severity="error">
          <AlertTitle>{tPartners('detail.errors.notFound')}</AlertTitle>
          {tPartners('detail.errors.notFoundMessage', { name: resolvedCompanyName })}
        </Alert>
      </Container>
    );
  }
 
  // Error state - Other errors
  if (isError) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Alert severity="error">
          <AlertTitle>{tPartners('detail.errors.loading')}</AlertTitle>
          {tPartners('detail.errors.loadingMessage')}
        </Alert>
      </Container>
    );
  }
 
  // No partner data
  Iif (!partner) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Alert severity="warning">
          <AlertTitle>{tPartners('detail.errors.noData')}</AlertTitle>
          {tPartners('detail.errors.noDataMessage')}
        </Alert>
      </Container>
    );
  }
 
  const isPartner = currentUser.role === 'PARTNER';
 
  // Tabs visible per role — mirrors PartnerTabNavigation logic
  const allTabs = [
    { key: 'overview', label: tPartners('detail.tabs.overview'), icon: <OverviewIcon /> },
    { key: 'contacts', label: tPartners('detail.tabs.contacts'), icon: <ContactsIcon /> },
    { key: 'meetings', label: tPartners('detail.tabs.meetings'), icon: <MeetingsIcon /> },
    { key: 'analytics', label: tPartners('common:navigation.analytics'), icon: <AnalyticsIcon /> },
    { key: 'notes', label: tPartners('detail.tabs.notes'), icon: <NotesIcon /> },
    { key: 'topics', label: tPartners('detail.tabs.topics'), icon: <TopicsIcon /> },
    { key: 'settings', label: tPartners('detail.tabs.settings'), icon: <SettingsIcon /> },
  ];
  const visibleTabs = isPartner
    ? allTabs.filter((tab) => tab.key !== 'settings' && tab.key !== 'notes')
    : allTabs;
 
  return (
    <Box sx={{ pb: 8 }}>
      <Container maxWidth="xl" sx={{ py: 4 }} data-testid="partner-detail-container">
        {/* Breadcrumbs — hidden for PARTNER (they can only belong to one company) */}
        {currentUser.role !== 'PARTNER' && <Breadcrumbs items={breadcrumbItems} marginBottom={2} />}
 
        {/* Header */}
        <PartnerDetailHeader partner={partner} role={currentUser.role} isMobile={isMobile} />
 
        {/* Tab Navigation — desktop only (bottom nav always shown) */}
        {!isMobile && (
          <Box sx={{ mt: 3 }}>
            <PartnerTabNavigation
              activeTab={effectiveTab}
              onTabChange={handleTabChange}
              role={currentUser.role}
            />
          </Box>
        )}
 
        {/* Tab Panels */}
        <Box sx={{ mt: 3 }}>
          {/* Overview Tab */}
          {effectiveTab === 0 && <PartnerOverviewTab partner={partner} />}
 
          {/* Contacts Tab */}
          {effectiveTab === 1 && (
            <PartnerContactsPanel
              companyName={partner.companyName}
              isMobile={isMobile}
              isOrganizer={!isPartner}
            />
          )}
 
          {/* Meetings Tab */}
          {effectiveTab === 2 && (
            <PartnerMeetingsTab companyName={partner.companyName} role={currentUser.role} />
          )}
 
          {/* Analytics Tab */}
          {effectiveTab === 3 && <PartnerAttendanceDashboard companyName={partner.companyName} />}
 
          {/* Notes Tab — Story 8.4: hidden for PARTNER (organizer-internal notes) */}
          {effectiveTab === 4 && currentUser.role !== 'PARTNER' && (
            <PartnerNotesTab companyName={partner.companyName} role={currentUser.role} />
          )}
 
          {/* Topics Tab — organizer records partner topic suggestions during meetings */}
          {effectiveTab === 5 && currentUser.role !== 'PARTNER' && (
            <PartnerTopicsTab companyName={partner.companyName} />
          )}
 
          {/* Settings Tab — Story 8.0 H2: explicit role guard in addition to tab nav filtering */}
          {effectiveTab === 6 && currentUser.role !== 'PARTNER' && (
            <PartnerSettingsTab partner={partner} currentUser={currentUser} />
          )}
        </Box>
 
        {/* Edit Partner Modal */}
        <PartnerCreateEditModal />
      </Container>
 
      {/* Bottom Navigation — mobile only */}
      <Paper
        sx={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          right: 0,
          zIndex: 1100,
          display: { xs: 'block', md: 'none' },
        }}
        elevation={3}
      >
        <BottomNavigation value={effectiveTab} onChange={(_, v) => handleTabChange(v)}>
          {visibleTabs.map((tab, idx) => (
            <BottomNavigationAction
              key={tab.key}
              value={idx}
              icon={tab.icon}
              sx={{ minWidth: 0, flex: 1, px: 0 }}
            />
          ))}
        </BottomNavigation>
      </Paper>
    </Box>
  );
};