Ctrl+K
- 1.52 kB initial commit
- 206 Bytes <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>South African Employment Equity Tool</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html> import React, { useEffect } from 'react'; import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { AppProvider, useAppContext } from './contexts/AppContext'; import Header from './components/layout/Header'; import DashboardPage from './pages/DashboardPage'; import EmployeesPage from './pages/EmployeesPage'; import ReportsPage from './pages/ReportsPage'; import GoalsPage from './pages/GoalsPage'; import LoginPage from './pages/LoginPage'; import BarrierAnalysisPage from './pages/BarrierAnalysisPage'; // Protected route component const ProtectedRoute: React.FC<{children: React.ReactNode}> = ({ children }) => { const { currentUser } = useAppContext(); const location = useLocation(); if (!currentUser) { // Redirect to login if not authenticated return <Navigate to="/login\" state={{ from: location }} replace />; } import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAppContext } from '../contexts/AppContext'; import Button from '../components/common/Button'; import { LogIn, User, Lock } from 'lucide-react'; const LoginPage: React.FC = () => { const [email, setEmail] = useState('admin@exemplar.co.za'); const [password, setPassword] = useState('password'); const [error, setError] = useState(''); const [isLoading, setIsLoading] = useState(false); const { login } = useAppContext(); const navigate = useNavigate(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setError(''); setIsLoading(true); // Simulate API call setTimeout(() => { const success = login(email); if (success) { navigate('/'); } else { setError('Invalid email or password'); } setIsLoading(false); }, 1000); }; const handleDemoLogin = (role: string) => { setIsLoading(true); // Simulate API call setTimeout(() => { const success = login('demo@example.com', role); if (success) { navigate('/'); } else { setError('Demo login failed'); } setIsLoading(false); }, 1000); }; return ( <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8"> <div className="sm:mx-auto sm:w-full sm:max-w-md"> <div className="flex justify-center"> <div className="w-16 h-16 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-2xl"> EE </div> </div> <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> Employment Equity Tool </h2> <p className="mt-2 text-center text-sm text-gray-600"> Sign in to manage your organization's equity compliance </p> </div> <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md"> <div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10"> <form className="space-y-6" onSubmit={handleSubmit}> {error && ( <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative" role="alert"> <span className="block sm:inline">{error}</span> </div> )} <div> <label htmlFor="email" className="block text-sm font-medium text-gray-700"> Email address </label> <div className="mt-1 relative rounded-md shadow-sm"> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <User className="h-5 w-5 text-gray-400" /> </div> <input id="email" name="email" type="email" autoComplete="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="admin@exemplar.co.za" /> </div> </div> <div> <label htmlFor="password" className="block text-sm font-medium text-gray-700"> Password </label> <div className="mt-1 relative rounded-md shadow-sm"> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <Lock className="h-5 w-5 text-gray-400" /> </div> <input id="password" name="password" type="password" autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="••••••••" /> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <input id="remember_me" name="remember_me" type="checkbox" className="h-4 w-4 text-emerald-600 focus:ring-emerald-500 border-gray-300 rounded" /> <label htmlFor="remember_me" className="ml-2 block text-sm text-gray-900"> Remember me </label> </div> <div className="text-sm"> <a href="#" className="font-medium text-emerald-600 hover:text-emerald-500"> Forgot your password? </a> </div> </div> <div> <Button type="submit" fullWidth isLoading={isLoading} icon={<LogIn className="w-4 h-4" />} > Sign in </Button> </div> </form> <div className="mt-6"> <div className="relative"> <div className="absolute inset-0 flex items-center"> <div className="w-full border-t border-gray-300"></div> </div> <div className="relative flex justify-center text-sm"> <span className="px-2 bg-white text-gray-500">Or continue with demo access</span> </div> </div> <div className="mt-6 grid grid-cols-3 gap-3"> <Button variant="outline" onClick={() => handleDemoLogin('admin')} disabled={isLoading} > Admin </Button> <Button variant="outline" onClick={() => handleDemoLogin('manager')} disabled={isLoading} > Manager </Button> <Button variant="outline" onClick={() => handleDemoLogin('viewer')} disabled={isLoading} > Viewer </Button> </div> </div> </div> </div> </div> ); }; export default LoginPage; import React, { useState } from 'react'; import { PlusCircle, BarChart3 } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import GoalForm from '../components/goals/GoalForm'; import { EquityGoal } from '../types'; import { calculateGoalProgress } from '../utils/calculations'; import { format } from 'date-fns'; import { v4 as uuidv4 } from 'uuid'; const GoalsPage: React.FC = () => { const { equityGoals, addEquityGoal, updateEquityGoal, deleteEquityGoal } = useAppContext(); const [showAddForm, setShowAddForm] = useState(false); const [showEditForm, setShowEditForm] = useState(false); const [currentGoal, setCurrentGoal] = useState<EquityGoal | undefined>(undefined); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [goalToDelete, setGoalToDelete] = useState<string>(''); // Handle add goal const handleAddGoal = (goal: EquityGoal) => { addEquityGoal({ ...goal, id: uuidv4() }); setShowAddForm(false); }; // Handle edit goal const handleEditGoal = (goal: EquityGoal) => { setCurrentGoal(goal); setShowEditForm(true); }; // Handle update goal const handleUpdateGoal = (goal: EquityGoal) => { updateEquityGoal(goal); setShowEditForm(false); setCurrentGoal(undefined); }; // Handle delete goal const handleDeleteConfirm = (id: string) => { setGoalToDelete(id); setShowDeleteConfirm(true); }; const confirmDelete = () => { deleteEquityGoal(goalToDelete); setShowDeleteConfirm(false); setGoalToDelete(''); }; // Group goals by occupational level const groupedGoals: Record<string, EquityGoal[]> = {}; equityGoals.forEach(goal => { if (!groupedGoals[goal.occupationalLevel]) { groupedGoals[goal.occupationalLevel] = []; } groupedGoals[goal.occupationalLevel].push(goal); }); return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Equity Goals</h1> <p className="mt-1 text-sm text-gray-500"> Set and track your organization's employment equity goals </p> </div> <div className="mt-4 sm:mt-0"> <Button icon={<PlusCircle className="w-4 h-4" />} onClick={() => setShowAddForm(true)} > Add Goal </Button> </div> </div> {/* Add/Edit Goal Form */} {showAddForm && ( <GoalForm onSubmit={handleAddGoal} onCancel={() => setShowAddForm(false)} /> )} {showEditForm && currentGoal && ( <GoalForm goal={currentGoal} onSubmit={handleUpdateGoal} onCancel={() => { setShowEditForm(false); setCurrentGoal(undefined); }} /> )} {/* Delete Confirmation Modal */} {showDeleteConfirm && ( <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center"> <div className="relative mx-auto p-5 border w-96 shadow-lg rounded-md bg-white"> <div className="mt-3 text-center"> <h3 className="text-lg leading-6 font-medium text-gray-900">Confirm Deletion</h3> <div className="mt-2 px-7 py-3"> <p className="text-sm text-gray-500"> Are you sure you want to delete this equity goal? This action cannot be undone. </p> </div> <div className="flex justify-end mt-4 gap-3"> <Button variant="outline" onClick={() => setShowDeleteConfirm(false)} > Cancel </Button> <Button variant="danger" onClick={confirmDelete} > Delete </Button> </div> </div> </div> </div> )} {/* Goals Overview */} <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"> <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Goals Overview</h3> <div className="flex items-center"> <BarChart3 className="h-5 w-5 text-gray-400 mr-2" /> <span className="text-sm text-gray-500">{equityGoals.length} Active Goals</span> </div> </div> {/* Info card if no goals */} {equityGoals.length === 0 ? ( <div className="p-6"> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">No Equity Goals Set</h3> <div className="mt-2 text-sm text-blue-700"> <p> Set equity goals to track your organization's progress towards achieving a more diverse and representative workforce in accordance with the Employment Equity Act. Goals can be set for different occupational levels and demographic groups. </p> <p className="mt-2"> <Button size="sm" onClick={() => setShowAddForm(true)} > Set Your First Goal </Button> </p> </div> </div> </div> </div> </div> ) : ( <div className="divide-y divide-gray-200"> {Object.entries(groupedGoals).map(([level, goals]) => ( <div key={level} className="p-6"> <h4 className="text-md font-medium text-gray-900 mb-4">{level}</h4> <div className="space-y-6"> {goals.map(goal => { const progress = calculateGoalProgress(goal.targetPercentage, goal.currentPercentage); return ( <div key={goal.id} className="bg-gray-50 p-4 rounded-lg border border-gray-200"> <div className="flex justify-between items-start mb-4"> <div> <h5 className="font-medium text-gray-900"> {goal.targetGroup} </h5> <p className="text-sm text-gray-500 mt-1"> Target: {goal.targetPercentage}% by {format(new Date(goal.targetDate), 'MMM d, yyyy')} </p> </div> <div className="flex space-x-2"> <Button variant="text" size="sm" onClick={() => handleEditGoal(goal)} > Edit </Button> <Button variant="text" size="sm" onClick={() => handleDeleteConfirm(goal.id)} > Delete </Button> </div> </div> {/* Progress bar */} <div className="w-full bg-gray-200 rounded-full h-2.5"> <div className={`h-2.5 rounded-full ${getProgressColorClass(progress)}`} style={{ width: `${progress}%` }} ></div> </div> {/* Progress details */} <div className="flex justify-between items-center mt-2"> <div className="flex items-center"> <span className={`text-sm ${getProgressTextColorClass(progress)}`}> {progress}% Complete </span> <span className="mx-2 text-gray-300">•</span> <span className="text-sm text-gray-500"> Current: {goal.currentPercentage}% </span> </div> <div className="text-sm text-gray-500"> {getDaysDifference(new Date(), new Date(goal.targetDate))} days remaining </div> </div> {/* Notes */} {goal.notes && ( <div className="mt-3 text-sm text-gray-600 bg-white p-2 rounded border border-gray-100"> <p>{goal.notes}</p> </div> )} </div> ); })} </div> </div> ))} </div> )} </div> {/* Goal Setting Guide */} <Card title="Employment Equity Goal Setting Guide"> <div className="space-y-4"> <p className="text-sm text-gray-600"> The Employment Equity Act requires designated employers to implement affirmative action measures to achieve employment equity in the workplace. Setting clear goals is an essential part of this process. </p> <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4"> <div className="bg-emerald-50 p-4 rounded-lg border border-emerald-100"> <h4 className="font-medium text-emerald-800 mb-2">Best Practices</h4> <ul className="text-sm text-emerald-700 space-y-2"> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Set realistic and achievable targets based on labor market availability </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Focus on both recruitment and promotion strategies </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Consider both short-term and long-term goals </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Track progress regularly and adjust strategies as needed </li> </ul> </div> <div className="bg-amber-50 p-4 rounded-lg border border-amber-100"> <h4 className="font-medium text-amber-800 mb-2">Compliance Requirements</h4> <ul className="text-sm text-amber-700 space-y-2"> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Goals must be specific, measurable, achievable, relevant, and time-bound </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Numerical targets must be included in your Employment Equity Plan </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Progress must be reported annually to the Department of Employment and Labour </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Goals should address all designated groups under the Act </li> </ul> </div> </div> </div> </Card> </div> ); }; // Helper functions const getProgressColorClass = (progress: number): string => { if (progress < 25) return 'bg-red-600'; if (progress < 50) return 'bg-amber-500'; if (progress < 75) return 'bg-blue-500'; return 'bg-emerald-600'; }; const getProgressTextColorClass = (progress: number): string => { if (progress < 25) return 'text-red-600 font-medium'; if (progress < 50) return 'text-amber-500 font-medium'; if (progress < 75) return 'text-blue-600 font-medium'; return 'text-emerald-600 font-medium'; }; const getDaysDifference = (startDate: Date, endDate: Date): number => { const diffTime = endDate.getTime() - startDate.getTime(); return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); }; export default GoalsPage; import React from 'react'; import { useAppContext } from '../contexts/AppContext'; import ReportGenerator from '../components/reports/ReportGenerator'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import { FileText, Download, Calendar } from 'lucide-react'; import { format } from 'date-fns'; const ReportsPage: React.FC = () => { const { employees, companyInfo, demographicSummary } = useAppContext(); // Mock saved reports data const savedReports = [ { id: '1', name: 'EEA2 Report - Jan 2024', type: 'EEA2', date: '2024-01-15', size: '1.2 MB' }, { id: '2', name: 'EEA4 Report - Jan 2024', type: 'EEA4', date: '2024-01-15', size: '956 KB' }, { id: '3', name: 'Quarterly Progress Report - Q4 2023', type: 'Internal', date: '2023-12-31', size: '2.1 MB' } ]; return ( <div className="space-y-6"> {/* Page header */} <div> <h1 className="text-2xl font-bold text-gray-900">Reports</h1> <p className="mt-1 text-sm text-gray-500"> Generate and manage employment equity reports </p> </div> {/* Report Generator */} <ReportGenerator employees={employees} companyInfo={companyInfo} demographicSummary={demographicSummary} /> {/* Saved Reports */} <Card title="Saved Reports"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Report Name </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Type </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Date Generated </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> File Size </th> <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Actions </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {savedReports.map((report) => ( <tr key={report.id} className="hover:bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center"> <FileText className="flex-shrink-0 h-5 w-5 text-gray-400" /> <div className="ml-3"> <div className="text-sm font-medium text-gray-900"> {report.name} </div> </div> </div> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${ report.type === 'EEA2' ? 'bg-blue-100 text-blue-800' : report.type === 'EEA4' ? 'bg-emerald-100 text-emerald-800' : 'bg-gray-100 text-gray-800' }`}> {report.type} </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {format(new Date(report.date), 'dd MMM yyyy')} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {report.size} </td> <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> <Button variant="text" size="sm" icon={<Download className="w-4 h-4" />} > Download </Button> </td> </tr> ))} </tbody> </table> </div> </Card> {/* Reporting Calendar */} <Card title="Reporting Calendar"> <div className="space-y-4"> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="flex-shrink-0"> <Calendar className="h-5 w-5 text-blue-600" /> </div> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">Important Compliance Dates</h3> <div className="mt-2 text-sm text-blue-700"> <p> South African employers designated under the Employment Equity Act must submit their reports annually by the first working day of October, or by 15 January for online submissions. </p> </div> </div> </div> </div> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Report Type </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Due Date </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Submission Method </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Status </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA2 Report</div> <div className="text-xs text-gray-500">Workforce Profile</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2025 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800"> Upcoming </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA4 Report</div> <div className="text-xs text-gray-500">Income Differentials</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2025 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800"> Upcoming </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA2 Report</div> <div className="text-xs text-gray-500">Workforce Profile</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2024 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Submitted </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA4 Report</div> <div className="text-xs text-gray-500">Income Differentials</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2024 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Submitted </span> </td> </tr> </tbody> </table> </div> </div> </Card> </div> ); }; export default ReportsPage; import React, { useState } from 'react'; import { PlusCircle, Upload, Download } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import EmployeeTable from '../components/employees/EmployeeTable'; import EmployeeForm from '../components/employees/EmployeeForm'; import Button from '../components/common/Button'; import Card from '../components/common/Card'; import { Employee } from '../types'; import { v4 as uuidv4 } from 'uuid'; const EmployeesPage: React.FC = () => { const { employees, addEmployee, updateEmployee, deleteEmployee } = useAppContext(); const [showAddForm, setShowAddForm] = useState(false); const [showEditForm, setShowEditForm] = useState(false); const [showViewDetails, setShowViewDetails] = useState(false); const [currentEmployee, setCurrentEmployee] = useState<Employee | undefined>(undefined); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [employeeToDelete, setEmployeeToDelete] = useState<string>(''); // Handle add employee const handleAddEmployee = (employee: Employee) => { addEmployee({ ...employee, id: uuidv4() }); setShowAddForm(false); }; // Handle edit employee const handleEditEmployee = (employee: Employee) => { setCurrentEmployee(employee); setShowEditForm(true); setShowViewDetails(false); }; // Handle update employee const handleUpdateEmployee = (employee: Employee) => { updateEmployee(employee); setShowEditForm(false); setCurrentEmployee(undefined); }; // Handle view employee const handleViewEmployee = (employee: Employee) => { setCurrentEmployee(employee); setShowViewDetails(true); setShowEditForm(false); }; // Handle delete employee const handleDeleteConfirm = (id: string) => { setEmployeeToDelete(id); setShowDeleteConfirm(true); }; const confirmDelete = () => { deleteEmployee(employeeToDelete); setShowDeleteConfirm(false); setEmployeeToDelete(''); }; return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Employees</h1> <p className="mt-1 text-sm text-gray-500"> Manage your organization's employee database </p> </div> <div className="mt-4 sm:mt-0 flex flex-wrap gap-2"> <Button variant="outline" size="sm" icon={<Upload className="w-4 h-4" />} > Import </Button> <Button variant="outline" size="sm" icon={<Download className="w-4 h-4" />} > Export </Button> <Button icon={<PlusCircle className="w-4 h-4" />} onClick={() => setShowAddForm(true)} > Add Employee </Button> </div> </div> {/* Add/Edit Employee Form */} {showAddForm && ( <EmployeeForm onSubmit={handleAddEmployee} onCancel={() => setShowAddForm(false)} /> )} {showEditForm && currentEmployee && ( <EmployeeForm employee={currentEmployee} onSubmit={handleUpdateEmployee} onCancel={() => { setShowEditForm(false); setCurrentEmployee(undefined); }} /> )} {/* Employee Details View */} {showViewDetails && currentEmployee && ( <Card title="Employee Details" footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={() => { setShowViewDetails(false); setCurrentEmployee(undefined); }} > Close </Button> <Button onClick={() => { setShowViewDetails(false); handleEditEmployee(currentEmployee); }} > Edit Employee </Button> </div> } > <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <h3 className="text-lg font-medium text-gray-900 mb-4">Personal Information</h3> <div className="space-y-3"> <div> <h4 className="text-sm font-medium text-gray-500">Full Name</h4> <p className="mt-1">{currentEmployee.firstName} {currentEmployee.lastName}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">ID Number</h4> <p className="mt-1">{currentEmployee.idNumber}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Race</h4> <p className="mt-1">{currentEmployee.race}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Gender</h4> <p className="mt-1">{currentEmployee.gender}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Disability Status</h4> <p className="mt-1"> {currentEmployee.hasDisability ? 'Yes' : 'No'} {currentEmployee.hasDisability && currentEmployee.disabilityDetails && ` - ${currentEmployee.disabilityDetails}`} </p> </div> </div> </div> <div> <h3 className="text-lg font-medium text-gray-900 mb-4">Employment Information</h3> <div className="space-y-3"> <div> <h4 className="text-sm font-medium text-gray-500">Occupational Level</h4> <p className="mt-1">{currentEmployee.occupationalLevel}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Department</h4> <p className="mt-1">{currentEmployee.department}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Annual Salary</h4> <p className="mt-1">R {currentEmployee.salary.toLocaleString()}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Join Date</h4> <p className="mt-1">{new Date(currentEmployee.joinDate).toLocaleDateString()}</p> </div> {currentEmployee.terminationDate && ( <div> <h4 className="text-sm font-medium text-gray-500">Termination Date</h4> <p className="mt-1">{new Date(currentEmployee.terminationDate).toLocaleDateString()}</p> </div> )} </div> </div> </div> </Card> )} {/* Delete Confirmation Modal */} {showDeleteConfirm && ( <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center"> <div className="relative mx-auto p-5 border w-96 shadow-lg rounded-md bg-white"> <div className="mt-3 text-center"> <h3 className="text-lg leading-6 font-medium text-gray-900">Confirm Deletion</h3> <div className="mt-2 px-7 py-3"> <p className="text-sm text-gray-500"> Are you sure you want to delete this employee? This action cannot be undone. </p> </div> <div className="flex justify-end mt-4 gap-3"> <Button variant="outline" onClick={() => setShowDeleteConfirm(false)} > Cancel </Button> <Button variant="danger" onClick={confirmDelete} > Delete </Button> </div> </div> </div> </div> )} {/* Employee Table */} <EmployeeTable employees={employees} onEdit={handleEditEmployee} onDelete={handleDeleteConfirm} onView={handleViewEmployee} /> </div> ); }; export default EmployeesPage; import React, { useState } from 'react'; import { Users, BarChart2, FileText, Target, CalendarClock } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import StatCard from '../components/dashboard/StatCard'; import DemographicChart from '../components/dashboard/DemographicChart'; import GoalTracker from '../components/dashboard/GoalTracker'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import { format } from 'date-fns'; const DashboardPage: React.FC = () => { const { employees, equityGoals, demographicSummary, companyInfo } = useAppContext(); const [selectedDepartment, setSelectedDepartment] = useState<string>('All Departments'); // Get unique departments const departments = ['All Departments', ...Array.from(new Set(employees.map(emp => emp.department)))]; // Filter employees by department const filteredEmployees = selectedDepartment === 'All Departments' ? employees : employees.filter(emp => emp.department === selectedDepartment); // Calculate quick stats const totalEmployees = filteredEmployees.length; const disabledCount = filteredEmployees.filter(emp => emp.hasDisability).length; const disabledPercentage = totalEmployees > 0 ? Math.round((disabledCount / totalEmployees) * 100) : 0; const blackEmployees = filteredEmployees.filter(emp => emp.race === 'Black').length; const blackPercentage = totalEmployees > 0 ? Math.round((blackEmployees / totalEmployees) * 100) : 0; const femaleEmployees = filteredEmployees.filter(emp => emp.gender === 'Female').length; const femalePercentage = totalEmployees > 0 ? Math.round((femaleEmployees / totalEmployees) * 100) : 0; return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1> <p className="mt-1 text-sm text-gray-500"> Overview of your organization's employment equity status </p> </div> <div className="mt-4 sm:mt-0"> <select value={selectedDepartment} onChange={(e) => setSelectedDepartment(e.target.value)} className="block w-full rounded-md border border-gray-300 py-2 pl-3 pr-10 text-base focus:border-emerald-500 focus:outline-none focus:ring-emerald-500 sm:text-sm" > {departments.map(dept => ( <option key={dept} value={dept}>{dept}</option> ))} </select> </div> </div> {/* Stats cards */} <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6"> <StatCard title="Total Employees" value={totalEmployees} icon={<Users className="w-5 h-5" />} color="emerald" /> <StatCard title="Black Representation" value={`${blackPercentage}%`} change={{ value: 2.5, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="blue" /> <StatCard title="Female Representation" value={`${femalePercentage}%`} change={{ value: 1.2, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="violet" /> <StatCard title="People with Disabilities" value={`${disabledPercentage}%`} change={{ value: 0.5, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="amber" /> </div> {/* Charts grid */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <DemographicChart employees={filteredEmployees} chartType="race" title="Race Distribution" /> <DemographicChart employees={filteredEmployees} chartType="gender" title="Gender Distribution" /> </div> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <DemographicChart employees={filteredEmployees} chartType="occupational" title="Occupational Levels" /> <GoalTracker goals={equityGoals} /> </div> {/* Upcoming deadlines */} <Card title="Upcoming Compliance Deadlines"> <div className="space-y-4"> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center"> <FileText className="h-5 w-5 text-amber-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">EEA2 Report Submission</h3> <p className="text-sm text-gray-500">Department of Employment and Labour</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800"> 15 Jan 2025 </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(2025, 0, 15).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center"> <Target className="h-5 w-5 text-blue-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">Equity Plan Review</h3> <p className="text-sm text-gray-500">Internal Milestone</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"> 30 Sep 2024 </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(2024, 8, 30).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center"> <CalendarClock className="h-5 w-5 text-emerald-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">Quarterly Progress Review</h3> <p className="text-sm text-gray-500">Management Meeting</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800"> {format(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15), 'dd MMM yyyy')} </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> </div> <div className="mt-6 flex justify-end"> <Button variant="outline" size="sm" icon={<CalendarClock className="w-4 h-4" />}> View Full Calendar </Button> </div> </Card> {/* Company info */} <Card title="Company Information"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <h3 className="text-sm font-medium text-gray-500 mb-2">Company Details</h3> <p className="text-sm"><span className="font-medium">Name:</span> {companyInfo.name}</p> <p className="text-sm"><span className="font-medium">Registration Number:</span> {companyInfo.registrationNumber}</p> <p className="text-sm"><span className="font-medium">Industry:</span> {companyInfo.industry}</p> <p className="text-sm"><span className="font-medium">Address:</span> {companyInfo.address}</p> </div> <div> <h3 className="text-sm font-medium text-gray-500 mb-2">Contact Information</h3> <p className="text-sm"><span className="font-medium">Contact Person:</span> {companyInfo.contactPerson}</p> <p className="text-sm"><span className="font-medium">Email:</span> {companyInfo.contactEmail}</p> <p className="text-sm"><span className="font-medium">Phone:</span> {companyInfo.contactPhone}</p> </div> </div> <div className="mt-6 flex justify-end"> <Button variant="outline" size="sm"> Edit Company Information </Button> </div> </Card> </div> ); }; export default DashboardPage; import React, { useState, useEffect } from 'react'; import { EquityGoal, OccupationalLevel } from '../../types'; import { v4 as uuidv4 } from 'uuid'; import Card from '../common/Card'; import Button from '../common/Button'; import { Calendar, BarChart3, X } from 'lucide-react'; interface GoalFormProps { goal?: EquityGoal; onSubmit: (goal: EquityGoal) => void; onCancel: () => void; } const GoalForm: React.FC<GoalFormProps> = ({ goal, onSubmit, onCancel }) => { const [formData, setFormData] = useState<EquityGoal>({ id: '', occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 0, targetPercentage: 0, targetDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0], notes: '' }); const [errors, setErrors] = useState<Partial<Record<keyof EquityGoal, string>>>({}); const [isSubmitting, setIsSubmitting] = useState(false); // Initialize form with goal data if editing useEffect(() => { if (goal) { setFormData({ ...goal, targetDate: goal.targetDate.split('T')[0] }); } else { // Generate a new ID for new goals setFormData(prev => ({ ...prev, id: uuidv4() })); } }, [goal]); const handleChange = ( e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement> ) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when field is changed if (errors[name as keyof EquityGoal]) { setErrors(prev => ({ ...prev, [name]: '' })); } }; const validateForm = (): boolean => { const newErrors: Partial<Record<keyof EquityGoal, string>> = {}; // Validate percentages if (formData.currentPercentage < 0 || formData.currentPercentage > 100) { newErrors.currentPercentage = 'Current percentage must be between 0 and 100'; } if (formData.targetPercentage <= 0 || formData.targetPercentage > 100) { newErrors.targetPercentage = 'Target percentage must be between 1 and 100'; } // Validate target date (must be in the future) const today = new Date(); today.setHours(0, 0, 0, 0); const targetDate = new Date(formData.targetDate); if (targetDate <= today) { newErrors.targetDate = 'Target date must be in the future'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (validateForm()) { setIsSubmitting(true); // Convert string values to numbers const submittedGoal: EquityGoal = { ...formData, currentPercentage: Number(formData.currentPercentage), targetPercentage: Number(formData.targetPercentage) }; // Submit the form data onSubmit(submittedGoal); setIsSubmitting(false); } }; const occupationalLevels: OccupationalLevel[] = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const targetGroups = [ 'Black', 'Coloured', 'Indian', 'White', 'Female', 'Male', 'People with Disabilities' ]; return ( <Card title={goal ? 'Edit Equity Goal' : 'Add New Equity Goal'} footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={onCancel} disabled={isSubmitting} > Cancel </Button> <Button type="submit" form="goal-form" isLoading={isSubmitting} icon={<BarChart3 className="w-4 h-4" />} > {goal ? 'Update Goal' : 'Add Goal'} </Button> </div> } > <form id="goal-form" onSubmit={handleSubmit} className="space-y-6"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Goal Details</h3> <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={onCancel} > Close </Button> </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="occupationalLevel" className="block text-sm font-medium text-gray-700"> Occupational Level * </label> <select name="occupationalLevel" id="occupationalLevel" value={formData.occupationalLevel} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {occupationalLevels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label htmlFor="targetGroup" className="block text-sm font-medium text-gray-700"> Target Group * </label> <select name="targetGroup" id="targetGroup" value={formData.targetGroup} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {targetGroups.map(group => ( <option key={group} value={group}>{group}</option> ))} </select> </div> <div> <label htmlFor="currentPercentage" className="block text-sm font-medium text-gray-700"> Current Percentage * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="number" name="currentPercentage" id="currentPercentage" min="0" max="100" step="0.1" value={formData.currentPercentage} onChange={handleChange} className={`block w-full rounded-md ${ errors.currentPercentage ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-12`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <span className="text-gray-500 sm:text-sm">%</span> </div> </div> {errors.currentPercentage && ( <p className="mt-1 text-sm text-red-600">{errors.currentPercentage}</p> )} </div> <div> <label htmlFor="targetPercentage" className="block text-sm font-medium text-gray-700"> Target Percentage * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="number" name="targetPercentage" id="targetPercentage" min="1" max="100" step="0.1" value={formData.targetPercentage} onChange={handleChange} className={`block w-full rounded-md ${ errors.targetPercentage ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-12`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <span className="text-gray-500 sm:text-sm">%</span> </div> </div> {errors.targetPercentage && ( <p className="mt-1 text-sm text-red-600">{errors.targetPercentage}</p> )} </div> <div> <label htmlFor="targetDate" className="block text-sm font-medium text-gray-700"> Target Date * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="date" name="targetDate" id="targetDate" value={formData.targetDate} onChange={handleChange} className={`block w-full rounded-md ${ errors.targetDate ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-10`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <Calendar className="h-4 w-4 text-gray-400" /> </div> </div> {errors.targetDate && ( <p className="mt-1 text-sm text-red-600">{errors.targetDate}</p> )} </div> <div className="md:col-span-2"> <label htmlFor="notes" className="block text-sm font-medium text-gray-700"> Notes </label> <textarea name="notes" id="notes" rows={3} placeholder="Add any additional information or strategies to achieve this goal..." value={formData.notes || ''} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> </form> </Card> ); }; export default GoalForm; import React, { useState } from 'react'; import { format } from 'date-fns'; import Card from '../common/Card'; import Button from '../common/Button'; import { Download, FileText, Table, Clipboard } from 'lucide-react'; import { Employee, CompanyInfo, DemographicSummary } from '../../types'; interface ReportGeneratorProps { employees: Employee[]; companyInfo: CompanyInfo; demographicSummary: DemographicSummary[]; } const ReportGenerator: React.FC<ReportGeneratorProps> = ({ employees, companyInfo, demographicSummary }) => { const [reportType, setReportType] = useState<'EEA2' | 'EEA4'>('EEA2'); const [reportPeriod, setReportPeriod] = useState<string>(format(new Date(), 'yyyy-MM')); const [isGenerating, setIsGenerating] = useState(false); const [reportGenerated, setReportGenerated] = useState(false); const handleGenerateReport = () => { setIsGenerating(true); // Simulate report generation with a timeout setTimeout(() => { setIsGenerating(false); setReportGenerated(true); }, 1500); }; return ( <div className="space-y-6"> <Card title="Generate Employment Equity Report"> <div className="space-y-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Report Type </label> <div className="flex space-x-4"> <label className="inline-flex items-center"> <input type="radio" name="reportType" value="EEA2" checked={reportType === 'EEA2'} onChange={() => setReportType('EEA2')} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">EEA2 (Workforce Profile)</span> </label> <label className="inline-flex items-center"> <input type="radio" name="reportType" value="EEA4" checked={reportType === 'EEA4'} onChange={() => setReportType('EEA4')} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">EEA4 (Income Differentials)</span> </label> </div> </div> <div> <label htmlFor="reportPeriod" className="block text-sm font-medium text-gray-700 mb-1"> Reporting Period </label> <input type="month" id="reportPeriod" value={reportPeriod} onChange={(e) => setReportPeriod(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="flex-shrink-0"> <FileText className="h-5 w-5 text-blue-600" /> </div> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">Report Information</h3> <div className="mt-2 text-sm text-blue-700"> <p> {reportType === 'EEA2' ? ( <> The EEA2 report is a workforce profile analysis required by the Department of Employment and Labour. It breaks down your workforce by occupational level, race, gender, and disability status. </> ) : ( <> The EEA4 report analyzes income differentials within your organization by race, gender, and occupational level. It helps identify pay disparities that may require attention. </> )} </p> </div> </div> </div> </div> <div className="flex justify-end"> <Button onClick={handleGenerateReport} isLoading={isGenerating} icon={<Table className="w-4 h-4" />} > Generate Report </Button> </div> </div> </Card> {reportGenerated && ( <Card title={`${reportType} Report - ${format(new Date(reportPeriod), 'MMMM yyyy')}`}> <div className="space-y-6"> <div className="border border-gray-200 rounded-md overflow-hidden"> <div className="bg-gray-50 px-4 py-3 border-b border-gray-200"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900"> {companyInfo.name} - Employment Equity Report </h3> <p className="text-sm text-gray-500"> Generated on {format(new Date(), 'dd MMM yyyy')} </p> </div> </div> <div className="p-4"> <div className="mb-6"> <h4 className="text-md font-medium text-gray-900 mb-2">Company Information</h4> <div className="grid grid-cols-2 gap-4 text-sm"> <div> <p><span className="font-medium">Name:</span> {companyInfo.name}</p> <p><span className="font-medium">Registration Number:</span> {companyInfo.registrationNumber}</p> <p><span className="font-medium">Industry:</span> {companyInfo.industry}</p> </div> <div> <p><span className="font-medium">Contact Person:</span> {companyInfo.contactPerson}</p> <p><span className="font-medium">Contact Email:</span> {companyInfo.contactEmail}</p> <p><span className="font-medium">Total Employees:</span> {companyInfo.employeeCount}</p> </div> </div> </div> {reportType === 'EEA2' ? ( <div> <h4 className="text-md font-medium text-gray-900 mb-2">Workforce Profile Summary</h4> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Occupational Level </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Black) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Coloured) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Indian) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (White) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Black) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Coloured) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Indian) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (White) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Disabled </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Total </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {demographicSummary.map((summary) => ( <tr key={summary.occupationalLevel}> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {summary.occupationalLevel} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleBlack} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleColoured} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleIndian} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleWhite} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleBlack} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleColoured} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleIndian} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleWhite} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.disabledCount} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {summary.total} </td> </tr> ))} {/* Totals row */} <tr className="bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Total </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleBlack, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleColoured, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleIndian, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleWhite, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleBlack, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleColoured, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleIndian, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleWhite, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.disabledCount, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.total, 0)} </td> </tr> </tbody> </table> </div> </div> ) : ( <div> <h4 className="text-md font-medium text-gray-900 mb-2">Income Differentials Summary</h4> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Occupational Level </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Gender Gap (%) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Black Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> White Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Race Gap (%) </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {/* Income differential data would be calculated and displayed here */} <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Top Management </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,150,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,020,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 11.3% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 980,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,230,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 20.3% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Senior Management </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 825,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 780,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 5.8% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 760,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 845,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 10.1% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Professionally Qualified </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 625,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 590,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 5.6% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 585,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 645,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 9.3% </td> </tr> </tbody> </table> </div> </div> )} </div> </div> <div className="flex justify-end space-x-3"> <Button variant="outline" size="md" icon={<Clipboard className="w-4 h-4" />} > Copy to Clipboard </Button> <Button size="md" icon={<Download className="w-4 h-4" />} > Download {reportType} Report </Button> </div> </div> </Card> )} </div> ); }; export default ReportGenerator; import React, { useState, useEffect } from 'react'; import { Employee, Race, Gender, OccupationalLevel } from '../../types'; import { v4 as uuidv4 } from 'uuid'; import Card from '../common/Card'; import Button from '../common/Button'; import { X } from 'lucide-react'; interface EmployeeFormProps { employee?: Employee; onSubmit: (employee: Employee) => void; onCancel: () => void; } const EmployeeForm: React.FC<EmployeeFormProps> = ({ employee, onSubmit, onCancel }) => { const [formData, setFormData] = useState<Employee>({ id: '', firstName: '', lastName: '', idNumber: '', race: 'Black', gender: 'Male', hasDisability: false, disabilityDetails: '', occupationalLevel: 'Skilled Technical', department: '', salary: 0, joinDate: new Date().toISOString().split('T')[0] }); const [errors, setErrors] = useState<Partial<Record<keyof Employee, string>>>({}); const [isSubmitting, setIsSubmitting] = useState(false); // Initialize form with employee data if editing useEffect(() => { if (employee) { setFormData({ ...employee, joinDate: employee.joinDate.split('T')[0] }); } else { // Generate a new ID for new employees setFormData(prev => ({ ...prev, id: uuidv4() })); } }, [employee]); const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => { const { name, value, type } = e.target; if (type === 'checkbox') { const checked = (e.target as HTMLInputElement).checked; setFormData(prev => ({ ...prev, [name]: checked })); } else { setFormData(prev => ({ ...prev, [name]: value })); } // Clear error when field is changed if (errors[name as keyof Employee]) { setErrors(prev => ({ ...prev, [name]: '' })); } }; const validateForm = (): boolean => { const newErrors: Partial<Record<keyof Employee, string>> = {}; // Required fields validation if (!formData.firstName) newErrors.firstName = 'First name is required'; if (!formData.lastName) newErrors.lastName = 'Last name is required'; if (!formData.idNumber) newErrors.idNumber = 'ID number is required'; if (!formData.department) newErrors.department = 'Department is required'; if (!formData.joinDate) newErrors.joinDate = 'Join date is required'; // ID number validation (basic South African ID number format) if (formData.idNumber && !/^\d{13}$/.test(formData.idNumber)) { newErrors.idNumber = 'ID number must be 13 digits'; } // Salary validation if (formData.salary < 0) { newErrors.salary = 'Salary cannot be negative'; } // Disability details required if hasDisability is true if (formData.hasDisability && !formData.disabilityDetails) { newErrors.disabilityDetails = 'Disability details are required'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (validateForm()) { setIsSubmitting(true); // Submit the form data onSubmit(formData); setIsSubmitting(false); } }; const occupationalLevels: OccupationalLevel[] = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const races: Race[] = [ 'Black', 'Coloured', 'Indian', 'White', 'Foreign National' ]; const genders: Gender[] = [ 'Male', 'Female', 'Non-binary' ]; return ( <Card title={employee ? 'Edit Employee' : 'Add New Employee'} footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={onCancel} disabled={isSubmitting} > Cancel </Button> <Button type="submit" form="employee-form" isLoading={isSubmitting} > {employee ? 'Update Employee' : 'Add Employee'} </Button> </div> } > <form id="employee-form" onSubmit={handleSubmit} className="space-y-6"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Personal Information</h3> <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={onCancel} > Close </Button> </div> {/* Personal Information */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="firstName" className="block text-sm font-medium text-gray-700"> First Name * </label> <input type="text" name="firstName" id="firstName" value={formData.firstName} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.firstName ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.firstName && ( <p className="mt-1 text-sm text-red-600">{errors.firstName}</p> )} </div> <div> <label htmlFor="lastName" className="block text-sm font-medium text-gray-700"> Last Name * </label> <input type="text" name="lastName" id="lastName" value={formData.lastName} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.lastName ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.lastName && ( <p className="mt-1 text-sm text-red-600">{errors.lastName}</p> )} </div> <div> <label htmlFor="idNumber" className="block text-sm font-medium text-gray-700"> ID Number * </label> <input type="text" name="idNumber" id="idNumber" value={formData.idNumber} onChange={handleChange} placeholder="13 digit South African ID" className={`mt-1 block w-full rounded-md border ${ errors.idNumber ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.idNumber && ( <p className="mt-1 text-sm text-red-600">{errors.idNumber}</p> )} </div> <div> <label htmlFor="race" className="block text-sm font-medium text-gray-700"> Race * </label> <select name="race" id="race" value={formData.race} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {races.map(race => ( <option key={race} value={race}>{race}</option> ))} </select> </div> <div> <label htmlFor="gender" className="block text-sm font-medium text-gray-700"> Gender * </label> <select name="gender" id="gender" value={formData.gender} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {genders.map(gender => ( <option key={gender} value={gender}>{gender}</option> ))} </select> </div> <div> <div className="flex items-center mt-5"> <input type="checkbox" name="hasDisability" id="hasDisability" checked={formData.hasDisability} onChange={handleChange} className="h-4 w-4 text-emerald-600 focus:ring-emerald-500 border-gray-300 rounded" /> <label htmlFor="hasDisability" className="ml-2 block text-sm font-medium text-gray-700"> Person with Disability </label> </div> </div> {formData.hasDisability && ( <div> <label htmlFor="disabilityDetails" className="block text-sm font-medium text-gray-700"> Disability Details * </label> <input type="text" name="disabilityDetails" id="disabilityDetails" value={formData.disabilityDetails || ''} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.disabilityDetails ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.disabilityDetails && ( <p className="mt-1 text-sm text-red-600">{errors.disabilityDetails}</p> )} </div> )} </div> {/* Employment Information */} <div className="pt-6 border-t border-gray-200"> <h3 className="text-lg font-medium text-gray-900 mb-4">Employment Information</h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="occupationalLevel" className="block text-sm font-medium text-gray-700"> Occupational Level * </label> <select name="occupationalLevel" id="occupationalLevel" value={formData.occupationalLevel} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {occupationalLevels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" name="department" id="department" value={formData.department} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.department ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.department && ( <p className="mt-1 text-sm text-red-600">{errors.department}</p> )} </div> <div> <label htmlFor="salary" className="block text-sm font-medium text-gray-700"> Annual Salary (ZAR) </label> <input type="number" name="salary" id="salary" value={formData.salary} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.salary ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.salary && ( <p className="mt-1 text-sm text-red-600">{errors.salary}</p> )} </div> <div> <label htmlFor="joinDate" className="block text-sm font-medium text-gray-700"> Join Date * </label> <input type="date" name="joinDate" id="joinDate" value={formData.joinDate} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.joinDate ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.joinDate && ( <p className="mt-1 text-sm text-red-600">{errors.joinDate}</p> )} </div> <div> <label htmlFor="terminationDate" className="block text-sm font-medium text-gray-700"> Termination Date (if applicable) </label> <input type="date" name="terminationDate" id="terminationDate" value={formData.terminationDate || ''} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> </div> </form> </Card> ); }; export default EmployeeForm; import React, { useState } from 'react'; import { Employee, Race, Gender, OccupationalLevel } from '../../types'; import { Edit, Trash2, ChevronDown, ChevronUp, Info, Search, Filter, X } from 'lucide-react'; import Button from '../common/Button'; import Card from '../common/Card'; interface EmployeeTableProps { employees: Employee[]; onEdit: (employee: Employee) => void; onDelete: (id: string) => void; onView: (employee: Employee) => void; } const EmployeeTable: React.FC<EmployeeTableProps> = ({ employees, onEdit, onDelete, onView }) => { const [sortField, setSortField] = useState<keyof Employee>('lastName'); const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc'); const [searchTerm, setSearchTerm] = useState(''); const [filters, setFilters] = useState<{ race: Race | 'All'; gender: Gender | 'All'; occupationalLevel: OccupationalLevel | 'All'; hasDisability: 'All' | 'Yes' | 'No'; }>({ race: 'All', gender: 'All', occupationalLevel: 'All', hasDisability: 'All' }); const [showFilters, setShowFilters] = useState(false); // Handle sort const handleSort = (field: keyof Employee) => { if (sortField === field) { setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc'); } else { setSortField(field); setSortDirection('asc'); } }; // Handle search const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => { setSearchTerm(e.target.value); }; // Filter and sort employees const filteredEmployees = employees .filter(employee => { // Search filter const searchMatch = searchTerm === '' || `${employee.firstName} ${employee.lastName}`.toLowerCase().includes(searchTerm.toLowerCase()) || employee.idNumber.includes(searchTerm); // Dropdown filters const raceMatch = filters.race === 'All' || employee.race === filters.race; const genderMatch = filters.gender === 'All' || employee.gender === filters.gender; const levelMatch = filters.occupationalLevel === 'All' || employee.occupationalLevel === filters.occupationalLevel; const disabilityMatch = filters.hasDisability === 'All' || (filters.hasDisability === 'Yes' && employee.hasDisability) || (filters.hasDisability === 'No' && !employee.hasDisability); return searchMatch && raceMatch && genderMatch && levelMatch && disabilityMatch; }) .sort((a, b) => { if (a[sortField] < b[sortField]) { return sortDirection === 'asc' ? -1 : 1; } if (a[sortField] > b[sortField]) { return sortDirection === 'asc' ? 1 : -1; } return 0; }); // Reset filters const resetFilters = () => { setFilters({ race: 'All', gender: 'All', occupationalLevel: 'All', hasDisability: 'All' }); setSearchTerm(''); }; // Get unique values for filter dropdowns const races = ['All', ...Array.from(new Set(employees.map(e => e.race)))]; const genders = ['All', ...Array.from(new Set(employees.map(e => e.gender)))]; const levels = ['All', ...Array.from(new Set(employees.map(e => e.occupationalLevel)))]; return ( <Card noPadding className="overflow-hidden"> {/* Search and filters */} <div className="p-4 border-b border-gray-200 bg-gray-50"> <div className="flex flex-col sm:flex-row justify-between space-y-2 sm:space-y-0"> <div className="relative w-full sm:w-64"> <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none"> <Search className="w-4 h-4 text-gray-500" /> </div> <input type="text" className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full pl-10 p-2" placeholder="Search employees..." value={searchTerm} onChange={handleSearch} /> </div> <div className="flex space-x-2"> <Button variant="outline" size="sm" icon={<Filter className="w-4 h-4" />} onClick={() => setShowFilters(!showFilters)} > Filters {(filters.race !== 'All' || filters.gender !== 'All' || filters.occupationalLevel !== 'All' || filters.hasDisability !== 'All') && ( <span className="ml-1 px-1.5 py-0.5 text-xs bg-emerald-100 text-emerald-800 rounded-full"> {Object.values(filters).filter(v => v !== 'All').length} </span> )} </Button> {(filters.race !== 'All' || filters.gender !== 'All' || filters.occupationalLevel !== 'All' || filters.hasDisability !== 'All') && ( <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={resetFilters} > Clear </Button> )} </div> </div> {/* Expanded filters */} {showFilters && ( <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4"> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Race</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.race} onChange={(e) => setFilters({...filters, race: e.target.value as Race | 'All'})} > {races.map(race => ( <option key={race} value={race}>{race}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Gender</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.gender} onChange={(e) => setFilters({...filters, gender: e.target.value as Gender | 'All'})} > {genders.map(gender => ( <option key={gender} value={gender}>{gender}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Occupational Level</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.occupationalLevel} onChange={(e) => setFilters({...filters, occupationalLevel: e.target.value as OccupationalLevel | 'All'})} > {levels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Disability Status</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.hasDisability} onChange={(e) => setFilters({...filters, hasDisability: e.target.value as 'All' | 'Yes' | 'No'})} > <option value="All">All</option> <option value="Yes">With Disability</option> <option value="No">No Disability</option> </select> </div> </div> )} </div> {/* Table */} <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('lastName')} > <span>Employee</span> {sortField === 'lastName' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('race')} > <span>Race</span> {sortField === 'race' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('gender')} > <span>Gender</span> {sortField === 'gender' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('occupationalLevel')} > <span>Occupational Level</span> {sortField === 'occupationalLevel' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('hasDisability')} > <span>Disability</span> {sortField === 'hasDisability' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Actions </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {filteredEmployees.length > 0 ? ( filteredEmployees.map((employee) => ( <tr key={employee.id} className="hover:bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center"> <div> <div className="text-sm font-medium text-gray-900"> {employee.firstName} {employee.lastName} </div> <div className="text-sm text-gray-500"> {employee.idNumber} </div> </div> </div> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800"> {employee.race} </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {employee.gender} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {employee.occupationalLevel} </td> <td className="px-6 py-4 whitespace-nowrap"> {employee.hasDisability ? ( <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-amber-100 text-amber-800"> Yes </span> ) : ( <span className="text-sm text-gray-500">No</span> )} </td> <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> <div className="flex justify-end space-x-2"> <button onClick={() => onView(employee)} className="text-blue-600 hover:text-blue-900 focus:outline-none" > <Info className="w-5 h-5" /> </button> <button onClick={() => onEdit(employee)} className="text-indigo-600 hover:text-indigo-900 focus:outline-none" > <Edit className="w-5 h-5" /> </button> <button onClick={() => onDelete(employee.id)} className="text-red-600 hover:text-red-900 focus:outline-none" > <Trash2 className="w-5 h-5" /> </button> </div> </td> </tr> )) ) : ( <tr> <td colSpan={6} className="px-6 py-4 text-center text-sm text-gray-500"> No employees found matching the current filters. </td> </tr> )} </tbody> </table> </div> {/* Table footer with counts */} <div className="px-6 py-3 bg-gray-50 border-t border-gray-200 text-sm text-gray-500"> Showing {filteredEmployees.length} of {employees.length} employees </div> </Card> ); }; export default EmployeeTable; import React from 'react'; import { EquityGoal } from '../../types'; import Card from '../common/Card'; import { calculateGoalProgress } from '../../utils/calculations'; import { format } from 'date-fns'; interface GoalTrackerProps { goals: EquityGoal[]; } const GoalTracker: React.FC<GoalTrackerProps> = ({ goals }) => { if (!goals || goals.length === 0) { return ( <Card title="Equity Goals Progress"> <div className="flex flex-col items-center justify-center py-8"> <p className="text-gray-500 mb-4">No equity goals have been set yet.</p> <a href="/goals" className="text-emerald-600 hover:text-emerald-700 font-medium"> + Add Equity Goals </a> </div> </Card> ); } return ( <Card title="Equity Goals Progress" className="h-full"> <div className="space-y-6 max-h-[350px] overflow-y-auto pr-2"> {goals.map((goal) => { const progress = calculateGoalProgress(goal.targetPercentage, goal.currentPercentage); return ( <div key={goal.id} className="space-y-2"> <div className="flex justify-between items-center"> <div> <h4 className="font-medium text-gray-900"> {goal.targetGroup} - {goal.occupationalLevel} </h4> <p className="text-sm text-gray-500"> Target: {goal.targetPercentage}% by {format(new Date(goal.targetDate), 'MMM d, yyyy')} </p> </div> <div className="text-right"> <span className="text-sm font-medium text-gray-900"> {goal.currentPercentage}% </span> <span className="text-xs text-gray-500 ml-1"> of {goal.targetPercentage}% </span> </div> </div> {/* Progress bar */} <div className="w-full bg-gray-200 rounded-full h-2.5"> <div className={`h-2.5 rounded-full ${getProgressColorClass(progress)}`} style={{ width: `${progress}%` }} ></div> </div> {/* Progress indicator */} <div className="flex justify-between text-xs"> <span className={getProgressTextColorClass(progress)}> {progress}% Complete </span> {goal.notes && ( <span className="text-gray-500 truncate max-w-[60%]" title={goal.notes}> {goal.notes} </span> )} </div> </div> ); })} </div> </Card> ); }; const getProgressColorClass = (progress: number): string => { if (progress < 25) return 'bg-red-600'; if (progress < 50) return 'bg-amber-500'; if (progress < 75) return 'bg-blue-500'; return 'bg-emerald-600'; }; const getProgressTextColorClass = (progress: number): string => { if (progress < 25) return 'text-red-600 font-medium'; if (progress < 50) return 'text-amber-500 font-medium'; if (progress < 75) return 'text-blue-600 font-medium'; return 'text-emerald-600 font-medium'; }; export default GoalTracker; import React, { useEffect, useState } from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement, RadialLinearScale } from 'chart.js'; import { Bar, Doughnut, Radar } from 'react-chartjs-2'; import Card from '../common/Card'; import { Race, Gender, Employee } from '../../types'; import { calculateRacePercentages, calculateGenderPercentages, calculateDisabilityPercentage } from '../../utils/calculations'; // Register ChartJS components ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement, RadialLinearScale ); interface DemographicChartProps { employees: Employee[]; chartType: 'race' | 'gender' | 'occupational' | 'disability'; title?: string; } const DemographicChart: React.FC<DemographicChartProps> = ({ employees, chartType, title }) => { const [chartData, setChartData] = useState<any>(null); const [loading, setLoading] = useState(true); useEffect(() => { if (!employees || employees.length === 0) { setLoading(false); return; } let data; let options; switch (chartType) { case 'race': const racePercentages = calculateRacePercentages(employees); data = { labels: Object.keys(racePercentages) as Race[], datasets: [ { label: 'Race Distribution', data: Object.values(racePercentages), backgroundColor: [ 'rgba(16, 185, 129, 0.7)', // emerald 'rgba(59, 130, 246, 0.7)', // blue 'rgba(245, 158, 11, 0.7)', // amber 'rgba(244, 63, 94, 0.7)', // rose 'rgba(139, 92, 246, 0.7)', // violet ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Race Distribution', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; case 'gender': const genderPercentages = calculateGenderPercentages(employees); data = { labels: Object.keys(genderPercentages), datasets: [ { label: 'Gender Distribution', data: Object.values(genderPercentages), backgroundColor: [ 'rgba(59, 130, 246, 0.7)', // blue 'rgba(244, 63, 94, 0.7)', // rose 'rgba(139, 92, 246, 0.7)', // violet ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Gender Distribution', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; case 'occupational': // Count employees by occupational level const occupationalLevels = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const occupationalCounts: Record<string, number> = {}; occupationalLevels.forEach(level => { occupationalCounts[level] = employees.filter(emp => emp.occupationalLevel === level).length; }); data = { labels: occupationalLevels, datasets: [ { label: '# of Employees', data: Object.values(occupationalCounts), backgroundColor: 'rgba(16, 185, 129, 0.7)', borderColor: 'rgba(16, 185, 129, 1)', borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { display: false, }, title: { display: !!title, text: title || 'Occupational Levels', }, }, scales: { y: { beginAtZero: true, title: { display: true, text: 'Number of Employees' } }, x: { title: { display: true, text: 'Occupational Level' } } }, }; setChartData({ data, options, type: 'bar' }); break; case 'disability': const disabilityPercentage = calculateDisabilityPercentage(employees); data = { labels: ['With Disabilities', 'Without Disabilities'], datasets: [ { label: 'Disability Status', data: [disabilityPercentage, 100 - disabilityPercentage], backgroundColor: [ 'rgba(245, 158, 11, 0.7)', // amber 'rgba(209, 213, 219, 0.7)', // gray ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Disability Status', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; default: setChartData(null); } setLoading(false); }, [employees, chartType, title]); if (loading) { return <Card loading={true} />; } if (!chartData) { return ( <Card> <div className="flex items-center justify-center h-64"> <p className="text-gray-500">No data available</p> </div> </Card> ); } return ( <Card title={chartData.options.plugins.title.text} className="h-full"> <div className="h-64"> {chartData.type === 'doughnut' && ( <Doughnut data={chartData.data} options={chartData.options} /> )} {chartData.type === 'bar' && ( <Bar data={chartData.data} options={chartData.options} /> )} </div> </Card> ); }; export default DemographicChart; import React, { ReactNode } from 'react'; import Card from '../common/Card'; interface StatCardProps { title: string; value: string | number; change?: { value: number; isPositive: boolean; }; icon?: ReactNode; color?: 'emerald' | 'blue' | 'amber' | 'rose' | 'violet' | 'indigo'; } const StatCard: React.FC<StatCardProps> = ({ title, value, change, icon, color = 'emerald' }) => { const colorClasses = { emerald: 'bg-emerald-100 text-emerald-600', blue: 'bg-blue-100 text-blue-600', amber: 'bg-amber-100 text-amber-600', rose: 'bg-rose-100 text-rose-600', violet: 'bg-violet-100 text-violet-600', indigo: 'bg-indigo-100 text-indigo-600', }; const changeColorClasses = change?.isPositive ? 'text-green-600 bg-green-50' : 'text-red-600 bg-red-50'; return ( <Card className="hover:shadow-md transition-shadow duration-300"> <div className="flex items-start justify-between"> <div> <p className="text-sm font-medium text-gray-500">{title}</p> <p className="mt-2 text-3xl font-semibold text-gray-900">{value}</p> {change && ( <div className="mt-2 flex items-center"> <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${changeColorClasses}`}> {change.isPositive ? '↑' : '↓'} {Math.abs(change.value)}% </span> <span className="text-xs text-gray-500 ml-2">from last period</span> </div> )} </div> {icon && ( <div className={`p-3 rounded-full ${colorClasses[color]}`}> {icon} </div> )} </div> </Card> ); }; export default StatCard; import React, { ButtonHTMLAttributes, ReactNode } from 'react'; interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { variant?: 'primary' | 'secondary' | 'outline' | 'danger' | 'success' | 'text'; size?: 'sm' | 'md' | 'lg'; isLoading?: boolean; icon?: ReactNode; iconPosition?: 'left' | 'right'; fullWidth?: boolean; children: ReactNode; } const Button: React.FC<ButtonProps> = ({ variant = 'primary', size = 'md', isLoading = false, icon, iconPosition = 'left', fullWidth = false, className = '', children, disabled, ...rest }) => { // Base classes const baseClasses = 'inline-flex items-center justify-center font-medium rounded-md focus:outline-none transition-colors'; // Size classes const sizeClasses = { sm: 'px-3 py-1.5 text-sm', md: 'px-4 py-2 text-sm', lg: 'px-6 py-3 text-base' }; // Variant classes const variantClasses = { primary: 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm', secondary: 'bg-blue-600 hover:bg-blue-700 text-white shadow-sm', outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50', danger: 'bg-red-600 hover:bg-red-700 text-white shadow-sm', success: 'bg-green-600 hover:bg-green-700 text-white shadow-sm', text: 'text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50' }; // Disabled classes const disabledClasses = 'opacity-50 cursor-not-allowed pointer-events-none'; // Icon spacing const iconSpacing = icon ? (iconPosition === 'left' ? 'space-x-2' : 'space-x-reverse space-x-2') : ''; // Full width const widthClasses = fullWidth ? 'w-full' : ''; return ( <button className={` ${baseClasses} ${sizeClasses[size]} ${variantClasses[variant]} ${(disabled || isLoading) ? disabledClasses : ''} ${iconSpacing} ${widthClasses} ${className} `} disabled={disabled || isLoading} {...rest} > {isLoading ? ( <> <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" > <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" ></circle> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" ></path> </svg> {children} </> ) : ( <> {icon && iconPosition === 'left' && <span>{icon}</span>} <span>{children}</span> {icon && iconPosition === 'right' && <span>{icon}</span>} </> )} </button> ); }; export default Button; import React, { ReactNode } from 'react'; interface CardProps { title?: string; children: ReactNode; className?: string; footer?: ReactNode; noPadding?: boolean; loading?: boolean; } const Card: React.FC<CardProps> = ({ title, children, className = '', footer, noPadding = false, loading = false }) => { return ( <div className={`bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden ${className}`}> {title && ( <div className="px-6 py-4 border-b border-gray-200"> <h3 className="text-lg font-medium text-gray-900">{title}</h3> </div> )} <div className={`${noPadding ? '' : 'p-6'} ${loading ? 'opacity-50' : ''}`}> {loading ? ( <div className="flex items-center justify-center py-8"> <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div> </div> ) : ( children )} </div> {footer && ( <div className="px-6 py-3 bg-gray-50 border-t border-gray-200"> {footer} </div> )} </div> ); }; export default Card; import React, { useState, useEffect } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { Menu, X, UserCircle, LogOut, ChevronDown } from 'lucide-react'; import { useAppContext } from '../../contexts/AppContext'; const Header: React.FC = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const [isUserMenuOpen, setIsUserMenuOpen] = useState(false); const [scrolled, setScrolled] = useState(false); const { currentUser, logout } = useAppContext(); const location = useLocation(); // Handle scroll effect for header useEffect(() => { const handleScroll = () => { if (window.scrollY > 10) { setScrolled(true); } else { setScrolled(false); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); // Close mobile menu when route changes useEffect(() => { setIsMenuOpen(false); }, [location]); return ( <header className={`fixed top-0 left-0 right-0 z-10 transition-all duration-300 ${ scrolled ? 'bg-white shadow-md py-2' : 'bg-transparent py-4' }`} > <div className="container mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex justify-between items-center"> {/* Logo */} <Link to="/" className="flex items-center"> <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-xl mr-2"> EE </div> <span className="text-xl font-bold text-gray-800">EquityTool</span> </Link> {/* Desktop Navigation */} <nav className="hidden md:flex space-x-8"> <NavLink to="/" active={location.pathname === '/'}>Dashboard</NavLink> <NavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</NavLink> <NavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</NavLink> <NavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</NavLink> <NavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</NavLink> </nav> {/* User Menu (Desktop) */} <div className="hidden md:flex items-center"> {currentUser ? ( <div className="relative"> <button className="flex items-center space-x-2 text-gray-700 hover:text-emerald-600 focus:outline-none" onClick={() => setIsUserMenuOpen(!isUserMenuOpen)} > <UserCircle className="w-6 h-6" /> <span>{currentUser.name}</span> <ChevronDown className={`w-4 h-4 transition-transform ${isUserMenuOpen ? 'rotate-180' : ''}`} /> </button> {isUserMenuOpen && ( <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20"> <div className="px-4 py-2 text-sm text-gray-500 border-b"> Logged in as <span className="font-semibold">{currentUser.role}</span> </div> <Link to="/profile" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" onClick={() => setIsUserMenuOpen(false)} > Profile Settings </Link> <button className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsUserMenuOpen(false); }} > <div className="flex items-center"> <LogOut className="w-4 h-4 mr-2" /> Sign Out </div> </button> </div> )} </div> ) : ( <Link to="/login" className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-emerald-600 hover:bg-emerald-700" > Sign In </Link> )} </div> {/* Mobile Menu Button */} <button className="md:hidden text-gray-700 focus:outline-none" onClick={() => setIsMenuOpen(!isMenuOpen)} > {isMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />} </button> </div> </div> {/* Mobile Menu */} {isMenuOpen && ( <div className="md:hidden bg-white border-t shadow-lg"> <div className="px-2 pt-2 pb-3 space-y-1"> <MobileNavLink to="/" active={location.pathname === '/'}>Dashboard</MobileNavLink> <MobileNavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</MobileNavLink> <MobileNavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</MobileNavLink> <MobileNavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</MobileNavLink> <MobileNavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</MobileNavLink> </div> {/* User Menu (Mobile) */} <div className="px-5 pt-4 pb-3 border-t border-gray-200"> {currentUser ? ( <> <div className="flex items-center mb-3"> <div className="flex-shrink-0"> <UserCircle className="w-10 h-10 text-gray-400" /> </div> <div className="ml-3"> <div className="text-base font-medium text-gray-800">{currentUser.name}</div> <div className="text-sm font-medium text-gray-500">{currentUser.email}</div> </div> </div> <div className="space-y-1"> <Link to="/profile" className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:bg-gray-100" > Profile Settings </Link> <button className="block w-full text-left px-3 py-2 rounded-md text-base font-medium text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsMenuOpen(false); }} > Sign Out </button> </div> </> ) : ( <Link to="/login" className="block w-full px-5 py-3 text-center font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-md" > Sign In </Link> )} </div> </div> )} </header> ); }; interface NavLinkProps { to: string; active: boolean; children: React.ReactNode; } const NavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`relative px-2 py-1 transition-colors ${ active ? 'text-emerald-600 font-medium' : 'text-gray-600 hover:text-emerald-600' }`} > {children} {active && ( <span className="absolute bottom-0 left-0 w-full h-0.5 bg-emerald-600 rounded-full"></span> )} </Link> ); }; const MobileNavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`block px-3 py-2 rounded-md text-base font-medium ${ active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-700 hover:bg-gray-50 hover:text-emerald-600' }`} > {children} </Link> ); }; export default Header; import React, { createContext, useContext, useState, ReactNode } from 'react'; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { mockEmployees, mockCompanyInfo, mockEquityGoals, mockDemographicSummary, mockUsers } from '../utils/mockData'; import { calculateDemographicSummary } from '../utils/calculations'; interface AppContextType { employees: Employee[]; addEmployee: (employee: Employee) => void; updateEmployee: (employee: Employee) => void; deleteEmployee: (id: string) => void; companyInfo: CompanyInfo; updateCompanyInfo: (info: CompanyInfo) => void; equityGoals: EquityGoal[]; addEquityGoal: (goal: EquityGoal) => void; updateEquityGoal: (goal: EquityGoal) => void; deleteEquityGoal: (id: string) => void; demographicSummary: DemographicSummary[]; refreshDemographicSummary: () => void; users: User[]; addUser: (user: User) => void; updateUser: (user: User) => void; deleteUser: (id: string) => void; currentUser: User | null; login: (email: string, role?: string) => void; logout: () => void; } const AppContext = createContext<AppContextType | undefined>(undefined); export const AppProvider: React.FC<{children: ReactNode}> = ({ children }) => { const [employees, setEmployees] = useState<Employee[]>(mockEmployees); const [companyInfo, setCompanyInfo] = useState<CompanyInfo>(mockCompanyInfo); const [equityGoals, setEquityGoals] = useState<EquityGoal[]>(mockEquityGoals); const [demographicSummary, setDemographicSummary] = useState<DemographicSummary[]>(mockDemographicSummary); const [users, setUsers] = useState<User[]>(mockUsers); const [currentUser, setCurrentUser] = useState<User | null>(null); // Employee functions const addEmployee = (employee: Employee) => { setEmployees(prev => [...prev, employee]); refreshDemographicSummary(); }; const updateEmployee = (employee: Employee) => { setEmployees(prev => prev.map(emp => emp.id === employee.id ? employee : emp)); refreshDemographicSummary(); }; const deleteEmployee = (id: string) => { setEmployees(prev => prev.filter(emp => emp.id !== id)); refreshDemographicSummary(); }; // Company info functions const updateCompanyInfo = (info: CompanyInfo) => { setCompanyInfo(info); }; // Equity goal functions const addEquityGoal = (goal: EquityGoal) => { setEquityGoals(prev => [...prev, goal]); }; const updateEquityGoal = (goal: EquityGoal) => { setEquityGoals(prev => prev.map(g => g.id === goal.id ? goal : g)); }; const deleteEquityGoal = (id: string) => { setEquityGoals(prev => prev.filter(g => g.id !== id)); }; // Demographic summary functions const refreshDemographicSummary = () => { const summary = calculateDemographicSummary(employees); setDemographicSummary(summary); }; // User management functions const addUser = (user: User) => { setUsers(prev => [...prev, user]); }; const updateUser = (user: User) => { setUsers(prev => prev.map(u => u.id === user.id ? user : u)); }; const deleteUser = (id: string) => { setUsers(prev => prev.filter(u => u.id !== id)); }; // Authentication functions const login = (email: string, role?: string) => { // For demo purposes, auto-login with the first user or specified role let userToLogin; if (role) { userToLogin = users.find(u => u.role === role); } else { userToLogin = users.find(u => u.email === email); } if (userToLogin) { setCurrentUser(userToLogin); return true; } return false; }; const logout = () => { setCurrentUser(null); }; const value = { employees, addEmployee, updateEmployee, deleteEmployee, companyInfo, updateCompanyInfo, equityGoals, addEquityGoal, updateEquityGoal, deleteEquityGoal, demographicSummary, refreshDemographicSummary, users, addUser, updateUser, deleteUser, currentUser, login, logout }; return <AppContext.Provider value={value}>{children}</AppContext.Provider>; }; export const useAppContext = (): AppContextType => { const context = useContext(AppContext); if (context === undefined) { throw new Error('useAppContext must be used within an AppProvider'); } return context; }; { "name": "equity-compliance-tool", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint .", "preview": "vite preview" }, "dependencies": { "@headlessui/react": "^1.7.17", "chart.js": "^4.4.1", "date-fns": "^2.30.0", "lucide-react": "^0.344.0", "react": "^18.3.1", "react-chartjs-2": "^5.2.0", "react-dom": "^18.3.1", "react-router-dom": "^6.22.1", "uuid": "^9.0.1" }, "devDependencies": { "@eslint/js": "^9.9.1", "@types/react": "^18.3.5", "@types/react-dom": "^18.3.0", "@types/uuid": "^9.0.7", "@vitejs/plugin-react": "^4.3.1", "autoprefixer": "^10.4.18", "eslint": "^9.9.1", "eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-refresh": "^0.4.11", "globals": "^15.9.0", "postcss": "^8.4.35", "tailwindcss": "^3.4.1", "typescript": "^5.5.3", "typescript-eslint": "^8.3.0", "vite": "^5.4.2" } } import { Employee, DemographicSummary, OccupationalLevel, Race, Gender } from '../types'; /** * Calculates demographic summary by occupational level */ export const calculateDemographicSummary = ( employees: Employee[] ): DemographicSummary[] => { // Get unique occupational levels const occupationalLevels = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ] as OccupationalLevel[]; return occupationalLevels.map(level => { const levelEmployees = employees.filter(emp => emp.occupationalLevel === level); // Initialize summary const summary: DemographicSummary = { occupationalLevel: level, maleBlack: 0, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: levelEmployees.length }; // Count by demographics levelEmployees.forEach(emp => { // Count by gender and race if (emp.gender === 'Male') { if (emp.race === 'Black') summary.maleBlack++; else if (emp.race === 'Coloured') summary.maleColoured++; else if (emp.race === 'Indian') summary.maleIndian++; else if (emp.race === 'White') summary.maleWhite++; else if (emp.race === 'Foreign National') summary.maleForeignNational++; } else if (emp.gender === 'Female') { if (emp.race === 'Black') summary.femaleBlack++; else if (emp.race === 'Coloured') summary.femaleColoured++; else if (emp.race === 'Indian') summary.femaleIndian++; else if (emp.race === 'White') summary.femaleWhite++; else if (emp.race === 'Foreign National') summary.femaleForeignNational++; } // Count people with disabilities if (emp.hasDisability) { summary.disabledCount++; } }); return summary; }); }; /** * Calculate percentage of employees by race */ export const calculateRacePercentages = (employees: Employee[]): Record<Race, number> => { const total = employees.length; const counts: Record<Race, number> = { 'Black': 0, 'Coloured': 0, 'Indian': 0, 'White': 0, 'Foreign National': 0 }; employees.forEach(emp => { counts[emp.race]++; }); const percentages: Record<Race, number> = {} as Record<Race, number>; Object.keys(counts).forEach(race => { percentages[race as Race] = total > 0 ? Math.round((counts[race as Race] / total) * 100) : 0; }); return percentages; }; /** * Calculate percentage of employees by gender */ export const calculateGenderPercentages = (employees: Employee[]): Record<string, number> => { const total = employees.length; const counts: Record<string, number> = { 'Male': 0, 'Female': 0, 'Non-binary': 0 }; employees.forEach(emp => { counts[emp.gender]++; }); const percentages: Record<string, number> = {}; Object.keys(counts).forEach(gender => { percentages[gender] = total > 0 ? Math.round((counts[gender] / total) * 100) : 0; }); return percentages; }; /** * Calculate percentage of employees with disabilities */ export const calculateDisabilityPercentage = (employees: Employee[]): number => { const total = employees.length; const disabledCount = employees.filter(emp => emp.hasDisability).length; return total > 0 ? Math.round((disabledCount / total) * 100) : 0; }; /** * Filter employees by department */ export const filterByDepartment = (employees: Employee[], department: string): Employee[] => { if (!department || department === 'All Departments') { return employees; } return employees.filter(emp => emp.department === department); }; /** * Get unique departments from employee data */ export const getUniqueDepartments = (employees: Employee[]): string[] => { const departments = new Set<string>(); employees.forEach(emp => departments.add(emp.department)); return Array.from(departments).sort(); }; /** * Calculate progress towards goals */ export const calculateGoalProgress = ( targetPercentage: number, currentPercentage: number ): number => { if (targetPercentage <= 0) return 100; return Math.min(Math.round((currentPercentage / targetPercentage) * 100), 100); }; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { v4 as uuidv4 } from 'uuid'; // Mock Company Information - Updated for 2024 legislation export const mockCompanyInfo: CompanyInfo = { name: 'Exemplar Holdings', registrationNumber: '2010/123456/07', industry: 'Financial Services', sectorCode: 'K', address: '123 Main Street, Sandton, Johannesburg, 2196', province: 'Gauteng', contactPerson: 'Jane Smith', contactEmail: 'jane.smith@exemplar.co.za', contactPhone: '011 123 4567', employeeCount: 245, designatedEmployer: true, complianceOfficer: 'John Doe', complianceOfficerContact: 'john.doe@exemplar.co.za' }; // Mock Employees export const mockEmployees: Employee[] = [ { id: uuidv4(), firstName: 'Thabo', lastName: 'Mbeki', idNumber: '7501015800082', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Top Management', department: 'Executive', salary: 1200000, joinDate: '2020-01-15' }, { id: uuidv4(), firstName: 'Sarah', lastName: 'Johnson', idNumber: '8012045800082', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Senior Management', department: 'Finance', salary: 850000, joinDate: '2019-04-12' }, { id: uuidv4(), firstName: 'Lerato', lastName: 'Nkosi', idNumber: '8909235800083', race: 'Black', gender: 'Female', hasDisability: true, disabilityDetails: 'Hearing impairment', occupationalLevel: 'Professionally Qualified', department: 'Human Resources', salary: 620000, joinDate: '2018-06-01' }, { id: uuidv4(), firstName: 'Ahmed', lastName: 'Patel', idNumber: '7705125800084', race: 'Indian', gender: 'Male', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 450000, joinDate: '2021-03-15' }, { id: uuidv4(), firstName: 'Jessica', lastName: 'De Villiers', idNumber: '9012055800086', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Professionally Qualified', department: 'Marketing', salary: 580000, joinDate: '2019-11-01' }, { id: uuidv4(), firstName: 'Sipho', lastName: 'Ndlovu', idNumber: '8504175800087', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Semi-skilled', department: 'Operations', salary: 320000, joinDate: '2020-08-15' }, { id: uuidv4(), firstName: 'Fatima', lastName: 'Mohammed', idNumber: '9108235800088', race: 'Indian', gender: 'Female', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 470000, joinDate: '2019-05-20' }, { id: uuidv4(), firstName: 'James', lastName: 'Wilson', idNumber: '8306155800089', race: 'Coloured', gender: 'Male', hasDisability: true, disabilityDetails: 'Mobility impairment', occupationalLevel: 'Skilled Technical', department: 'Finance', salary: 420000, joinDate: '2018-10-10' } ]; // Mock Equity Goals export const mockEquityGoals: EquityGoal[] = [ { id: uuidv4(), occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 25, targetPercentage: 50, targetDate: '2025-12-31', notes: 'Focus on internal promotions and external recruitment' }, { id: uuidv4(), occupationalLevel: 'Senior Management', targetGroup: 'Female', currentPercentage: 30, targetPercentage: 45, targetDate: '2024-12-31', notes: 'Implement mentorship program to prepare for promotions' }, { id: uuidv4(), occupationalLevel: 'Professionally Qualified', targetGroup: 'People with Disabilities', currentPercentage: 2, targetPercentage: 7, targetDate: '2025-06-30', notes: 'Improve workplace accessibility and targeted recruitment' } ]; // Mock Demographic Summary export const mockDemographicSummary: DemographicSummary[] = [ { occupationalLevel: 'Top Management', maleBlack: 1, maleColoured: 0, maleIndian: 0, maleWhite: 3, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 1, femaleForeignNational: 0, disabledCount: 0, total: 5 }, { occupationalLevel: 'Senior Management', maleBlack: 2, maleColoured: 1, maleIndian: 1, maleWhite: 5, maleForeignNational: 1, femaleBlack: 1, femaleColoured: 1, femaleIndian: 0, femaleWhite: 3, femaleForeignNational: 0, disabledCount: 1, total: 15 }, { occupationalLevel: 'Professionally Qualified', maleBlack: 15, maleColoured: 6, maleIndian: 8, maleWhite: 12, maleForeignNational: 2, femaleBlack: 12, femaleColoured: 5, femaleIndian: 7, femaleWhite: 10, femaleForeignNational: 1, disabledCount: 4, total: 78 }, { occupationalLevel: 'Skilled Technical', maleBlack: 25, maleColoured: 8, maleIndian: 6, maleWhite: 10, maleForeignNational: 3, femaleBlack: 18, femaleColoured: 7, femaleIndian: 5, femaleWhite: 8, femaleForeignNational: 2, disabledCount: 5, total: 92 }, { occupationalLevel: 'Semi-skilled', maleBlack: 18, maleColoured: 5, maleIndian: 2, maleWhite: 3, maleForeignNational: 4, femaleBlack: 12, femaleColoured: 3, femaleIndian: 1, femaleWhite: 2, femaleForeignNational: 0, disabledCount: 2, total: 50 }, { occupationalLevel: 'Unskilled', maleBlack: 3, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 2, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: 5 } ]; // Mock Users - Updated with analyst role export const mockUsers: User[] = [ { id: uuidv4(), name: 'Admin User', email: 'admin@exemplar.co.za', cellphone: '+27821234567', role: 'admin', lastLogin: '2023-06-15T08:30:00Z', isVerified: true }, { id: uuidv4(), name: 'HR Manager', email: 'hr@exemplar.co.za', cellphone: '+27829876543', role: 'manager', lastLogin: '2023-06-14T11:45:00Z', isVerified: true }, { id: uuidv4(), name: 'Department Head', email: 'department@exemplar.co.za', cellphone: '+27835551234', role: 'viewer', lastLogin: '2023-06-10T09:15:00Z', isVerified: true }, { id: uuidv4(), name: 'Equity Analyst', email: 'analyst@exemplar.co.za', cellphone: '+27847778888', role: 'analyst', lastLogin: '2023-06-16T14:20:00Z', isVerified: true } ]; // Employment Equity Types export type Race = 'Black' | 'Coloured' | 'Indian' | 'White' | 'Foreign National'; export type Gender = 'Male' | 'Female' | 'Non-binary'; export type OccupationalLevel = | 'Top Management' | 'Senior Management' | 'Professionally Qualified' | 'Skilled Technical' | 'Semi-skilled' | 'Unskilled' | 'Temporary Employees'; export interface Employee { id: string; firstName: string; lastName: string; idNumber: string; race: Race; gender: Gender; hasDisability: boolean; disabilityDetails?: string; occupationalLevel: OccupationalLevel; department: string; salary: number; joinDate: string; terminationDate?: string; jobTitle?: string; yearsOfExperience?: number; qualifications?: string[]; performanceRating?: number; } export interface CompanyInfo { name: string; registrationNumber: string; industry: string; sectorCode: string; address: string; province: string; contactPerson: string; contactEmail: string; contactPhone: string; employeeCount: number; designatedEmployer: boolean; complianceOfficer: string; complianceOfficerContact: string; } export interface EquityGoal { id: string; occupationalLevel: OccupationalLevel; targetGroup: Race | Gender | 'People with Disabilities'; currentPercentage: number; targetPercentage: number; targetDate: string; notes?: string; } export interface DemographicSummary { occupationalLevel: OccupationalLevel; maleBlack: number; maleColoured: number; maleIndian: number; maleWhite: number; maleForeignNational: number; femaleBlack: number; femaleColoured: number; femaleIndian: number; femaleWhite: number; femaleForeignNational: number; disabledCount: number; total: number; } export interface User { id: string; name: string; email: string; cellphone?: string; role: 'admin' | 'manager' | 'viewer' | 'analyst'; lastLogin?: string; isVerified?: boolean; } export interface BarrierAnalysis { id: string; category: BarrierCategory; description: string; affectedGroups: (Race | Gender | 'People with Disabilities')[]; impact: 'High' | 'Medium' | 'Low'; remedialActions: string[]; timeframe: string; status: 'Identified' | 'In Progress' | 'Completed'; responsiblePerson: string; dateIdentified: string; completionDate?: string; } export type BarrierCategory = | 'Recruitment Procedures' | 'Advertising Positions' | 'Selection Criteria' | 'Appointments' | 'Job Classification' | 'Remuneration' | 'Terms & Conditions' | 'Job Assignments' | 'Work Environment' | 'Training & Development' | 'Performance Evaluation' | 'Promotions' | 'Transfers' | 'Succession Planning' | 'Disciplinary Measures' | 'Company Culture' | 'Reasonable Accommodation' | 'HIV & AIDS Prevention' | 'Other'; export interface PayAnalysis { id: string; occupationalLevel: OccupationalLevel; jobTitle: string; differenceReason?: PayDifferenceReason[]; averageSalaryByRace: Record<Race, number>; averageSalaryByGender: Record<Gender, number>; payGapPercentage: number; justificationNotes?: string; actionPlan?: string; reviewDate: string; } export type PayDifferenceReason = | 'Seniority' | 'Experience' | 'Qualifications' | 'Performance' | 'Scarce Skills' | 'Market Forces' | 'Responsibility Level' | 'Other'; // New types for enhanced functionality export interface BarrierQuestionnaire { id: string; respondentId: string; respondentName: string; respondentEmail: string; respondentCellphone: string; department: string; position: string; dateCompleted: string; responses: QuestionnaireResponse[]; status: 'Draft' | 'Submitted' | 'Reviewed'; } export interface QuestionnaireResponse { questionId: string; question: string; category: BarrierCategory; response: 'Yes' | 'No' | 'Partially' | 'Not Applicable'; comments?: string; severity?: 'Low' | 'Medium' | 'High'; } export interface BarrierQuestion { id: string; category: BarrierCategory; question: string; description?: string; isRequired: boolean; } export interface EconomicActivePopulation { province: string; sectorCode: string; sectorName: string; nationalData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; provincialData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; sectorData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; } export interface CellphoneVerification { cellphone: string; verificationCode: string; isVerified: boolean; expiresAt: string; } export interface AnalysisResult { id: string; questionnaireId: string; overallScore: number; categoryScores: Record<BarrierCategory, number>; identifiedBarriers: string[]; recommendations: string[]; priorityActions: string[]; complianceRisk: 'Low' | 'Medium' | 'High'; generatedDate: string; } import { BarrierQuestion, BarrierCategory } from '../types'; export const barrierQuestions: BarrierQuestion[] = [ // Recruitment Procedures { id: 'rec_001', category: 'Recruitment Procedures', question: 'Are recruitment procedures documented and consistently applied across all positions?', description: 'Assess whether standardized recruitment processes exist', isRequired: true }, { id: 'rec_002', category: 'Recruitment Procedures', question: 'Do recruitment procedures include specific measures to attract designated groups?', description: 'Evaluate proactive recruitment strategies for equity', isRequired: true }, { id: 'rec_003', category: 'Recruitment Procedures', question: 'Are recruitment sources diverse and include platforms that reach designated groups?', description: 'Check if recruitment channels are inclusive', isRequired: true }, // Advertising Positions { id: 'adv_001', category: 'Advertising Positions', question: 'Are job advertisements placed in media that reach designated groups?', description: 'Assess advertising reach to diverse communities', isRequired: true }, { id: 'adv_002', category: 'Advertising Positions', question: 'Do job advertisements include employment equity statements?', description: 'Check for inclusive language in job postings', isRequired: true }, { id: 'adv_003', category: 'Advertising Positions', question: 'Are job requirements clearly justified and not unnecessarily restrictive?', description: 'Evaluate if requirements create unfair barriers', isRequired: true }, // Selection Criteria { id: 'sel_001', category: 'Selection Criteria', question: 'Are selection criteria job-related and consistently applied?', description: 'Assess fairness and relevance of selection standards', isRequired: true }, { id: 'sel_002', category: 'Selection Criteria', question: 'Do selection panels include diverse representation?', description: 'Check composition of interview panels', isRequired: true }, { id: 'sel_003', category: 'Selection Criteria', question: 'Are unconscious bias training provided to selection panel members?', description: 'Evaluate bias mitigation measures', isRequired: true }, // Appointments { id: 'app_001', category: 'Appointments', question: 'Are appointment decisions documented with clear justifications?', description: 'Assess transparency in hiring decisions', isRequired: true }, { id: 'app_002', category: 'Appointments', question: 'Is preference given to designated group members when candidates are equally qualified?', description: 'Check implementation of affirmative action', isRequired: true }, // Job Classification { id: 'job_001', category: 'Job Classification', question: 'Are job classifications based on objective job evaluation systems?', description: 'Assess fairness in job grading', isRequired: true }, { id: 'job_002', category: 'Job Classification', question: 'Are job classifications regularly reviewed for bias?', description: 'Check for systematic review processes', isRequired: true }, // Remuneration { id: 'rem_001', category: 'Remuneration', question: 'Is there a transparent remuneration policy applied consistently?', description: 'Assess pay equity policies', isRequired: true }, { id: 'rem_002', category: 'Remuneration', question: 'Are regular pay equity analyses conducted?', description: 'Check for systematic pay gap monitoring', isRequired: true }, { id: 'rem_003', category: 'Remuneration', question: 'Are unjustifiable pay differences addressed promptly?', description: 'Evaluate remedial action processes', isRequired: true }, // Terms & Conditions { id: 'terms_001', category: 'Terms & Conditions', question: 'Are terms and conditions of employment applied equally to all employees?', description: 'Assess consistency in employment terms', isRequired: true }, { id: 'terms_002', category: 'Terms & Conditions', question: 'Are flexible work arrangements available to accommodate diverse needs?', description: 'Check for inclusive work policies', isRequired: true }, // Training & Development { id: 'train_001', category: 'Training & Development', question: 'Are training and development opportunities equally accessible to all employees?', description: 'Assess equity in skills development', isRequired: true }, { id: 'train_002', category: 'Training & Development', question: 'Are there specific development programs for designated groups?', description: 'Check for targeted development initiatives', isRequired: true }, { id: 'train_003', category: 'Training & Development', question: 'Is training provided in accessible formats for people with disabilities?', description: 'Evaluate accessibility of training materials', isRequired: true }, // Performance Evaluation { id: 'perf_001', category: 'Performance Evaluation', question: 'Are performance evaluation criteria objective and job-related?', description: 'Assess fairness in performance management', isRequired: true }, { id: 'perf_002', category: 'Performance Evaluation', question: 'Are evaluators trained to avoid bias in performance assessments?', description: 'Check for bias mitigation in evaluations', isRequired: true }, // Promotions { id: 'prom_001', category: 'Promotions', question: 'Are promotion criteria transparent and consistently applied?', description: 'Assess fairness in advancement opportunities', isRequired: true }, { id: 'prom_002', category: 'Promotions', question: 'Are designated group members given preference when equally qualified?', description: 'Check implementation of affirmative action in promotions', isRequired: true }, // Work Environment { id: 'env_001', category: 'Work Environment', question: 'Is the workplace free from discrimination and harassment?', description: 'Assess workplace culture and safety', isRequired: true }, { id: 'env_002', category: 'Work Environment', question: 'Are reasonable accommodations provided for people with disabilities?', description: 'Check accessibility and accommodation measures', isRequired: true }, { id: 'env_003', category: 'Work Environment', question: 'Are cultural and religious practices respected and accommodated?', description: 'Evaluate cultural inclusivity', isRequired: true }, // Company Culture { id: 'culture_001', category: 'Company Culture', question: 'Does leadership demonstrate visible commitment to employment equity?', description: 'Assess leadership engagement in equity initiatives', isRequired: true }, { id: 'culture_002', category: 'Company Culture', question: 'Are diversity and inclusion values embedded in company policies?', description: 'Check integration of equity principles', isRequired: true } ]; export const getQuestionsByCategory = (category: BarrierCategory): BarrierQuestion[] => { return barrierQuestions.filter(q => q.category === category); }; export const getAllCategories = (): BarrierCategory[] => { return Array.from(new Set(barrierQuestions.map(q => q.category))); }; import { EconomicActivePopulation } from '../types'; // Mock data based on Stats SA Quarterly Labour Force Survey export const economicActivePopulationData: EconomicActivePopulation[] = [ { province: 'Gauteng', sectorCode: 'J', sectorName: 'Information and Communication', nationalData: { blackMale: 285000, blackFemale: 195000, colouredMale: 25000, colouredFemale: 18000, indianMale: 35000, indianFemale: 22000, whiteMale: 125000, whiteFemale: 85000, total: 790000 }, provincialData: { blackMale: 95000, blackFemale: 65000, colouredMale: 8000, colouredFemale: 6000, indianMale: 15000, indianFemale: 9000, whiteMale: 45000, whiteFemale: 32000, total: 275000 }, sectorData: { blackMale: 142500, blackFemale: 97500, colouredMale: 12500, colouredFemale: 9000, indianMale: 17500, indianFemale: 11000, whiteMale: 62500, whiteFemale: 42500, total: 395000 } }, { province: 'Western Cape', sectorCode: 'K', sectorName: 'Financial and Insurance Activities', nationalData: { blackMale: 195000, blackFemale: 285000, colouredMale: 45000, colouredFemale: 65000, indianMale: 25000, indianFemale: 35000, whiteMale: 85000, whiteFemale: 125000, total: 860000 }, provincialData: { blackMale: 35000, blackFemale: 52000, colouredMale: 28000, colouredFemale: 42000, indianMale: 8000, indianFemale: 12000, whiteMale: 32000, whiteFemale: 48000, total: 257000 }, sectorData: { blackMale: 97500, blackFemale: 142500, colouredMale: 22500, colouredFemale: 32500, indianMale: 12500, indianFemale: 17500, whiteMale: 42500, whiteFemale: 62500, total: 430000 } }, { province: 'KwaZulu-Natal', sectorCode: 'C', sectorName: 'Manufacturing', nationalData: { blackMale: 850000, blackFemale: 425000, colouredMale: 95000, colouredFemale: 48000, indianMale: 65000, indianFemale: 32000, whiteMale: 125000, whiteFemale: 62000, total: 1702000 }, provincialData: { blackMale: 185000, blackFemale: 92000, colouredMale: 12000, colouredFemale: 6000, indianMale: 35000, indianFemale: 18000, whiteMale: 25000, whiteFemale: 12000, total: 385000 }, sectorData: { blackMale: 425000, blackFemale: 212500, colouredMale: 47500, colouredFemale: 24000, indianMale: 32500, indianFemale: 16000, whiteMale: 62500, whiteFemale: 31000, total: 851000 } } ]; export const getEconomicDataByProvince = (province: string): EconomicActivePopulation[] => { return economicActivePopulationData.filter(data => data.province === province); }; export const getEconomicDataBySector = (sectorCode: string): EconomicActivePopulation[] => { return economicActivePopulationData.filter(data => data.sectorCode === sectorCode); }; export const getAllProvinces = (): string[] => { return Array.from(new Set(economicActivePopulationData.map(data => data.province))); }; export const getAllSectors = (): { code: string; name: string }[] => { const sectors = new Map(); economicActivePopulationData.forEach(data => { sectors.set(data.sectorCode, data.sectorName); }); return Array.from(sectors.entries()).map(([code, name]) => ({ code, name })); }; import { BarrierQuestionnaire, QuestionnaireResponse, AnalysisResult, BarrierCategory } from '../types'; import { barrierQuestions } from './barrierQuestions'; export const analyzeQuestionnaire = (questionnaire: BarrierQuestionnaire): AnalysisResult => { const categoryScores: Record<BarrierCategory, number> = {} as Record<BarrierCategory, number>; const identifiedBarriers: string[] = []; const recommendations: string[] = []; const priorityActions: string[] = []; // Initialize category scores const categories = Array.from(new Set(barrierQuestions.map(q => q.category))); categories.forEach(category => { categoryScores[category] = 0; }); // Calculate scores by category categories.forEach(category => { const categoryResponses = questionnaire.responses.filter(r => r.category === category); const categoryQuestions = barrierQuestions.filter(q => q.category === category); if (categoryQuestions.length === 0) return; let categoryScore = 0; let totalPossible = categoryQuestions.length * 100; categoryResponses.forEach(response => { switch (response.response) { case 'Yes': categoryScore += 100; break; case 'Partially': categoryScore += 50; if (response.severity === 'High') { identifiedBarriers.push(`${category}: ${response.question}`); priorityActions.push(`Address partial compliance in ${category}`); } break; case 'No': categoryScore += 0; identifiedBarriers.push(`${category}: ${response.question}`); if (response.severity === 'High') { priorityActions.push(`Urgent action required: ${response.question}`); } break; case 'Not Applicable': totalPossible -= 100; break; } }); categoryScores[category] = totalPossible > 0 ? Math.round((categoryScore / totalPossible) * 100) : 100; }); // Calculate overall score const validScores = Object.values(categoryScores).filter(score => score >= 0); const overallScore = validScores.length > 0 ? Math.round(validScores.reduce((sum, score) => sum + score, 0) / validScores.length) : 0; // Generate recommendations based on scores Object.entries(categoryScores).forEach(([category, score]) => { if (score < 70) { recommendations.push(generateRecommendation(category as BarrierCategory, score)); } }); // Determine compliance risk let complianceRisk: 'Low' | 'Medium' | 'High' = 'Low'; if (overallScore < 60) { complianceRisk = 'High'; } else if (overallScore < 80) { complianceRisk = 'Medium'; } return { id: `analysis_${Date.now()}`, questionnaireId: questionnaire.id, overallScore, categoryScores, identifiedBarriers, recommendations, priorityActions, complianceRisk, generatedDate: new Date().toISOString() }; }; const generateRecommendation = (category: BarrierCategory, score: number): string => { const recommendations: Record<BarrierCategory, string> = { 'Recruitment Procedures': 'Develop standardized, inclusive recruitment procedures with clear documentation and training for hiring managers.', 'Advertising Positions': 'Expand job advertising to diverse media channels and include employment equity statements in all job postings.', 'Selection Criteria': 'Review and validate selection criteria for job-relatedness and implement diverse interview panels.', 'Appointments': 'Establish clear appointment decision documentation and implement affirmative action preferences.', 'Job Classification': 'Implement objective job evaluation systems and conduct regular bias reviews of job classifications.', 'Remuneration': 'Develop transparent pay policies and conduct regular pay equity analyses with remedial action plans.', 'Terms & Conditions': 'Ensure consistent application of employment terms and implement flexible work arrangements.', 'Job Assignments': 'Review job assignment processes for fairness and eliminate discriminatory practices.', 'Work Environment': 'Create inclusive workplace policies and provide reasonable accommodations for all employees.', 'Training & Development': 'Ensure equal access to development opportunities and create targeted programs for designated groups.', 'Performance Evaluation': 'Implement objective performance criteria and provide bias training for evaluators.', 'Promotions': 'Establish transparent promotion criteria and implement affirmative action in advancement decisions.', 'Transfers': 'Develop fair transfer policies that consider employee development and organizational needs.', 'Succession Planning': 'Create inclusive succession planning that identifies and develops diverse talent.', 'Disciplinary Measures': 'Ensure consistent and fair application of disciplinary procedures across all employee groups.', 'Company Culture': 'Foster inclusive leadership and embed diversity values in organizational policies and practices.', 'Reasonable Accommodation': 'Develop comprehensive accommodation policies and ensure accessibility in all workplace aspects.', 'HIV & AIDS Prevention': 'Implement non-discriminatory HIV/AIDS policies and provide education and support programs.', 'Other': 'Address specific barriers identified through targeted interventions and policy development.' }; return recommendations[category] || 'Implement targeted interventions to address identified barriers.'; }; export const generateComplianceReport = (analysis: AnalysisResult): string => { return ` Employment Equity Barrier Analysis Report Overall Compliance Score: ${analysis.overallScore}% Compliance Risk Level: ${analysis.complianceRisk} Category Breakdown: ${Object.entries(analysis.categoryScores) .map(([category, score]) => `- ${category}: ${score}%`) .join('\n')} Identified Barriers (${analysis.identifiedBarriers.length}): ${analysis.identifiedBarriers.map(barrier => `- ${barrier}`).join('\n')} Priority Actions Required: ${analysis.priorityActions.map(action => `- ${action}`).join('\n')} Recommendations: ${analysis.recommendations.map(rec => `- ${rec}`).join('\n')} Generated: ${new Date(analysis.generatedDate).toLocaleDateString()} `.trim(); }; import React, { useState, useEffect } from 'react'; import { CheckCircle, AlertTriangle, FileText, Send } from 'lucide-react'; import Button from '../common/Button'; import Card from '../common/Card'; import { BarrierQuestionnaire as BarrierQuestionnaireType, QuestionnaireResponse, BarrierCategory } from '../../types'; import { barrierQuestions, getAllCategories } from '../../utils/barrierQuestions'; import { v4 as uuidv4 } from 'uuid'; interface BarrierQuestionnaireProps { respondentName: string; respondentEmail: string; respondentCellphone: string; // Keep for compatibility but not used onSubmit: (questionnaire: BarrierQuestionnaireType) => void; onSaveDraft?: (questionnaire: BarrierQuestionnaireType) => void; } const BarrierQuestionnaire: React.FC<BarrierQuestionnaireProps> = ({ respondentName, respondentEmail, respondentCellphone, onSubmit, onSaveDraft }) => { const [currentCategory, setCurrentCategory] = useState<BarrierCategory>('Recruitment Procedures'); const [responses, setResponses] = useState<QuestionnaireResponse[]>([]); const [department, setDepartment] = useState(''); const [position, setPosition] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); const categories = getAllCategories(); const currentQuestions = barrierQuestions.filter(q => q.category === currentCategory); const currentCategoryIndex = categories.indexOf(currentCategory); const isLastCategory = currentCategoryIndex === categories.length - 1; // Initialize responses for current category useEffect(() => { const categoryResponses = responses.filter(r => r.category === currentCategory); const missingQuestions = currentQuestions.filter( q => !categoryResponses.find(r => r.questionId === q.id) ); if (missingQuestions.length > 0) { const newResponses = missingQuestions.map(q => ({ questionId: q.id, question: q.question, category: q.category, response: 'Not Applicable' as const, comments: '', severity: 'Medium' as const })); setResponses(prev => [...prev, ...newResponses]); } }, [currentCategory, currentQuestions, responses]); const handleResponseChange = ( questionId: string, field: keyof QuestionnaireResponse, value: string ) => { setResponses(prev => prev.map(response => response.questionId === questionId ? { ...response, [field]: value } : response )); }; const getResponseForQuestion = (questionId: string): QuestionnaireResponse | undefined => { return responses.find(r => r.questionId === questionId); }; const getCategoryProgress = (category: BarrierCategory): number => { const categoryQuestions = barrierQuestions.filter(q => q.category === category); const categoryResponses = responses.filter(r => r.category === category); const answeredQuestions = categoryResponses.filter(r => r.response !== 'Not Applicable'); return categoryQuestions.length > 0 ? Math.round((answeredQuestions.length / categoryQuestions.length) * 100) : 0; }; const getOverallProgress = (): number => { const totalQuestions = barrierQuestions.length; const answeredQuestions = responses.filter(r => r.response !== 'Not Applicable').length; return totalQuestions > 0 ? Math.round((answeredQuestions / totalQuestions) * 100) : 0; }; const handleNextCategory = () => { if (!isLastCategory) { setCurrentCategory(categories[currentCategoryIndex + 1]); } }; const handlePreviousCategory = () => { if (currentCategoryIndex > 0) { setCurrentCategory(categories[currentCategoryIndex - 1]); } }; const handleSubmit = async () => { if (!department || !position) { alert('Please fill in your department and position'); return; } setIsSubmitting(true); const questionnaire: BarrierQuestionnaireType = { id: uuidv4(), respondentId: uuidv4(), respondentName, respondentEmail, respondentCellphone: '', // No longer required department, position, dateCompleted: new Date().toISOString(), responses, status: 'Submitted' }; try { await onSubmit(questionnaire); } finally { setIsSubmitting(false); } }; const handleSaveDraft = () => { if (!onSaveDraft) return; const questionnaire: BarrierQuestionnaireType = { id: uuidv4(), respondentId: uuidv4(), respondentName, respondentEmail, respondentCellphone: '', // No longer required department, position, dateCompleted: new Date().toISOString(), responses, status: 'Draft' }; onSaveDraft(questionnaire); }; return ( <div className="space-y-6"> {/* Progress Overview */} <Card title="Barrier Analysis Questionnaire"> <div className="space-y-4"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Overall Progress</h3> <span className="text-sm font-medium text-emerald-600"> {getOverallProgress()}% Complete </span> </div> <div className="w-full bg-gray-200 rounded-full h-2"> <div className="bg-emerald-600 h-2 rounded-full transition-all duration-300" style={{ width: `${getOverallProgress()}%` }} /> </div> {/* Respondent Information */} <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t"> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" id="department" value={department} onChange={(e) => setDepartment(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your department" /> </div> <div> <label htmlFor="position" className="block text-sm font-medium text-gray-700"> Position/Job Title * </label> <input type="text" id="position" value={position} onChange={(e) => setPosition(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your position" /> </div> </div> </div> </Card> {/* Category Navigation */} <Card title="Categories"> <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3"> {categories.map((category, index) => { const progress = getCategoryProgress(category); const isActive = category === currentCategory; return ( <button key={category} onClick={() => setCurrentCategory(category)} className={`p-3 rounded-lg border text-left transition-colors ${ isActive ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-gray-200 hover:border-gray-300' }`} > <div className="flex items-center justify-between mb-2"> <span className="text-xs font-medium"> {index + 1}. {category} </span> {progress === 100 && ( <CheckCircle className="h-4 w-4 text-green-500" /> )} </div> <div className="w-full bg-gray-200 rounded-full h-1"> <div className="bg-emerald-600 h-1 rounded-full transition-all duration-300" style={{ width: `${progress}%` }} /> </div> </button> ); })} </div> </Card> {/* Current Category Questions */} <Card title={`${currentCategoryIndex + 1}. ${currentCategory}`}> <div className="space-y-6"> {currentQuestions.map((question, index) => { const response = getResponseForQuestion(question.id); return ( <div key={question.id} className="border border-gray-200 rounded-lg p-4"> <div className="space-y-4"> <div> <h4 className="text-sm font-medium text-gray-900 mb-2"> {index + 1}. {question.question} {question.isRequired && <span className="text-red-500 ml-1">*</span>} </h4> {question.description && ( <p className="text-sm text-gray-600 mb-3">{question.description}</p> )} </div> <div className="grid grid-cols-2 md:grid-cols-4 gap-3"> {['Yes', 'No', 'Partially', 'Not Applicable'].map((option) => ( <label key={option} className="inline-flex items-center"> <input type="radio" name={`question_${question.id}`} value={option} checked={response?.response === option} onChange={(e) => handleResponseChange(question.id, 'response', e.target.value)} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">{option}</span> </label> ))} </div> {response?.response === 'No' || response?.response === 'Partially' ? ( <div className="space-y-3"> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Severity Level </label> <select value={response.severity || 'Medium'} onChange={(e) => handleResponseChange(question.id, 'severity', e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > <option value="Low">Low</option> <option value="Medium">Medium</option> <option value="High">High</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Comments (Optional) </label> <textarea value={response.comments || ''} onChange={(e) => handleResponseChange(question.id, 'comments', e.target.value)} rows={2} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Provide additional details about this barrier..." /> </div> </div> ) : null} </div> </div> ); })} </div> {/* Navigation */} <div className="flex justify-between items-center mt-6 pt-6 border-t"> <Button variant="outline" onClick={handlePreviousCategory} disabled={currentCategoryIndex === 0} > Previous </Button> <div className="flex space-x-3"> {onSaveDraft && ( <Button variant="outline" onClick={handleSaveDraft} icon={<FileText className="w-4 h-4" />} > Save Draft </Button> )} {isLastCategory ? ( <Button onClick={handleSubmit} isLoading={isSubmitting} icon={<Send className="w-4 h-4" />} disabled={!department || !position} > Submit Questionnaire </Button> ) : ( <Button onClick={handleNextCategory}> Next </Button> )} </div> </div> </Card> </div> ); }; export default BarrierQuestionnaire; import React from 'react'; import { BarChart, AlertTriangle, CheckCircle, TrendingUp, Download } from 'lucide-react'; import Card from '../common/Card'; import Button from '../common/Button'; import { AnalysisResult, BarrierCategory } from '../../types'; import { generateComplianceReport } from '../../utils/analysisEngine'; interface AnalysisResultsProps { analysis: AnalysisResult; onDownloadReport?: () => void; } const AnalysisResults: React.FC<AnalysisResultsProps> = ({ analysis, onDownloadReport }) => { const getRiskColor = (risk: string) => { switch (risk) { case 'High': return 'text-red-600 bg-red-100'; case 'Medium': return 'text-amber-600 bg-amber-100'; case 'Low': return 'text-green-600 bg-green-100'; default: return 'text-gray-600 bg-gray-100'; } }; const getScoreColor = (score: number) => { if (score >= 80) return 'text-green-600'; if (score >= 60) return 'text-amber-600'; return 'text-red-600'; }; const getScoreIcon = (score: number) => { if (score >= 80) return <CheckCircle className="h-5 w-5 text-green-500" />; if (score >= 60) return <AlertTriangle className="h-5 w-5 text-amber-500" />; return <AlertTriangle className="h-5 w-5 text-red-500" />; }; return ( <div className="space-y-6"> {/* Overall Score */} <Card title="Analysis Results"> <div className="grid grid-cols-1 md:grid-cols-3 gap-6"> <div className="text-center"> <div className="flex items-center justify-center mb-2"> {getScoreIcon(analysis.overallScore)} </div> <div className={`text-3xl font-bold ${getScoreColor(analysis.overallScore)}`}> {analysis.overallScore}% </div> <p className="text-sm text-gray-500">Overall Compliance Score</p> </div> <div className="text-center"> <div className="flex items-center justify-center mb-2"> <AlertTriangle className="h-5 w-5 text-amber-500" /> </div> <div className="text-3xl font-bold text-gray-900"> {analysis.identifiedBarriers.length} </div> <p className="text-sm text-gray-500">Barriers Identified</p> </div> <div className="text-center"> <div className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${getRiskColor(analysis.complianceRisk)}`}> {analysis.complianceRisk} Risk </div> <p className="text-sm text-gray-500 mt-2">Compliance Risk Level</p> </div> </div> <div className="mt-6 flex justify-end"> <Button onClick={onDownloadReport} icon={<Download className="w-4 h-4" />} variant="outline" > Download Report </Button> </div> </Card> {/* Category Scores */} <Card title="Category Breakdown"> <div className="space-y-4"> {Object.entries(analysis.categoryScores).map(([category, score]) => ( <div key={category} className="flex items-center justify-between"> <div className="flex-1"> <div className="flex items-center justify-between mb-1"> <span className="text-sm font-medium text-gray-900">{category}</span> <span className={`text-sm font-medium ${getScoreColor(score)}`}> {score}% </span> </div> <div className="w-full bg-gray-200 rounded-full h-2"> <div className={`h-2 rounded-full transition-all duration-300 ${ score >= 80 ? 'bg-green-500' : score >= 60 ? 'bg-amber-500' : 'bg-red-500' }`} style={{ width: `${score}%` }} /> </div> </div> </div> ))} </div> </Card> {/* Priority Actions */} {analysis.priorityActions.length > 0 && ( <Card title="Priority Actions Required"> <div className="space-y-3"> {analysis.priorityActions.map((action, index) => ( <div key={index} className="flex items-start"> <div className="flex-shrink-0 h-5 w-5 rounded-full bg-red-100 flex items-center justify-center mr-3 mt-0.5"> <span className="text-xs font-medium text-red-600">{index + 1}</span> </div> <p className="text-sm text-gray-700">{action}</p> </div> ))} </div> </Card> )} {/* Identified Barriers */} {analysis.identifiedBarriers.length > 0 && ( <Card title="Identified Barriers"> <div className="space-y-2"> {analysis.identifiedBarriers.map((barrier, index) => ( <div key={index} className="flex items-start"> <AlertTriangle className="h-4 w-4 text-amber-500 mr-2 mt-0.5 flex-shrink-0" /> <p className="text-sm text-gray-700">{barrier}</p> </div> ))} </div> </Card> )} {/* Recommendations */} <Card title="Recommendations"> <div className="space-y-4"> {analysis.recommendations.map((recommendation, index) => ( <div key={index} className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <TrendingUp className="h-5 w-5 text-blue-600 mr-3 mt-0.5 flex-shrink-0" /> <p className="text-sm text-blue-700">{recommendation}</p> </div> </div> ))} </div> </Card> {/* Compliance Summary */} <Card title="Compliance Summary"> <div className="bg-gray-50 rounded-lg p-4"> <pre className="text-xs text-gray-700 whitespace-pre-wrap font-mono"> {generateComplianceReport(analysis)} </pre> </div> </Card> </div> ); }; export default AnalysisResults; import React, { useState } from 'react'; import { BarChart3, Users, TrendingUp } from 'lucide-react'; import Card from '../common/Card'; import { EconomicActivePopulation } from '../../types'; import { economicActivePopulationData, getAllProvinces, getAllSectors } from '../../utils/economicActivePopulation'; const EconomicActivePopulationView: React.FC = () => { const [selectedProvince, setSelectedProvince] = useState<string>('All'); const [selectedSector, setSelectedSector] = useState<string>('All'); const provinces = ['All', ...getAllProvinces()]; const sectors = [{ code: 'All', name: 'All Sectors' }, ...getAllSectors()]; const filteredData = economicActivePopulationData.filter(data => { const provinceMatch = selectedProvince === 'All' || data.province === selectedProvince; const sectorMatch = selectedSector === 'All' || data.sectorCode === selectedSector; return provinceMatch && sectorMatch; }); const calculateTotals = (data: EconomicActivePopulation[]) => { return data.reduce((acc, curr) => ({ nationalData: { blackMale: acc.nationalData.blackMale + curr.nationalData.blackMale, blackFemale: acc.nationalData.blackFemale + curr.nationalData.blackFemale, colouredMale: acc.nationalData.colouredMale + curr.nationalData.colouredMale, colouredFemale: acc.nationalData.colouredFemale + curr.nationalData.colouredFemale, indianMale: acc.nationalData.indianMale + curr.nationalData.indianMale, indianFemale: acc.nationalData.indianFemale + curr.nationalData.indianFemale, whiteMale: acc.nationalData.whiteMale + curr.nationalData.whiteMale, whiteFemale: acc.nationalData.whiteFemale + curr.nationalData.whiteFemale, total: acc.nationalData.total + curr.nationalData.total }, provincialData: { blackMale: acc.provincialData.blackMale + curr.provincialData.blackMale, blackFemale: acc.provincialData.blackFemale + curr.provincialData.blackFemale, colouredMale: acc.provincialData.colouredMale + curr.provincialData.colouredMale, colouredFemale: acc.provincialData.colouredFemale + curr.provincialData.colouredFemale, indianMale: acc.provincialData.indianMale + curr.provincialData.indianMale, indianFemale: acc.provincialData.indianFemale + curr.provincialData.indianFemale, whiteMale: acc.provincialData.whiteMale + curr.provincialData.whiteMale, whiteFemale: acc.provincialData.whiteFemale + curr.provincialData.whiteFemale, total: acc.provincialData.total + curr.provincialData.total }, sectorData: { blackMale: acc.sectorData.blackMale + curr.sectorData.blackMale, blackFemale: acc.sectorData.blackFemale + curr.sectorData.blackFemale, colouredMale: acc.sectorData.colouredMale + curr.sectorData.colouredMale, colouredFemale: acc.sectorData.colouredFemale + curr.sectorData.colouredFemale, indianMale: acc.sectorData.indianMale + curr.sectorData.indianMale, indianFemale: acc.sectorData.indianFemale + curr.sectorData.indianFemale, whiteMale: acc.sectorData.whiteMale + curr.sectorData.whiteMale, whiteFemale: acc.sectorData.whiteFemale + curr.sectorData.whiteFemale, total: acc.sectorData.total + curr.sectorData.total } }), { nationalData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 }, provincialData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 }, sectorData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 } }); }; const totals = calculateTotals(filteredData); const formatNumber = (num: number) => num.toLocaleString(); const calculatePercentage = (value: number, total: number) => { return total > 0 ? ((value / total) * 100).toFixed(1) : '0.0'; }; return ( <div className="space-y-6"> {/* Filters */} <Card title="Economic Active Population Analysis"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6"> <div> <label htmlFor="province" className="block text-sm font-medium text-gray-700 mb-1"> Province </label> <select id="province" value={selectedProvince} onChange={(e) => setSelectedProvince(e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {provinces.map(province => ( <option key={province} value={province}>{province}</option> ))} </select> </div> <div> <label htmlFor="sector" className="block text-sm font-medium text-gray-700 mb-1"> Sector </label> <select id="sector" value={selectedSector} onChange={(e) => setSelectedSector(e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {sectors.map(sector => ( <option key={sector.code} value={sector.code}> {sector.code !== 'All' ? `${sector.code} - ${sector.name}` : sector.name} </option> ))} </select> </div> </div> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <Users className="h-5 w-5 text-blue-600 mr-3 mt-0.5" /> <div> <h3 className="text-sm font-medium text-blue-800">About Economic Active Population Data</h3> <p className="text-sm text-blue-700 mt-1"> This data is based on Statistics South Africa's Quarterly Labour Force Survey and represents the economically active population by race, gender, province, and economic sector. Use this data to set realistic employment equity targets based on labour market availability. </p> </div> </div> </div> </Card> {/* National Data */} <Card title="National Economic Active Population"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Demographic Group </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Count </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Percentage </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Black Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.blackMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.blackMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Black Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.blackFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.blackFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Coloured Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.colouredMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.colouredMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Coloured Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.colouredFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.colouredFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Indian Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.indianMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.indianMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Indian Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.indianFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.indianFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">White Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.whiteMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.whiteMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">White Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.whiteFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.whiteFemale, totals.nationalData.total)}% </td> </tr> <tr className="bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">Total</td> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 text-right"> {formatNumber(totals.nationalData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 text-right"> 100.0% </td> </tr> </tbody> </table> </div> </Card> {/* Provincial and Sector Comparison */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <Card title={`Provincial Data${selectedProvince !== 'All' ? ` - ${selectedProvince}` : ''}`}> <div className="space-y-3"> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Black (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.blackMale + totals.provincialData.blackFemale)} ({calculatePercentage(totals.provincialData.blackMale + totals.provincialData.blackFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Coloured (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.colouredMale + totals.provincialData.colouredFemale)} ({calculatePercentage(totals.provincialData.colouredMale + totals.provincialData.colouredFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Indian (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.indianMale + totals.provincialData.indianFemale)} ({calculatePercentage(totals.provincialData.indianMale + totals.provincialData.indianFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">White (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.whiteMale + totals.provincialData.whiteFemale)} ({calculatePercentage(totals.provincialData.whiteMale + totals.provincialData.whiteFemale, totals.provincialData.total)}%) </span> </div> <div className="pt-2 border-t border-gray-200"> <div className="flex justify-between items-center"> <span className="text-sm font-medium text-gray-900">Total Provincial</span> <span className="text-sm font-bold text-gray-900"> {formatNumber(totals.provincialData.total)} </span> </div> </div> </div> </Card> <Card title={`Sector Data${selectedSector !== 'All' ? ` - ${sectors.find(s => s.code === selectedSector)?.name}` : ''}`}> <div className="space-y-3"> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Black (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.blackMale + totals.sectorData.blackFemale)} ({calculatePercentage(totals.sectorData.blackMale + totals.sectorData.blackFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Coloured (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.colouredMale + totals.sectorData.colouredFemale)} ({calculatePercentage(totals.sectorData.colouredMale + totals.sectorData.colouredFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Indian (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.indianMale + totals.sectorData.indianFemale)} ({calculatePercentage(totals.sectorData.indianMale + totals.sectorData.indianFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">White (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.whiteMale + totals.sectorData.whiteFemale)} ({calculatePercentage(totals.sectorData.whiteMale + totals.sectorData.whiteFemale, totals.sectorData.total)}%) </span> </div> <div className="pt-2 border-t border-gray-200"> <div className="flex justify-between items-center"> <span className="text-sm font-medium text-gray-900">Total Sector</span> <span className="text-sm font-bold text-gray-900"> {formatNumber(totals.sectorData.total)} </span> </div> </div> </div> </Card> </div> {/* Detailed Breakdown */} {filteredData.length > 0 && ( <Card title="Detailed Breakdown by Location and Sector"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Province </th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Sector </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> National Total </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Provincial Total </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Sector Total </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {filteredData.map((data, index) => ( <tr key={index}> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {data.province} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {data.sectorCode} - {data.sectorName} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.nationalData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.provincialData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.sectorData.total)} </td> </tr> ))} </tbody> </table> </div> </Card> )} </div> ); }; export default EconomicActivePopulationView; import React, { useState } from 'react'; import { ClipboardList, Users, BarChart3, Download } from 'lucide-react'; import Button from '../components/common/Button'; import Card from '../components/common/Card'; import BarrierQuestionnaire from '../components/questionnaire/BarrierQuestionnaire'; import AnalysisResults from '../components/analysis/AnalysisResults'; import EconomicActivePopulationView from '../components/analysis/EconomicActivePopulationView'; import { BarrierQuestionnaire as BarrierQuestionnaireType, AnalysisResult } from '../types'; import { analyzeQuestionnaire, generateComplianceReport } from '../utils/analysisEngine'; const BarrierAnalysisPage: React.FC = () => { const [currentStep, setCurrentStep] = useState<'questionnaire' | 'results' | 'population'>('questionnaire'); const [respondentInfo, setRespondentInfo] = useState({ name: '', email: '', department: '', position: '' }); const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null); const [activeTab, setActiveTab] = useState<'questionnaire' | 'population'>('questionnaire'); const handleQuestionnaireSubmit = (questionnaire: BarrierQuestionnaireType) => { // Analyze the questionnaire const analysis = analyzeQuestionnaire(questionnaire); setAnalysisResult(analysis); setCurrentStep('results'); }; const handleDownloadReport = () => { if (!analysisResult) return; const report = generateComplianceReport(analysisResult); const blob = new Blob([report], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `barrier-analysis-report-${new Date().toISOString().split('T')[0]}.txt`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; const renderStepContent = () => { switch (currentStep) { case 'questionnaire': return ( <div className="max-w-4xl mx-auto"> <div className="text-center mb-8"> <ClipboardList className="mx-auto h-16 w-16 text-emerald-600 mb-4" /> <h1 className="text-3xl font-bold text-gray-900 mb-2"> Employment Equity Barrier Analysis </h1> <p className="text-lg text-gray-600"> Complete our comprehensive questionnaire to identify potential barriers to employment equity in your organization. </p> </div> <Card title="Get Started"> <div className="space-y-4 mb-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <label htmlFor="name" className="block text-sm font-medium text-gray-700"> Full Name * </label> <input type="text" id="name" value={respondentInfo.name} onChange={(e) => setRespondentInfo(prev => ({ ...prev, name: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your full name" /> </div> <div> <label htmlFor="email" className="block text-sm font-medium text-gray-700"> Email Address * </label> <input type="email" id="email" value={respondentInfo.email} onChange={(e) => setRespondentInfo(prev => ({ ...prev, email: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your email address" /> </div> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" id="department" value={respondentInfo.department} onChange={(e) => setRespondentInfo(prev => ({ ...prev, department: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your department" /> </div> <div> <label htmlFor="position" className="block text-sm font-medium text-gray-700"> Position/Job Title * </label> <input type="text" id="position" value={respondentInfo.position} onChange={(e) => setRespondentInfo(prev => ({ ...prev, position: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your position" /> </div> </div> {respondentInfo.name && respondentInfo.email && respondentInfo.department && respondentInfo.position && ( <div className="mt-6"> <Button onClick={() => { // Start the questionnaire directly setCurrentStep('questionnaire'); }} icon={<ClipboardList className="w-4 h-4" />} fullWidth > Start Barrier Analysis Questionnaire </Button> </div> )} </div> </Card> {respondentInfo.name && respondentInfo.email && respondentInfo.department && respondentInfo.position && ( <BarrierQuestionnaire respondentName={respondentInfo.name} respondentEmail={respondentInfo.email} respondentCellphone="" // No longer required onSubmit={handleQuestionnaireSubmit} /> )} </div> ); case 'results': return analysisResult ? ( <AnalysisResults analysis={analysisResult} onDownloadReport={handleDownloadReport} /> ) : null; default: return null; } }; if (currentStep === 'questionnaire' || currentStep === 'results') { return ( <div className="space-y-6"> {/* Navigation */} {currentStep !== 'questionnaire' && ( <div className="flex justify-between items-center"> <Button variant="outline" onClick={() => { if (currentStep === 'results') { setCurrentStep('questionnaire'); } }} > Back </Button> <div className="flex space-x-4"> <Button variant={activeTab === 'questionnaire' ? 'primary' : 'outline'} onClick={() => setActiveTab('questionnaire')} icon={<ClipboardList className="w-4 h-4" />} > Barrier Analysis </Button> <Button variant={activeTab === 'population' ? 'primary' : 'outline'} onClick={() => { setActiveTab('population'); setCurrentStep('population'); }} icon={<Users className="w-4 h-4" />} > Economic Active Population </Button> </div> </div> )} {renderStepContent()} </div> ); } return ( <div className="space-y-6"> {/* Page Header */} <div className="flex justify-between items-center"> <div> <h1 className="text-2xl font-bold text-gray-900">Employment Equity Analysis</h1> <p className="mt-1 text-sm text-gray-500"> Comprehensive barrier analysis and economic active population data </p> </div> <div className="flex space-x-4"> <Button variant={activeTab === 'questionnaire' ? 'primary' : 'outline'} onClick={() => { setActiveTab('questionnaire'); setCurrentStep('questionnaire'); }} icon={<ClipboardList className="w-4 h-4" />} > Barrier Analysis </Button> <Button variant={activeTab === 'population' ? 'primary' : 'outline'} onClick={() => setActiveTab('population')} icon={<Users className="w-4 h-4" />} > Economic Active Population </Button> </div> </div> {/* Content */} {activeTab === 'population' && <EconomicActivePopulationView />} </div> ); }; export default BarrierAnalysisPage; import React, { useEffect } from 'react'; import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { AppProvider, useAppContext } from './contexts/AppContext'; import Header from './components/layout/Header'; import DashboardPage from './pages/DashboardPage'; import EmployeesPage from './pages/EmployeesPage'; import ReportsPage from './pages/ReportsPage'; import GoalsPage from './pages/GoalsPage'; import LoginPage from './pages/LoginPage'; import BarrierAnalysisPage from './pages/BarrierAnalysisPage'; // Protected route component const ProtectedRoute: React.FC<{children: React.ReactNode}> = ({ children }) => { const { currentUser } = useAppContext(); const location = useLocation(); if (!currentUser) { // Redirect to login if not authenticated return <Navigate to="/login\" state={{ from: location }} replace />; } import React, { useState, useEffect } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { Menu, X, UserCircle, LogOut, ChevronDown } from 'lucide-react'; import { useAppContext } from '../../contexts/AppContext'; const Header: React.FC = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const [isUserMenuOpen, setIsUserMenuOpen] = useState(false); const [scrolled, setScrolled] = useState(false); const { currentUser, logout } = useAppContext(); const location = useLocation(); // Handle scroll effect for header useEffect(() => { const handleScroll = () => { if (window.scrollY > 10) { setScrolled(true); } else { setScrolled(false); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); // Close mobile menu when route changes useEffect(() => { setIsMenuOpen(false); }, [location]); return ( <header className={`fixed top-0 left-0 right-0 z-10 transition-all duration-300 ${ scrolled ? 'bg-white shadow-md py-2' : 'bg-transparent py-4' }`} > <div className="container mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex justify-between items-center"> {/* Logo */} <Link to="/" className="flex items-center"> <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-xl mr-2"> EE </div> <span className="text-xl font-bold text-gray-800">EquityTool</span> </Link> {/* Desktop Navigation */} <nav className="hidden md:flex space-x-8"> <NavLink to="/" active={location.pathname === '/'}>Dashboard</NavLink> <NavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</NavLink> <NavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</NavLink> <NavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</NavLink> <NavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</NavLink> </nav> {/* User Menu (Desktop) */} <div className="hidden md:flex items-center"> {currentUser ? ( <div className="relative"> <button className="flex items-center space-x-2 text-gray-700 hover:text-emerald-600 focus:outline-none" onClick={() => setIsUserMenuOpen(!isUserMenuOpen)} > <UserCircle className="w-6 h-6" /> <span>{currentUser.name}</span> <ChevronDown className={`w-4 h-4 transition-transform ${isUserMenuOpen ? 'rotate-180' : ''}`} /> </button> {isUserMenuOpen && ( <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20"> <div className="px-4 py-2 text-sm text-gray-500 border-b"> Logged in as <span className="font-semibold">{currentUser.role}</span> </div> <Link to="/profile" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" onClick={() => setIsUserMenuOpen(false)} > Profile Settings </Link> <button className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsUserMenuOpen(false); }} > <div className="flex items-center"> <LogOut className="w-4 h-4 mr-2" /> Sign Out </div> </button> </div> )} </div> ) : ( <Link to="/login" className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-emerald-600 hover:bg-emerald-700" > Sign In </Link> )} </div> {/* Mobile Menu Button */} <button className="md:hidden text-gray-700 focus:outline-none" onClick={() => setIsMenuOpen(!isMenuOpen)} > {isMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />} </button> </div> </div> {/* Mobile Menu */} {isMenuOpen && ( <div className="md:hidden bg-white border-t shadow-lg"> <div className="px-2 pt-2 pb-3 space-y-1"> <MobileNavLink to="/" active={location.pathname === '/'}>Dashboard</MobileNavLink> <MobileNavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</MobileNavLink> <MobileNavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</MobileNavLink> <MobileNavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</MobileNavLink> <MobileNavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</MobileNavLink> </div> {/* User Menu (Mobile) */} <div className="px-5 pt-4 pb-3 border-t border-gray-200"> {currentUser ? ( <> <div className="flex items-center mb-3"> <div className="flex-shrink-0"> <UserCircle className="w-10 h-10 text-gray-400" /> </div> <div className="ml-3"> <div className="text-base font-medium text-gray-800">{currentUser.name}</div> <div className="text-sm font-medium text-gray-500">{currentUser.email}</div> </div> </div> <div className="space-y-1"> <Link to="/profile" className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:bg-gray-100" > Profile Settings </Link> <button className="block w-full text-left px-3 py-2 rounded-md text-base font-medium text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsMenuOpen(false); }} > Sign Out </button> </div> </> ) : ( <Link to="/login" className="block w-full px-5 py-3 text-center font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-md" > Sign In </Link> )} </div> </div> )} </header> ); }; interface NavLinkProps { to: string; active: boolean; children: React.ReactNode; } const NavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`relative px-2 py-1 transition-colors ${ active ? 'text-emerald-600 font-medium' : 'text-gray-600 hover:text-emerald-600' }`} > {children} {active && ( <span className="absolute bottom-0 left-0 w-full h-0.5 bg-emerald-600 rounded-full"></span> )} </Link> ); }; const MobileNavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`block px-3 py-2 rounded-md text-base font-medium ${ active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-700 hover:bg-gray-50 hover:text-emerald-600' }`} > {children} </Link> ); }; export default Header; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { v4 as uuidv4 } from 'uuid'; // Mock Company Information - Updated for 2024 legislation export const mockCompanyInfo: CompanyInfo = { name: 'Exemplar Holdings', registrationNumber: '2010/123456/07', industry: 'Financial Services', sectorCode: 'K', address: '123 Main Street, Sandton, Johannesburg, 2196', province: 'Gauteng', contactPerson: 'Jane Smith', contactEmail: 'jane.smith@exemplar.co.za', contactPhone: '011 123 4567', employeeCount: 245, designatedEmployer: true, complianceOfficer: 'John Doe', complianceOfficerContact: 'john.doe@exemplar.co.za' }; // Mock Employees export const mockEmployees: Employee[] = [ { id: uuidv4(), firstName: 'Thabo', lastName: 'Mbeki', idNumber: '7501015800082', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Top Management', department: 'Executive', salary: 1200000, joinDate: '2020-01-15' }, { id: uuidv4(), firstName: 'Sarah', lastName: 'Johnson', idNumber: '8012045800082', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Senior Management', department: 'Finance', salary: 850000, joinDate: '2019-04-12' }, { id: uuidv4(), firstName: 'Lerato', lastName: 'Nkosi', idNumber: '8909235800083', race: 'Black', gender: 'Female', hasDisability: true, disabilityDetails: 'Hearing impairment', occupationalLevel: 'Professionally Qualified', department: 'Human Resources', salary: 620000, joinDate: '2018-06-01' }, { id: uuidv4(), firstName: 'Ahmed', lastName: 'Patel', idNumber: '7705125800084', race: 'Indian', gender: 'Male', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 450000, joinDate: '2021-03-15' }, { id: uuidv4(), firstName: 'Jessica', lastName: 'De Villiers', idNumber: '9012055800086', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Professionally Qualified', department: 'Marketing', salary: 580000, joinDate: '2019-11-01' }, { id: uuidv4(), firstName: 'Sipho', lastName: 'Ndlovu', idNumber: '8504175800087', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Semi-skilled', department: 'Operations', salary: 320000, joinDate: '2020-08-15' }, { id: uuidv4(), firstName: 'Fatima', lastName: 'Mohammed', idNumber: '9108235800088', race: 'Indian', gender: 'Female', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 470000, joinDate: '2019-05-20' }, { id: uuidv4(), firstName: 'James', lastName: 'Wilson', idNumber: '8306155800089', race: 'Coloured', gender: 'Male', hasDisability: true, disabilityDetails: 'Mobility impairment', occupationalLevel: 'Skilled Technical', department: 'Finance', salary: 420000, joinDate: '2018-10-10' } ]; // Mock Equity Goals export const mockEquityGoals: EquityGoal[] = [ { id: uuidv4(), occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 25, targetPercentage: 50, targetDate: '2025-12-31', notes: 'Focus on internal promotions and external recruitment' }, { id: uuidv4(), occupationalLevel: 'Senior Management', targetGroup: 'Female', currentPercentage: 30, targetPercentage: 45, targetDate: '2024-12-31', notes: 'Implement mentorship program to prepare for promotions' }, { id: uuidv4(), occupationalLevel: 'Professionally Qualified', targetGroup: 'People with Disabilities', currentPercentage: 2, targetPercentage: 7, targetDate: '2025-06-30', notes: 'Improve workplace accessibility and targeted recruitment' } ]; // Mock Demographic Summary export const mockDemographicSummary: DemographicSummary[] = [ { occupationalLevel: 'Top Management', maleBlack: 1, maleColoured: 0, maleIndian: 0, maleWhite: 3, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 1, femaleForeignNational: 0, disabledCount: 0, total: 5 }, { occupationalLevel: 'Senior Management', maleBlack: 2, maleColoured: 1, maleIndian: 1, maleWhite: 5, maleForeignNational: 1, femaleBlack: 1, femaleColoured: 1, femaleIndian: 0, femaleWhite: 3, femaleForeignNational: 0, disabledCount: 1, total: 15 }, { occupationalLevel: 'Professionally Qualified', maleBlack: 15, maleColoured: 6, maleIndian: 8, maleWhite: 12, maleForeignNational: 2, femaleBlack: 12, femaleColoured: 5, femaleIndian: 7, femaleWhite: 10, femaleForeignNational: 1, disabledCount: 4, total: 78 }, { occupationalLevel: 'Skilled Technical', maleBlack: 25, maleColoured: 8, maleIndian: 6, maleWhite: 10, maleForeignNational: 3, femaleBlack: 18, femaleColoured: 7, femaleIndian: 5, femaleWhite: 8, femaleForeignNational: 2, disabledCount: 5, total: 92 }, { occupationalLevel: 'Semi-skilled', maleBlack: 18, maleColoured: 5, maleIndian: 2, maleWhite: 3, maleForeignNational: 4, femaleBlack: 12, femaleColoured: 3, femaleIndian: 1, femaleWhite: 2, femaleForeignNational: 0, disabledCount: 2, total: 50 }, { occupationalLevel: 'Unskilled', maleBlack: 3, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 2, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: 5 } ]; // Mock Users - Updated with analyst role export const mockUsers: User[] = [ { id: uuidv4(), name: 'Admin User', email: 'admin@exemplar.co.za', cellphone: '+27821234567', role: 'admin', lastLogin: '2023-06-15T08:30:00Z', isVerified: true }, { id: uuidv4(), name: 'HR Manager', email: 'hr@exemplar.co.za', cellphone: '+27829876543', role: 'manager', lastLogin: '2023-06-14T11:45:00Z', isVerified: true }, { id: uuidv4(), name: 'Department Head', email: 'department@exemplar.co.za', cellphone: '+27835551234', role: 'viewer', lastLogin: '2023-06-10T09:15:00Z', isVerified: true }, { id: uuidv4(), name: 'Equity Analyst', email: 'analyst@exemplar.co.za', cellphone: '+27847778888', role: 'analyst', lastLogin: '2023-06-16T14:20:00Z', isVerified: true } ]; - Initial Deployment
- 85.8 kB <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>South African Employment Equity Tool</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html> import React, { useEffect } from 'react'; import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { AppProvider, useAppContext } from './contexts/AppContext'; import Header from './components/layout/Header'; import DashboardPage from './pages/DashboardPage'; import EmployeesPage from './pages/EmployeesPage'; import ReportsPage from './pages/ReportsPage'; import GoalsPage from './pages/GoalsPage'; import LoginPage from './pages/LoginPage'; import BarrierAnalysisPage from './pages/BarrierAnalysisPage'; // Protected route component const ProtectedRoute: React.FC<{children: React.ReactNode}> = ({ children }) => { const { currentUser } = useAppContext(); const location = useLocation(); if (!currentUser) { // Redirect to login if not authenticated return <Navigate to="/login\" state={{ from: location }} replace />; } import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAppContext } from '../contexts/AppContext'; import Button from '../components/common/Button'; import { LogIn, User, Lock } from 'lucide-react'; const LoginPage: React.FC = () => { const [email, setEmail] = useState('admin@exemplar.co.za'); const [password, setPassword] = useState('password'); const [error, setError] = useState(''); const [isLoading, setIsLoading] = useState(false); const { login } = useAppContext(); const navigate = useNavigate(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setError(''); setIsLoading(true); // Simulate API call setTimeout(() => { const success = login(email); if (success) { navigate('/'); } else { setError('Invalid email or password'); } setIsLoading(false); }, 1000); }; const handleDemoLogin = (role: string) => { setIsLoading(true); // Simulate API call setTimeout(() => { const success = login('demo@example.com', role); if (success) { navigate('/'); } else { setError('Demo login failed'); } setIsLoading(false); }, 1000); }; return ( <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8"> <div className="sm:mx-auto sm:w-full sm:max-w-md"> <div className="flex justify-center"> <div className="w-16 h-16 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-2xl"> EE </div> </div> <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900"> Employment Equity Tool </h2> <p className="mt-2 text-center text-sm text-gray-600"> Sign in to manage your organization's equity compliance </p> </div> <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md"> <div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10"> <form className="space-y-6" onSubmit={handleSubmit}> {error && ( <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative" role="alert"> <span className="block sm:inline">{error}</span> </div> )} <div> <label htmlFor="email" className="block text-sm font-medium text-gray-700"> Email address </label> <div className="mt-1 relative rounded-md shadow-sm"> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <User className="h-5 w-5 text-gray-400" /> </div> <input id="email" name="email" type="email" autoComplete="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="admin@exemplar.co.za" /> </div> </div> <div> <label htmlFor="password" className="block text-sm font-medium text-gray-700"> Password </label> <div className="mt-1 relative rounded-md shadow-sm"> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <Lock className="h-5 w-5 text-gray-400" /> </div> <input id="password" name="password" type="password" autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="••••••••" /> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <input id="remember_me" name="remember_me" type="checkbox" className="h-4 w-4 text-emerald-600 focus:ring-emerald-500 border-gray-300 rounded" /> <label htmlFor="remember_me" className="ml-2 block text-sm text-gray-900"> Remember me </label> </div> <div className="text-sm"> <a href="#" className="font-medium text-emerald-600 hover:text-emerald-500"> Forgot your password? </a> </div> </div> <div> <Button type="submit" fullWidth isLoading={isLoading} icon={<LogIn className="w-4 h-4" />} > Sign in </Button> </div> </form> <div className="mt-6"> <div className="relative"> <div className="absolute inset-0 flex items-center"> <div className="w-full border-t border-gray-300"></div> </div> <div className="relative flex justify-center text-sm"> <span className="px-2 bg-white text-gray-500">Or continue with demo access</span> </div> </div> <div className="mt-6 grid grid-cols-3 gap-3"> <Button variant="outline" onClick={() => handleDemoLogin('admin')} disabled={isLoading} > Admin </Button> <Button variant="outline" onClick={() => handleDemoLogin('manager')} disabled={isLoading} > Manager </Button> <Button variant="outline" onClick={() => handleDemoLogin('viewer')} disabled={isLoading} > Viewer </Button> </div> </div> </div> </div> </div> ); }; export default LoginPage; import React, { useState } from 'react'; import { PlusCircle, BarChart3 } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import GoalForm from '../components/goals/GoalForm'; import { EquityGoal } from '../types'; import { calculateGoalProgress } from '../utils/calculations'; import { format } from 'date-fns'; import { v4 as uuidv4 } from 'uuid'; const GoalsPage: React.FC = () => { const { equityGoals, addEquityGoal, updateEquityGoal, deleteEquityGoal } = useAppContext(); const [showAddForm, setShowAddForm] = useState(false); const [showEditForm, setShowEditForm] = useState(false); const [currentGoal, setCurrentGoal] = useState<EquityGoal | undefined>(undefined); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [goalToDelete, setGoalToDelete] = useState<string>(''); // Handle add goal const handleAddGoal = (goal: EquityGoal) => { addEquityGoal({ ...goal, id: uuidv4() }); setShowAddForm(false); }; // Handle edit goal const handleEditGoal = (goal: EquityGoal) => { setCurrentGoal(goal); setShowEditForm(true); }; // Handle update goal const handleUpdateGoal = (goal: EquityGoal) => { updateEquityGoal(goal); setShowEditForm(false); setCurrentGoal(undefined); }; // Handle delete goal const handleDeleteConfirm = (id: string) => { setGoalToDelete(id); setShowDeleteConfirm(true); }; const confirmDelete = () => { deleteEquityGoal(goalToDelete); setShowDeleteConfirm(false); setGoalToDelete(''); }; // Group goals by occupational level const groupedGoals: Record<string, EquityGoal[]> = {}; equityGoals.forEach(goal => { if (!groupedGoals[goal.occupationalLevel]) { groupedGoals[goal.occupationalLevel] = []; } groupedGoals[goal.occupationalLevel].push(goal); }); return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Equity Goals</h1> <p className="mt-1 text-sm text-gray-500"> Set and track your organization's employment equity goals </p> </div> <div className="mt-4 sm:mt-0"> <Button icon={<PlusCircle className="w-4 h-4" />} onClick={() => setShowAddForm(true)} > Add Goal </Button> </div> </div> {/* Add/Edit Goal Form */} {showAddForm && ( <GoalForm onSubmit={handleAddGoal} onCancel={() => setShowAddForm(false)} /> )} {showEditForm && currentGoal && ( <GoalForm goal={currentGoal} onSubmit={handleUpdateGoal} onCancel={() => { setShowEditForm(false); setCurrentGoal(undefined); }} /> )} {/* Delete Confirmation Modal */} {showDeleteConfirm && ( <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center"> <div className="relative mx-auto p-5 border w-96 shadow-lg rounded-md bg-white"> <div className="mt-3 text-center"> <h3 className="text-lg leading-6 font-medium text-gray-900">Confirm Deletion</h3> <div className="mt-2 px-7 py-3"> <p className="text-sm text-gray-500"> Are you sure you want to delete this equity goal? This action cannot be undone. </p> </div> <div className="flex justify-end mt-4 gap-3"> <Button variant="outline" onClick={() => setShowDeleteConfirm(false)} > Cancel </Button> <Button variant="danger" onClick={confirmDelete} > Delete </Button> </div> </div> </div> </div> )} {/* Goals Overview */} <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"> <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Goals Overview</h3> <div className="flex items-center"> <BarChart3 className="h-5 w-5 text-gray-400 mr-2" /> <span className="text-sm text-gray-500">{equityGoals.length} Active Goals</span> </div> </div> {/* Info card if no goals */} {equityGoals.length === 0 ? ( <div className="p-6"> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">No Equity Goals Set</h3> <div className="mt-2 text-sm text-blue-700"> <p> Set equity goals to track your organization's progress towards achieving a more diverse and representative workforce in accordance with the Employment Equity Act. Goals can be set for different occupational levels and demographic groups. </p> <p className="mt-2"> <Button size="sm" onClick={() => setShowAddForm(true)} > Set Your First Goal </Button> </p> </div> </div> </div> </div> </div> ) : ( <div className="divide-y divide-gray-200"> {Object.entries(groupedGoals).map(([level, goals]) => ( <div key={level} className="p-6"> <h4 className="text-md font-medium text-gray-900 mb-4">{level}</h4> <div className="space-y-6"> {goals.map(goal => { const progress = calculateGoalProgress(goal.targetPercentage, goal.currentPercentage); return ( <div key={goal.id} className="bg-gray-50 p-4 rounded-lg border border-gray-200"> <div className="flex justify-between items-start mb-4"> <div> <h5 className="font-medium text-gray-900"> {goal.targetGroup} </h5> <p className="text-sm text-gray-500 mt-1"> Target: {goal.targetPercentage}% by {format(new Date(goal.targetDate), 'MMM d, yyyy')} </p> </div> <div className="flex space-x-2"> <Button variant="text" size="sm" onClick={() => handleEditGoal(goal)} > Edit </Button> <Button variant="text" size="sm" onClick={() => handleDeleteConfirm(goal.id)} > Delete </Button> </div> </div> {/* Progress bar */} <div className="w-full bg-gray-200 rounded-full h-2.5"> <div className={`h-2.5 rounded-full ${getProgressColorClass(progress)}`} style={{ width: `${progress}%` }} ></div> </div> {/* Progress details */} <div className="flex justify-between items-center mt-2"> <div className="flex items-center"> <span className={`text-sm ${getProgressTextColorClass(progress)}`}> {progress}% Complete </span> <span className="mx-2 text-gray-300">•</span> <span className="text-sm text-gray-500"> Current: {goal.currentPercentage}% </span> </div> <div className="text-sm text-gray-500"> {getDaysDifference(new Date(), new Date(goal.targetDate))} days remaining </div> </div> {/* Notes */} {goal.notes && ( <div className="mt-3 text-sm text-gray-600 bg-white p-2 rounded border border-gray-100"> <p>{goal.notes}</p> </div> )} </div> ); })} </div> </div> ))} </div> )} </div> {/* Goal Setting Guide */} <Card title="Employment Equity Goal Setting Guide"> <div className="space-y-4"> <p className="text-sm text-gray-600"> The Employment Equity Act requires designated employers to implement affirmative action measures to achieve employment equity in the workplace. Setting clear goals is an essential part of this process. </p> <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4"> <div className="bg-emerald-50 p-4 rounded-lg border border-emerald-100"> <h4 className="font-medium text-emerald-800 mb-2">Best Practices</h4> <ul className="text-sm text-emerald-700 space-y-2"> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Set realistic and achievable targets based on labor market availability </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Focus on both recruitment and promotion strategies </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Consider both short-term and long-term goals </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-emerald-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-emerald-600">✓</span> Track progress regularly and adjust strategies as needed </li> </ul> </div> <div className="bg-amber-50 p-4 rounded-lg border border-amber-100"> <h4 className="font-medium text-amber-800 mb-2">Compliance Requirements</h4> <ul className="text-sm text-amber-700 space-y-2"> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Goals must be specific, measurable, achievable, relevant, and time-bound </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Numerical targets must be included in your Employment Equity Plan </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Progress must be reported annually to the Department of Employment and Labour </li> <li className="flex items-start"> <span className="inline-block h-5 w-5 rounded-full bg-amber-200 flex-shrink-0 mr-2 flex items-center justify-center text-xs text-amber-600">!</span> Goals should address all designated groups under the Act </li> </ul> </div> </div> </div> </Card> </div> ); }; // Helper functions const getProgressColorClass = (progress: number): string => { if (progress < 25) return 'bg-red-600'; if (progress < 50) return 'bg-amber-500'; if (progress < 75) return 'bg-blue-500'; return 'bg-emerald-600'; }; const getProgressTextColorClass = (progress: number): string => { if (progress < 25) return 'text-red-600 font-medium'; if (progress < 50) return 'text-amber-500 font-medium'; if (progress < 75) return 'text-blue-600 font-medium'; return 'text-emerald-600 font-medium'; }; const getDaysDifference = (startDate: Date, endDate: Date): number => { const diffTime = endDate.getTime() - startDate.getTime(); return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); }; export default GoalsPage; import React from 'react'; import { useAppContext } from '../contexts/AppContext'; import ReportGenerator from '../components/reports/ReportGenerator'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import { FileText, Download, Calendar } from 'lucide-react'; import { format } from 'date-fns'; const ReportsPage: React.FC = () => { const { employees, companyInfo, demographicSummary } = useAppContext(); // Mock saved reports data const savedReports = [ { id: '1', name: 'EEA2 Report - Jan 2024', type: 'EEA2', date: '2024-01-15', size: '1.2 MB' }, { id: '2', name: 'EEA4 Report - Jan 2024', type: 'EEA4', date: '2024-01-15', size: '956 KB' }, { id: '3', name: 'Quarterly Progress Report - Q4 2023', type: 'Internal', date: '2023-12-31', size: '2.1 MB' } ]; return ( <div className="space-y-6"> {/* Page header */} <div> <h1 className="text-2xl font-bold text-gray-900">Reports</h1> <p className="mt-1 text-sm text-gray-500"> Generate and manage employment equity reports </p> </div> {/* Report Generator */} <ReportGenerator employees={employees} companyInfo={companyInfo} demographicSummary={demographicSummary} /> {/* Saved Reports */} <Card title="Saved Reports"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Report Name </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Type </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Date Generated </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> File Size </th> <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Actions </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {savedReports.map((report) => ( <tr key={report.id} className="hover:bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center"> <FileText className="flex-shrink-0 h-5 w-5 text-gray-400" /> <div className="ml-3"> <div className="text-sm font-medium text-gray-900"> {report.name} </div> </div> </div> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${ report.type === 'EEA2' ? 'bg-blue-100 text-blue-800' : report.type === 'EEA4' ? 'bg-emerald-100 text-emerald-800' : 'bg-gray-100 text-gray-800' }`}> {report.type} </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {format(new Date(report.date), 'dd MMM yyyy')} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {report.size} </td> <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> <Button variant="text" size="sm" icon={<Download className="w-4 h-4" />} > Download </Button> </td> </tr> ))} </tbody> </table> </div> </Card> {/* Reporting Calendar */} <Card title="Reporting Calendar"> <div className="space-y-4"> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="flex-shrink-0"> <Calendar className="h-5 w-5 text-blue-600" /> </div> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">Important Compliance Dates</h3> <div className="mt-2 text-sm text-blue-700"> <p> South African employers designated under the Employment Equity Act must submit their reports annually by the first working day of October, or by 15 January for online submissions. </p> </div> </div> </div> </div> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Report Type </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Due Date </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Submission Method </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Status </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA2 Report</div> <div className="text-xs text-gray-500">Workforce Profile</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2025 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800"> Upcoming </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA4 Report</div> <div className="text-xs text-gray-500">Income Differentials</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2025 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800"> Upcoming </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA2 Report</div> <div className="text-xs text-gray-500">Workforce Profile</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2024 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Submitted </span> </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm font-medium text-gray-900">EEA4 Report</div> <div className="text-xs text-gray-500">Income Differentials</div> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 15 January 2024 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> Online (EE System) </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> Submitted </span> </td> </tr> </tbody> </table> </div> </div> </Card> </div> ); }; export default ReportsPage; import React, { useState } from 'react'; import { PlusCircle, Upload, Download } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import EmployeeTable from '../components/employees/EmployeeTable'; import EmployeeForm from '../components/employees/EmployeeForm'; import Button from '../components/common/Button'; import Card from '../components/common/Card'; import { Employee } from '../types'; import { v4 as uuidv4 } from 'uuid'; const EmployeesPage: React.FC = () => { const { employees, addEmployee, updateEmployee, deleteEmployee } = useAppContext(); const [showAddForm, setShowAddForm] = useState(false); const [showEditForm, setShowEditForm] = useState(false); const [showViewDetails, setShowViewDetails] = useState(false); const [currentEmployee, setCurrentEmployee] = useState<Employee | undefined>(undefined); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [employeeToDelete, setEmployeeToDelete] = useState<string>(''); // Handle add employee const handleAddEmployee = (employee: Employee) => { addEmployee({ ...employee, id: uuidv4() }); setShowAddForm(false); }; // Handle edit employee const handleEditEmployee = (employee: Employee) => { setCurrentEmployee(employee); setShowEditForm(true); setShowViewDetails(false); }; // Handle update employee const handleUpdateEmployee = (employee: Employee) => { updateEmployee(employee); setShowEditForm(false); setCurrentEmployee(undefined); }; // Handle view employee const handleViewEmployee = (employee: Employee) => { setCurrentEmployee(employee); setShowViewDetails(true); setShowEditForm(false); }; // Handle delete employee const handleDeleteConfirm = (id: string) => { setEmployeeToDelete(id); setShowDeleteConfirm(true); }; const confirmDelete = () => { deleteEmployee(employeeToDelete); setShowDeleteConfirm(false); setEmployeeToDelete(''); }; return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Employees</h1> <p className="mt-1 text-sm text-gray-500"> Manage your organization's employee database </p> </div> <div className="mt-4 sm:mt-0 flex flex-wrap gap-2"> <Button variant="outline" size="sm" icon={<Upload className="w-4 h-4" />} > Import </Button> <Button variant="outline" size="sm" icon={<Download className="w-4 h-4" />} > Export </Button> <Button icon={<PlusCircle className="w-4 h-4" />} onClick={() => setShowAddForm(true)} > Add Employee </Button> </div> </div> {/* Add/Edit Employee Form */} {showAddForm && ( <EmployeeForm onSubmit={handleAddEmployee} onCancel={() => setShowAddForm(false)} /> )} {showEditForm && currentEmployee && ( <EmployeeForm employee={currentEmployee} onSubmit={handleUpdateEmployee} onCancel={() => { setShowEditForm(false); setCurrentEmployee(undefined); }} /> )} {/* Employee Details View */} {showViewDetails && currentEmployee && ( <Card title="Employee Details" footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={() => { setShowViewDetails(false); setCurrentEmployee(undefined); }} > Close </Button> <Button onClick={() => { setShowViewDetails(false); handleEditEmployee(currentEmployee); }} > Edit Employee </Button> </div> } > <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <h3 className="text-lg font-medium text-gray-900 mb-4">Personal Information</h3> <div className="space-y-3"> <div> <h4 className="text-sm font-medium text-gray-500">Full Name</h4> <p className="mt-1">{currentEmployee.firstName} {currentEmployee.lastName}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">ID Number</h4> <p className="mt-1">{currentEmployee.idNumber}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Race</h4> <p className="mt-1">{currentEmployee.race}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Gender</h4> <p className="mt-1">{currentEmployee.gender}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Disability Status</h4> <p className="mt-1"> {currentEmployee.hasDisability ? 'Yes' : 'No'} {currentEmployee.hasDisability && currentEmployee.disabilityDetails && ` - ${currentEmployee.disabilityDetails}`} </p> </div> </div> </div> <div> <h3 className="text-lg font-medium text-gray-900 mb-4">Employment Information</h3> <div className="space-y-3"> <div> <h4 className="text-sm font-medium text-gray-500">Occupational Level</h4> <p className="mt-1">{currentEmployee.occupationalLevel}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Department</h4> <p className="mt-1">{currentEmployee.department}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Annual Salary</h4> <p className="mt-1">R {currentEmployee.salary.toLocaleString()}</p> </div> <div> <h4 className="text-sm font-medium text-gray-500">Join Date</h4> <p className="mt-1">{new Date(currentEmployee.joinDate).toLocaleDateString()}</p> </div> {currentEmployee.terminationDate && ( <div> <h4 className="text-sm font-medium text-gray-500">Termination Date</h4> <p className="mt-1">{new Date(currentEmployee.terminationDate).toLocaleDateString()}</p> </div> )} </div> </div> </div> </Card> )} {/* Delete Confirmation Modal */} {showDeleteConfirm && ( <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex items-center justify-center"> <div className="relative mx-auto p-5 border w-96 shadow-lg rounded-md bg-white"> <div className="mt-3 text-center"> <h3 className="text-lg leading-6 font-medium text-gray-900">Confirm Deletion</h3> <div className="mt-2 px-7 py-3"> <p className="text-sm text-gray-500"> Are you sure you want to delete this employee? This action cannot be undone. </p> </div> <div className="flex justify-end mt-4 gap-3"> <Button variant="outline" onClick={() => setShowDeleteConfirm(false)} > Cancel </Button> <Button variant="danger" onClick={confirmDelete} > Delete </Button> </div> </div> </div> </div> )} {/* Employee Table */} <EmployeeTable employees={employees} onEdit={handleEditEmployee} onDelete={handleDeleteConfirm} onView={handleViewEmployee} /> </div> ); }; export default EmployeesPage; import React, { useState } from 'react'; import { Users, BarChart2, FileText, Target, CalendarClock } from 'lucide-react'; import { useAppContext } from '../contexts/AppContext'; import StatCard from '../components/dashboard/StatCard'; import DemographicChart from '../components/dashboard/DemographicChart'; import GoalTracker from '../components/dashboard/GoalTracker'; import Card from '../components/common/Card'; import Button from '../components/common/Button'; import { format } from 'date-fns'; const DashboardPage: React.FC = () => { const { employees, equityGoals, demographicSummary, companyInfo } = useAppContext(); const [selectedDepartment, setSelectedDepartment] = useState<string>('All Departments'); // Get unique departments const departments = ['All Departments', ...Array.from(new Set(employees.map(emp => emp.department)))]; // Filter employees by department const filteredEmployees = selectedDepartment === 'All Departments' ? employees : employees.filter(emp => emp.department === selectedDepartment); // Calculate quick stats const totalEmployees = filteredEmployees.length; const disabledCount = filteredEmployees.filter(emp => emp.hasDisability).length; const disabledPercentage = totalEmployees > 0 ? Math.round((disabledCount / totalEmployees) * 100) : 0; const blackEmployees = filteredEmployees.filter(emp => emp.race === 'Black').length; const blackPercentage = totalEmployees > 0 ? Math.round((blackEmployees / totalEmployees) * 100) : 0; const femaleEmployees = filteredEmployees.filter(emp => emp.gender === 'Female').length; const femalePercentage = totalEmployees > 0 ? Math.round((femaleEmployees / totalEmployees) * 100) : 0; return ( <div className="space-y-6"> {/* Page header */} <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between"> <div> <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1> <p className="mt-1 text-sm text-gray-500"> Overview of your organization's employment equity status </p> </div> <div className="mt-4 sm:mt-0"> <select value={selectedDepartment} onChange={(e) => setSelectedDepartment(e.target.value)} className="block w-full rounded-md border border-gray-300 py-2 pl-3 pr-10 text-base focus:border-emerald-500 focus:outline-none focus:ring-emerald-500 sm:text-sm" > {departments.map(dept => ( <option key={dept} value={dept}>{dept}</option> ))} </select> </div> </div> {/* Stats cards */} <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6"> <StatCard title="Total Employees" value={totalEmployees} icon={<Users className="w-5 h-5" />} color="emerald" /> <StatCard title="Black Representation" value={`${blackPercentage}%`} change={{ value: 2.5, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="blue" /> <StatCard title="Female Representation" value={`${femalePercentage}%`} change={{ value: 1.2, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="violet" /> <StatCard title="People with Disabilities" value={`${disabledPercentage}%`} change={{ value: 0.5, isPositive: true }} icon={<BarChart2 className="w-5 h-5" />} color="amber" /> </div> {/* Charts grid */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <DemographicChart employees={filteredEmployees} chartType="race" title="Race Distribution" /> <DemographicChart employees={filteredEmployees} chartType="gender" title="Gender Distribution" /> </div> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <DemographicChart employees={filteredEmployees} chartType="occupational" title="Occupational Levels" /> <GoalTracker goals={equityGoals} /> </div> {/* Upcoming deadlines */} <Card title="Upcoming Compliance Deadlines"> <div className="space-y-4"> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center"> <FileText className="h-5 w-5 text-amber-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">EEA2 Report Submission</h3> <p className="text-sm text-gray-500">Department of Employment and Labour</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800"> 15 Jan 2025 </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(2025, 0, 15).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center"> <Target className="h-5 w-5 text-blue-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">Equity Plan Review</h3> <p className="text-sm text-gray-500">Internal Milestone</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"> 30 Sep 2024 </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(2024, 8, 30).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> <div className="flex items-center justify-between"> <div className="flex items-center"> <div className="flex-shrink-0 h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center"> <CalendarClock className="h-5 w-5 text-emerald-600" /> </div> <div className="ml-4"> <h3 className="text-sm font-medium text-gray-900">Quarterly Progress Review</h3> <p className="text-sm text-gray-500">Management Meeting</p> </div> </div> <div className="flex items-center"> <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800"> {format(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15), 'dd MMM yyyy')} </span> <span className="ml-2 text-sm text-gray-500"> (in {Math.ceil((new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))} days) </span> </div> </div> </div> <div className="mt-6 flex justify-end"> <Button variant="outline" size="sm" icon={<CalendarClock className="w-4 h-4" />}> View Full Calendar </Button> </div> </Card> {/* Company info */} <Card title="Company Information"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <h3 className="text-sm font-medium text-gray-500 mb-2">Company Details</h3> <p className="text-sm"><span className="font-medium">Name:</span> {companyInfo.name}</p> <p className="text-sm"><span className="font-medium">Registration Number:</span> {companyInfo.registrationNumber}</p> <p className="text-sm"><span className="font-medium">Industry:</span> {companyInfo.industry}</p> <p className="text-sm"><span className="font-medium">Address:</span> {companyInfo.address}</p> </div> <div> <h3 className="text-sm font-medium text-gray-500 mb-2">Contact Information</h3> <p className="text-sm"><span className="font-medium">Contact Person:</span> {companyInfo.contactPerson}</p> <p className="text-sm"><span className="font-medium">Email:</span> {companyInfo.contactEmail}</p> <p className="text-sm"><span className="font-medium">Phone:</span> {companyInfo.contactPhone}</p> </div> </div> <div className="mt-6 flex justify-end"> <Button variant="outline" size="sm"> Edit Company Information </Button> </div> </Card> </div> ); }; export default DashboardPage; import React, { useState, useEffect } from 'react'; import { EquityGoal, OccupationalLevel } from '../../types'; import { v4 as uuidv4 } from 'uuid'; import Card from '../common/Card'; import Button from '../common/Button'; import { Calendar, BarChart3, X } from 'lucide-react'; interface GoalFormProps { goal?: EquityGoal; onSubmit: (goal: EquityGoal) => void; onCancel: () => void; } const GoalForm: React.FC<GoalFormProps> = ({ goal, onSubmit, onCancel }) => { const [formData, setFormData] = useState<EquityGoal>({ id: '', occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 0, targetPercentage: 0, targetDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0], notes: '' }); const [errors, setErrors] = useState<Partial<Record<keyof EquityGoal, string>>>({}); const [isSubmitting, setIsSubmitting] = useState(false); // Initialize form with goal data if editing useEffect(() => { if (goal) { setFormData({ ...goal, targetDate: goal.targetDate.split('T')[0] }); } else { // Generate a new ID for new goals setFormData(prev => ({ ...prev, id: uuidv4() })); } }, [goal]); const handleChange = ( e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement> ) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when field is changed if (errors[name as keyof EquityGoal]) { setErrors(prev => ({ ...prev, [name]: '' })); } }; const validateForm = (): boolean => { const newErrors: Partial<Record<keyof EquityGoal, string>> = {}; // Validate percentages if (formData.currentPercentage < 0 || formData.currentPercentage > 100) { newErrors.currentPercentage = 'Current percentage must be between 0 and 100'; } if (formData.targetPercentage <= 0 || formData.targetPercentage > 100) { newErrors.targetPercentage = 'Target percentage must be between 1 and 100'; } // Validate target date (must be in the future) const today = new Date(); today.setHours(0, 0, 0, 0); const targetDate = new Date(formData.targetDate); if (targetDate <= today) { newErrors.targetDate = 'Target date must be in the future'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (validateForm()) { setIsSubmitting(true); // Convert string values to numbers const submittedGoal: EquityGoal = { ...formData, currentPercentage: Number(formData.currentPercentage), targetPercentage: Number(formData.targetPercentage) }; // Submit the form data onSubmit(submittedGoal); setIsSubmitting(false); } }; const occupationalLevels: OccupationalLevel[] = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const targetGroups = [ 'Black', 'Coloured', 'Indian', 'White', 'Female', 'Male', 'People with Disabilities' ]; return ( <Card title={goal ? 'Edit Equity Goal' : 'Add New Equity Goal'} footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={onCancel} disabled={isSubmitting} > Cancel </Button> <Button type="submit" form="goal-form" isLoading={isSubmitting} icon={<BarChart3 className="w-4 h-4" />} > {goal ? 'Update Goal' : 'Add Goal'} </Button> </div> } > <form id="goal-form" onSubmit={handleSubmit} className="space-y-6"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Goal Details</h3> <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={onCancel} > Close </Button> </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="occupationalLevel" className="block text-sm font-medium text-gray-700"> Occupational Level * </label> <select name="occupationalLevel" id="occupationalLevel" value={formData.occupationalLevel} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {occupationalLevels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label htmlFor="targetGroup" className="block text-sm font-medium text-gray-700"> Target Group * </label> <select name="targetGroup" id="targetGroup" value={formData.targetGroup} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {targetGroups.map(group => ( <option key={group} value={group}>{group}</option> ))} </select> </div> <div> <label htmlFor="currentPercentage" className="block text-sm font-medium text-gray-700"> Current Percentage * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="number" name="currentPercentage" id="currentPercentage" min="0" max="100" step="0.1" value={formData.currentPercentage} onChange={handleChange} className={`block w-full rounded-md ${ errors.currentPercentage ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-12`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <span className="text-gray-500 sm:text-sm">%</span> </div> </div> {errors.currentPercentage && ( <p className="mt-1 text-sm text-red-600">{errors.currentPercentage}</p> )} </div> <div> <label htmlFor="targetPercentage" className="block text-sm font-medium text-gray-700"> Target Percentage * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="number" name="targetPercentage" id="targetPercentage" min="1" max="100" step="0.1" value={formData.targetPercentage} onChange={handleChange} className={`block w-full rounded-md ${ errors.targetPercentage ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-12`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <span className="text-gray-500 sm:text-sm">%</span> </div> </div> {errors.targetPercentage && ( <p className="mt-1 text-sm text-red-600">{errors.targetPercentage}</p> )} </div> <div> <label htmlFor="targetDate" className="block text-sm font-medium text-gray-700"> Target Date * </label> <div className="mt-1 relative rounded-md shadow-sm"> <input type="date" name="targetDate" id="targetDate" value={formData.targetDate} onChange={handleChange} className={`block w-full rounded-md ${ errors.targetDate ? 'border-red-300' : 'border-gray-300' } focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm pr-10`} /> <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none"> <Calendar className="h-4 w-4 text-gray-400" /> </div> </div> {errors.targetDate && ( <p className="mt-1 text-sm text-red-600">{errors.targetDate}</p> )} </div> <div className="md:col-span-2"> <label htmlFor="notes" className="block text-sm font-medium text-gray-700"> Notes </label> <textarea name="notes" id="notes" rows={3} placeholder="Add any additional information or strategies to achieve this goal..." value={formData.notes || ''} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> </form> </Card> ); }; export default GoalForm; import React, { useState } from 'react'; import { format } from 'date-fns'; import Card from '../common/Card'; import Button from '../common/Button'; import { Download, FileText, Table, Clipboard } from 'lucide-react'; import { Employee, CompanyInfo, DemographicSummary } from '../../types'; interface ReportGeneratorProps { employees: Employee[]; companyInfo: CompanyInfo; demographicSummary: DemographicSummary[]; } const ReportGenerator: React.FC<ReportGeneratorProps> = ({ employees, companyInfo, demographicSummary }) => { const [reportType, setReportType] = useState<'EEA2' | 'EEA4'>('EEA2'); const [reportPeriod, setReportPeriod] = useState<string>(format(new Date(), 'yyyy-MM')); const [isGenerating, setIsGenerating] = useState(false); const [reportGenerated, setReportGenerated] = useState(false); const handleGenerateReport = () => { setIsGenerating(true); // Simulate report generation with a timeout setTimeout(() => { setIsGenerating(false); setReportGenerated(true); }, 1500); }; return ( <div className="space-y-6"> <Card title="Generate Employment Equity Report"> <div className="space-y-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Report Type </label> <div className="flex space-x-4"> <label className="inline-flex items-center"> <input type="radio" name="reportType" value="EEA2" checked={reportType === 'EEA2'} onChange={() => setReportType('EEA2')} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">EEA2 (Workforce Profile)</span> </label> <label className="inline-flex items-center"> <input type="radio" name="reportType" value="EEA4" checked={reportType === 'EEA4'} onChange={() => setReportType('EEA4')} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">EEA4 (Income Differentials)</span> </label> </div> </div> <div> <label htmlFor="reportPeriod" className="block text-sm font-medium text-gray-700 mb-1"> Reporting Period </label> <input type="month" id="reportPeriod" value={reportPeriod} onChange={(e) => setReportPeriod(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <div className="flex-shrink-0"> <FileText className="h-5 w-5 text-blue-600" /> </div> <div className="ml-3"> <h3 className="text-sm font-medium text-blue-800">Report Information</h3> <div className="mt-2 text-sm text-blue-700"> <p> {reportType === 'EEA2' ? ( <> The EEA2 report is a workforce profile analysis required by the Department of Employment and Labour. It breaks down your workforce by occupational level, race, gender, and disability status. </> ) : ( <> The EEA4 report analyzes income differentials within your organization by race, gender, and occupational level. It helps identify pay disparities that may require attention. </> )} </p> </div> </div> </div> </div> <div className="flex justify-end"> <Button onClick={handleGenerateReport} isLoading={isGenerating} icon={<Table className="w-4 h-4" />} > Generate Report </Button> </div> </div> </Card> {reportGenerated && ( <Card title={`${reportType} Report - ${format(new Date(reportPeriod), 'MMMM yyyy')}`}> <div className="space-y-6"> <div className="border border-gray-200 rounded-md overflow-hidden"> <div className="bg-gray-50 px-4 py-3 border-b border-gray-200"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900"> {companyInfo.name} - Employment Equity Report </h3> <p className="text-sm text-gray-500"> Generated on {format(new Date(), 'dd MMM yyyy')} </p> </div> </div> <div className="p-4"> <div className="mb-6"> <h4 className="text-md font-medium text-gray-900 mb-2">Company Information</h4> <div className="grid grid-cols-2 gap-4 text-sm"> <div> <p><span className="font-medium">Name:</span> {companyInfo.name}</p> <p><span className="font-medium">Registration Number:</span> {companyInfo.registrationNumber}</p> <p><span className="font-medium">Industry:</span> {companyInfo.industry}</p> </div> <div> <p><span className="font-medium">Contact Person:</span> {companyInfo.contactPerson}</p> <p><span className="font-medium">Contact Email:</span> {companyInfo.contactEmail}</p> <p><span className="font-medium">Total Employees:</span> {companyInfo.employeeCount}</p> </div> </div> </div> {reportType === 'EEA2' ? ( <div> <h4 className="text-md font-medium text-gray-900 mb-2">Workforce Profile Summary</h4> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Occupational Level </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Black) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Coloured) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (Indian) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male (White) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Black) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Coloured) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (Indian) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female (White) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Disabled </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Total </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {demographicSummary.map((summary) => ( <tr key={summary.occupationalLevel}> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {summary.occupationalLevel} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleBlack} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleColoured} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleIndian} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.maleWhite} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleBlack} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleColoured} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleIndian} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.femaleWhite} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {summary.disabledCount} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {summary.total} </td> </tr> ))} {/* Totals row */} <tr className="bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Total </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleBlack, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleColoured, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleIndian, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.maleWhite, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleBlack, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleColoured, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleIndian, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.femaleWhite, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.disabledCount, 0)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {demographicSummary.reduce((acc, curr) => acc + curr.total, 0)} </td> </tr> </tbody> </table> </div> </div> ) : ( <div> <h4 className="text-md font-medium text-gray-900 mb-2">Income Differentials Summary</h4> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Occupational Level </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Male Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Female Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Gender Gap (%) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Black Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> White Average (ZAR) </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Race Gap (%) </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {/* Income differential data would be calculated and displayed here */} <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Top Management </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,150,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,020,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 11.3% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 980,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 1,230,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 20.3% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Senior Management </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 825,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 780,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 5.8% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 760,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 845,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 10.1% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> Professionally Qualified </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 625,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 590,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 5.6% </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 585,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 645,000 </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> 9.3% </td> </tr> </tbody> </table> </div> </div> )} </div> </div> <div className="flex justify-end space-x-3"> <Button variant="outline" size="md" icon={<Clipboard className="w-4 h-4" />} > Copy to Clipboard </Button> <Button size="md" icon={<Download className="w-4 h-4" />} > Download {reportType} Report </Button> </div> </div> </Card> )} </div> ); }; export default ReportGenerator; import React, { useState, useEffect } from 'react'; import { Employee, Race, Gender, OccupationalLevel } from '../../types'; import { v4 as uuidv4 } from 'uuid'; import Card from '../common/Card'; import Button from '../common/Button'; import { X } from 'lucide-react'; interface EmployeeFormProps { employee?: Employee; onSubmit: (employee: Employee) => void; onCancel: () => void; } const EmployeeForm: React.FC<EmployeeFormProps> = ({ employee, onSubmit, onCancel }) => { const [formData, setFormData] = useState<Employee>({ id: '', firstName: '', lastName: '', idNumber: '', race: 'Black', gender: 'Male', hasDisability: false, disabilityDetails: '', occupationalLevel: 'Skilled Technical', department: '', salary: 0, joinDate: new Date().toISOString().split('T')[0] }); const [errors, setErrors] = useState<Partial<Record<keyof Employee, string>>>({}); const [isSubmitting, setIsSubmitting] = useState(false); // Initialize form with employee data if editing useEffect(() => { if (employee) { setFormData({ ...employee, joinDate: employee.joinDate.split('T')[0] }); } else { // Generate a new ID for new employees setFormData(prev => ({ ...prev, id: uuidv4() })); } }, [employee]); const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => { const { name, value, type } = e.target; if (type === 'checkbox') { const checked = (e.target as HTMLInputElement).checked; setFormData(prev => ({ ...prev, [name]: checked })); } else { setFormData(prev => ({ ...prev, [name]: value })); } // Clear error when field is changed if (errors[name as keyof Employee]) { setErrors(prev => ({ ...prev, [name]: '' })); } }; const validateForm = (): boolean => { const newErrors: Partial<Record<keyof Employee, string>> = {}; // Required fields validation if (!formData.firstName) newErrors.firstName = 'First name is required'; if (!formData.lastName) newErrors.lastName = 'Last name is required'; if (!formData.idNumber) newErrors.idNumber = 'ID number is required'; if (!formData.department) newErrors.department = 'Department is required'; if (!formData.joinDate) newErrors.joinDate = 'Join date is required'; // ID number validation (basic South African ID number format) if (formData.idNumber && !/^\d{13}$/.test(formData.idNumber)) { newErrors.idNumber = 'ID number must be 13 digits'; } // Salary validation if (formData.salary < 0) { newErrors.salary = 'Salary cannot be negative'; } // Disability details required if hasDisability is true if (formData.hasDisability && !formData.disabilityDetails) { newErrors.disabilityDetails = 'Disability details are required'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (validateForm()) { setIsSubmitting(true); // Submit the form data onSubmit(formData); setIsSubmitting(false); } }; const occupationalLevels: OccupationalLevel[] = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const races: Race[] = [ 'Black', 'Coloured', 'Indian', 'White', 'Foreign National' ]; const genders: Gender[] = [ 'Male', 'Female', 'Non-binary' ]; return ( <Card title={employee ? 'Edit Employee' : 'Add New Employee'} footer={ <div className="flex justify-end space-x-2"> <Button variant="outline" onClick={onCancel} disabled={isSubmitting} > Cancel </Button> <Button type="submit" form="employee-form" isLoading={isSubmitting} > {employee ? 'Update Employee' : 'Add Employee'} </Button> </div> } > <form id="employee-form" onSubmit={handleSubmit} className="space-y-6"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Personal Information</h3> <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={onCancel} > Close </Button> </div> {/* Personal Information */} <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="firstName" className="block text-sm font-medium text-gray-700"> First Name * </label> <input type="text" name="firstName" id="firstName" value={formData.firstName} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.firstName ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.firstName && ( <p className="mt-1 text-sm text-red-600">{errors.firstName}</p> )} </div> <div> <label htmlFor="lastName" className="block text-sm font-medium text-gray-700"> Last Name * </label> <input type="text" name="lastName" id="lastName" value={formData.lastName} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.lastName ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.lastName && ( <p className="mt-1 text-sm text-red-600">{errors.lastName}</p> )} </div> <div> <label htmlFor="idNumber" className="block text-sm font-medium text-gray-700"> ID Number * </label> <input type="text" name="idNumber" id="idNumber" value={formData.idNumber} onChange={handleChange} placeholder="13 digit South African ID" className={`mt-1 block w-full rounded-md border ${ errors.idNumber ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.idNumber && ( <p className="mt-1 text-sm text-red-600">{errors.idNumber}</p> )} </div> <div> <label htmlFor="race" className="block text-sm font-medium text-gray-700"> Race * </label> <select name="race" id="race" value={formData.race} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {races.map(race => ( <option key={race} value={race}>{race}</option> ))} </select> </div> <div> <label htmlFor="gender" className="block text-sm font-medium text-gray-700"> Gender * </label> <select name="gender" id="gender" value={formData.gender} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {genders.map(gender => ( <option key={gender} value={gender}>{gender}</option> ))} </select> </div> <div> <div className="flex items-center mt-5"> <input type="checkbox" name="hasDisability" id="hasDisability" checked={formData.hasDisability} onChange={handleChange} className="h-4 w-4 text-emerald-600 focus:ring-emerald-500 border-gray-300 rounded" /> <label htmlFor="hasDisability" className="ml-2 block text-sm font-medium text-gray-700"> Person with Disability </label> </div> </div> {formData.hasDisability && ( <div> <label htmlFor="disabilityDetails" className="block text-sm font-medium text-gray-700"> Disability Details * </label> <input type="text" name="disabilityDetails" id="disabilityDetails" value={formData.disabilityDetails || ''} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.disabilityDetails ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.disabilityDetails && ( <p className="mt-1 text-sm text-red-600">{errors.disabilityDetails}</p> )} </div> )} </div> {/* Employment Information */} <div className="pt-6 border-t border-gray-200"> <h3 className="text-lg font-medium text-gray-900 mb-4">Employment Information</h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label htmlFor="occupationalLevel" className="block text-sm font-medium text-gray-700"> Occupational Level * </label> <select name="occupationalLevel" id="occupationalLevel" value={formData.occupationalLevel} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {occupationalLevels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" name="department" id="department" value={formData.department} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.department ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.department && ( <p className="mt-1 text-sm text-red-600">{errors.department}</p> )} </div> <div> <label htmlFor="salary" className="block text-sm font-medium text-gray-700"> Annual Salary (ZAR) </label> <input type="number" name="salary" id="salary" value={formData.salary} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.salary ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.salary && ( <p className="mt-1 text-sm text-red-600">{errors.salary}</p> )} </div> <div> <label htmlFor="joinDate" className="block text-sm font-medium text-gray-700"> Join Date * </label> <input type="date" name="joinDate" id="joinDate" value={formData.joinDate} onChange={handleChange} className={`mt-1 block w-full rounded-md border ${ errors.joinDate ? 'border-red-300' : 'border-gray-300' } shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm`} /> {errors.joinDate && ( <p className="mt-1 text-sm text-red-600">{errors.joinDate}</p> )} </div> <div> <label htmlFor="terminationDate" className="block text-sm font-medium text-gray-700"> Termination Date (if applicable) </label> <input type="date" name="terminationDate" id="terminationDate" value={formData.terminationDate || ''} onChange={handleChange} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" /> </div> </div> </div> </form> </Card> ); }; export default EmployeeForm; import React, { useState } from 'react'; import { Employee, Race, Gender, OccupationalLevel } from '../../types'; import { Edit, Trash2, ChevronDown, ChevronUp, Info, Search, Filter, X } from 'lucide-react'; import Button from '../common/Button'; import Card from '../common/Card'; interface EmployeeTableProps { employees: Employee[]; onEdit: (employee: Employee) => void; onDelete: (id: string) => void; onView: (employee: Employee) => void; } const EmployeeTable: React.FC<EmployeeTableProps> = ({ employees, onEdit, onDelete, onView }) => { const [sortField, setSortField] = useState<keyof Employee>('lastName'); const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc'); const [searchTerm, setSearchTerm] = useState(''); const [filters, setFilters] = useState<{ race: Race | 'All'; gender: Gender | 'All'; occupationalLevel: OccupationalLevel | 'All'; hasDisability: 'All' | 'Yes' | 'No'; }>({ race: 'All', gender: 'All', occupationalLevel: 'All', hasDisability: 'All' }); const [showFilters, setShowFilters] = useState(false); // Handle sort const handleSort = (field: keyof Employee) => { if (sortField === field) { setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc'); } else { setSortField(field); setSortDirection('asc'); } }; // Handle search const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => { setSearchTerm(e.target.value); }; // Filter and sort employees const filteredEmployees = employees .filter(employee => { // Search filter const searchMatch = searchTerm === '' || `${employee.firstName} ${employee.lastName}`.toLowerCase().includes(searchTerm.toLowerCase()) || employee.idNumber.includes(searchTerm); // Dropdown filters const raceMatch = filters.race === 'All' || employee.race === filters.race; const genderMatch = filters.gender === 'All' || employee.gender === filters.gender; const levelMatch = filters.occupationalLevel === 'All' || employee.occupationalLevel === filters.occupationalLevel; const disabilityMatch = filters.hasDisability === 'All' || (filters.hasDisability === 'Yes' && employee.hasDisability) || (filters.hasDisability === 'No' && !employee.hasDisability); return searchMatch && raceMatch && genderMatch && levelMatch && disabilityMatch; }) .sort((a, b) => { if (a[sortField] < b[sortField]) { return sortDirection === 'asc' ? -1 : 1; } if (a[sortField] > b[sortField]) { return sortDirection === 'asc' ? 1 : -1; } return 0; }); // Reset filters const resetFilters = () => { setFilters({ race: 'All', gender: 'All', occupationalLevel: 'All', hasDisability: 'All' }); setSearchTerm(''); }; // Get unique values for filter dropdowns const races = ['All', ...Array.from(new Set(employees.map(e => e.race)))]; const genders = ['All', ...Array.from(new Set(employees.map(e => e.gender)))]; const levels = ['All', ...Array.from(new Set(employees.map(e => e.occupationalLevel)))]; return ( <Card noPadding className="overflow-hidden"> {/* Search and filters */} <div className="p-4 border-b border-gray-200 bg-gray-50"> <div className="flex flex-col sm:flex-row justify-between space-y-2 sm:space-y-0"> <div className="relative w-full sm:w-64"> <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none"> <Search className="w-4 h-4 text-gray-500" /> </div> <input type="text" className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full pl-10 p-2" placeholder="Search employees..." value={searchTerm} onChange={handleSearch} /> </div> <div className="flex space-x-2"> <Button variant="outline" size="sm" icon={<Filter className="w-4 h-4" />} onClick={() => setShowFilters(!showFilters)} > Filters {(filters.race !== 'All' || filters.gender !== 'All' || filters.occupationalLevel !== 'All' || filters.hasDisability !== 'All') && ( <span className="ml-1 px-1.5 py-0.5 text-xs bg-emerald-100 text-emerald-800 rounded-full"> {Object.values(filters).filter(v => v !== 'All').length} </span> )} </Button> {(filters.race !== 'All' || filters.gender !== 'All' || filters.occupationalLevel !== 'All' || filters.hasDisability !== 'All') && ( <Button variant="text" size="sm" icon={<X className="w-4 h-4" />} onClick={resetFilters} > Clear </Button> )} </div> </div> {/* Expanded filters */} {showFilters && ( <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4"> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Race</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.race} onChange={(e) => setFilters({...filters, race: e.target.value as Race | 'All'})} > {races.map(race => ( <option key={race} value={race}>{race}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Gender</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.gender} onChange={(e) => setFilters({...filters, gender: e.target.value as Gender | 'All'})} > {genders.map(gender => ( <option key={gender} value={gender}>{gender}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Occupational Level</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.occupationalLevel} onChange={(e) => setFilters({...filters, occupationalLevel: e.target.value as OccupationalLevel | 'All'})} > {levels.map(level => ( <option key={level} value={level}>{level}</option> ))} </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1">Disability Status</label> <select className="bg-white border border-gray-300 text-gray-900 text-sm rounded-md focus:ring-emerald-500 focus:border-emerald-500 block w-full p-2" value={filters.hasDisability} onChange={(e) => setFilters({...filters, hasDisability: e.target.value as 'All' | 'Yes' | 'No'})} > <option value="All">All</option> <option value="Yes">With Disability</option> <option value="No">No Disability</option> </select> </div> </div> )} </div> {/* Table */} <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('lastName')} > <span>Employee</span> {sortField === 'lastName' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('race')} > <span>Race</span> {sortField === 'race' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('gender')} > <span>Gender</span> {sortField === 'gender' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('occupationalLevel')} > <span>Occupational Level</span> {sortField === 'occupationalLevel' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> <button className="flex items-center space-x-1 focus:outline-none" onClick={() => handleSort('hasDisability')} > <span>Disability</span> {sortField === 'hasDisability' && ( sortDirection === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" /> )} </button> </th> <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Actions </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {filteredEmployees.length > 0 ? ( filteredEmployees.map((employee) => ( <tr key={employee.id} className="hover:bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center"> <div> <div className="text-sm font-medium text-gray-900"> {employee.firstName} {employee.lastName} </div> <div className="text-sm text-gray-500"> {employee.idNumber} </div> </div> </div> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800"> {employee.race} </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {employee.gender} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {employee.occupationalLevel} </td> <td className="px-6 py-4 whitespace-nowrap"> {employee.hasDisability ? ( <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-amber-100 text-amber-800"> Yes </span> ) : ( <span className="text-sm text-gray-500">No</span> )} </td> <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> <div className="flex justify-end space-x-2"> <button onClick={() => onView(employee)} className="text-blue-600 hover:text-blue-900 focus:outline-none" > <Info className="w-5 h-5" /> </button> <button onClick={() => onEdit(employee)} className="text-indigo-600 hover:text-indigo-900 focus:outline-none" > <Edit className="w-5 h-5" /> </button> <button onClick={() => onDelete(employee.id)} className="text-red-600 hover:text-red-900 focus:outline-none" > <Trash2 className="w-5 h-5" /> </button> </div> </td> </tr> )) ) : ( <tr> <td colSpan={6} className="px-6 py-4 text-center text-sm text-gray-500"> No employees found matching the current filters. </td> </tr> )} </tbody> </table> </div> {/* Table footer with counts */} <div className="px-6 py-3 bg-gray-50 border-t border-gray-200 text-sm text-gray-500"> Showing {filteredEmployees.length} of {employees.length} employees </div> </Card> ); }; export default EmployeeTable; import React from 'react'; import { EquityGoal } from '../../types'; import Card from '../common/Card'; import { calculateGoalProgress } from '../../utils/calculations'; import { format } from 'date-fns'; interface GoalTrackerProps { goals: EquityGoal[]; } const GoalTracker: React.FC<GoalTrackerProps> = ({ goals }) => { if (!goals || goals.length === 0) { return ( <Card title="Equity Goals Progress"> <div className="flex flex-col items-center justify-center py-8"> <p className="text-gray-500 mb-4">No equity goals have been set yet.</p> <a href="/goals" className="text-emerald-600 hover:text-emerald-700 font-medium"> + Add Equity Goals </a> </div> </Card> ); } return ( <Card title="Equity Goals Progress" className="h-full"> <div className="space-y-6 max-h-[350px] overflow-y-auto pr-2"> {goals.map((goal) => { const progress = calculateGoalProgress(goal.targetPercentage, goal.currentPercentage); return ( <div key={goal.id} className="space-y-2"> <div className="flex justify-between items-center"> <div> <h4 className="font-medium text-gray-900"> {goal.targetGroup} - {goal.occupationalLevel} </h4> <p className="text-sm text-gray-500"> Target: {goal.targetPercentage}% by {format(new Date(goal.targetDate), 'MMM d, yyyy')} </p> </div> <div className="text-right"> <span className="text-sm font-medium text-gray-900"> {goal.currentPercentage}% </span> <span className="text-xs text-gray-500 ml-1"> of {goal.targetPercentage}% </span> </div> </div> {/* Progress bar */} <div className="w-full bg-gray-200 rounded-full h-2.5"> <div className={`h-2.5 rounded-full ${getProgressColorClass(progress)}`} style={{ width: `${progress}%` }} ></div> </div> {/* Progress indicator */} <div className="flex justify-between text-xs"> <span className={getProgressTextColorClass(progress)}> {progress}% Complete </span> {goal.notes && ( <span className="text-gray-500 truncate max-w-[60%]" title={goal.notes}> {goal.notes} </span> )} </div> </div> ); })} </div> </Card> ); }; const getProgressColorClass = (progress: number): string => { if (progress < 25) return 'bg-red-600'; if (progress < 50) return 'bg-amber-500'; if (progress < 75) return 'bg-blue-500'; return 'bg-emerald-600'; }; const getProgressTextColorClass = (progress: number): string => { if (progress < 25) return 'text-red-600 font-medium'; if (progress < 50) return 'text-amber-500 font-medium'; if (progress < 75) return 'text-blue-600 font-medium'; return 'text-emerald-600 font-medium'; }; export default GoalTracker; import React, { useEffect, useState } from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement, RadialLinearScale } from 'chart.js'; import { Bar, Doughnut, Radar } from 'react-chartjs-2'; import Card from '../common/Card'; import { Race, Gender, Employee } from '../../types'; import { calculateRacePercentages, calculateGenderPercentages, calculateDisabilityPercentage } from '../../utils/calculations'; // Register ChartJS components ChartJS.register( CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ArcElement, PointElement, LineElement, RadialLinearScale ); interface DemographicChartProps { employees: Employee[]; chartType: 'race' | 'gender' | 'occupational' | 'disability'; title?: string; } const DemographicChart: React.FC<DemographicChartProps> = ({ employees, chartType, title }) => { const [chartData, setChartData] = useState<any>(null); const [loading, setLoading] = useState(true); useEffect(() => { if (!employees || employees.length === 0) { setLoading(false); return; } let data; let options; switch (chartType) { case 'race': const racePercentages = calculateRacePercentages(employees); data = { labels: Object.keys(racePercentages) as Race[], datasets: [ { label: 'Race Distribution', data: Object.values(racePercentages), backgroundColor: [ 'rgba(16, 185, 129, 0.7)', // emerald 'rgba(59, 130, 246, 0.7)', // blue 'rgba(245, 158, 11, 0.7)', // amber 'rgba(244, 63, 94, 0.7)', // rose 'rgba(139, 92, 246, 0.7)', // violet ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Race Distribution', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; case 'gender': const genderPercentages = calculateGenderPercentages(employees); data = { labels: Object.keys(genderPercentages), datasets: [ { label: 'Gender Distribution', data: Object.values(genderPercentages), backgroundColor: [ 'rgba(59, 130, 246, 0.7)', // blue 'rgba(244, 63, 94, 0.7)', // rose 'rgba(139, 92, 246, 0.7)', // violet ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Gender Distribution', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; case 'occupational': // Count employees by occupational level const occupationalLevels = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ]; const occupationalCounts: Record<string, number> = {}; occupationalLevels.forEach(level => { occupationalCounts[level] = employees.filter(emp => emp.occupationalLevel === level).length; }); data = { labels: occupationalLevels, datasets: [ { label: '# of Employees', data: Object.values(occupationalCounts), backgroundColor: 'rgba(16, 185, 129, 0.7)', borderColor: 'rgba(16, 185, 129, 1)', borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { display: false, }, title: { display: !!title, text: title || 'Occupational Levels', }, }, scales: { y: { beginAtZero: true, title: { display: true, text: 'Number of Employees' } }, x: { title: { display: true, text: 'Occupational Level' } } }, }; setChartData({ data, options, type: 'bar' }); break; case 'disability': const disabilityPercentage = calculateDisabilityPercentage(employees); data = { labels: ['With Disabilities', 'Without Disabilities'], datasets: [ { label: 'Disability Status', data: [disabilityPercentage, 100 - disabilityPercentage], backgroundColor: [ 'rgba(245, 158, 11, 0.7)', // amber 'rgba(209, 213, 219, 0.7)', // gray ], borderWidth: 1, }, ], }; options = { responsive: true, plugins: { legend: { position: 'right' as const, }, title: { display: !!title, text: title || 'Disability Status', }, }, }; setChartData({ data, options, type: 'doughnut' }); break; default: setChartData(null); } setLoading(false); }, [employees, chartType, title]); if (loading) { return <Card loading={true} />; } if (!chartData) { return ( <Card> <div className="flex items-center justify-center h-64"> <p className="text-gray-500">No data available</p> </div> </Card> ); } return ( <Card title={chartData.options.plugins.title.text} className="h-full"> <div className="h-64"> {chartData.type === 'doughnut' && ( <Doughnut data={chartData.data} options={chartData.options} /> )} {chartData.type === 'bar' && ( <Bar data={chartData.data} options={chartData.options} /> )} </div> </Card> ); }; export default DemographicChart; import React, { ReactNode } from 'react'; import Card from '../common/Card'; interface StatCardProps { title: string; value: string | number; change?: { value: number; isPositive: boolean; }; icon?: ReactNode; color?: 'emerald' | 'blue' | 'amber' | 'rose' | 'violet' | 'indigo'; } const StatCard: React.FC<StatCardProps> = ({ title, value, change, icon, color = 'emerald' }) => { const colorClasses = { emerald: 'bg-emerald-100 text-emerald-600', blue: 'bg-blue-100 text-blue-600', amber: 'bg-amber-100 text-amber-600', rose: 'bg-rose-100 text-rose-600', violet: 'bg-violet-100 text-violet-600', indigo: 'bg-indigo-100 text-indigo-600', }; const changeColorClasses = change?.isPositive ? 'text-green-600 bg-green-50' : 'text-red-600 bg-red-50'; return ( <Card className="hover:shadow-md transition-shadow duration-300"> <div className="flex items-start justify-between"> <div> <p className="text-sm font-medium text-gray-500">{title}</p> <p className="mt-2 text-3xl font-semibold text-gray-900">{value}</p> {change && ( <div className="mt-2 flex items-center"> <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${changeColorClasses}`}> {change.isPositive ? '↑' : '↓'} {Math.abs(change.value)}% </span> <span className="text-xs text-gray-500 ml-2">from last period</span> </div> )} </div> {icon && ( <div className={`p-3 rounded-full ${colorClasses[color]}`}> {icon} </div> )} </div> </Card> ); }; export default StatCard; import React, { ButtonHTMLAttributes, ReactNode } from 'react'; interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { variant?: 'primary' | 'secondary' | 'outline' | 'danger' | 'success' | 'text'; size?: 'sm' | 'md' | 'lg'; isLoading?: boolean; icon?: ReactNode; iconPosition?: 'left' | 'right'; fullWidth?: boolean; children: ReactNode; } const Button: React.FC<ButtonProps> = ({ variant = 'primary', size = 'md', isLoading = false, icon, iconPosition = 'left', fullWidth = false, className = '', children, disabled, ...rest }) => { // Base classes const baseClasses = 'inline-flex items-center justify-center font-medium rounded-md focus:outline-none transition-colors'; // Size classes const sizeClasses = { sm: 'px-3 py-1.5 text-sm', md: 'px-4 py-2 text-sm', lg: 'px-6 py-3 text-base' }; // Variant classes const variantClasses = { primary: 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm', secondary: 'bg-blue-600 hover:bg-blue-700 text-white shadow-sm', outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50', danger: 'bg-red-600 hover:bg-red-700 text-white shadow-sm', success: 'bg-green-600 hover:bg-green-700 text-white shadow-sm', text: 'text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50' }; // Disabled classes const disabledClasses = 'opacity-50 cursor-not-allowed pointer-events-none'; // Icon spacing const iconSpacing = icon ? (iconPosition === 'left' ? 'space-x-2' : 'space-x-reverse space-x-2') : ''; // Full width const widthClasses = fullWidth ? 'w-full' : ''; return ( <button className={` ${baseClasses} ${sizeClasses[size]} ${variantClasses[variant]} ${(disabled || isLoading) ? disabledClasses : ''} ${iconSpacing} ${widthClasses} ${className} `} disabled={disabled || isLoading} {...rest} > {isLoading ? ( <> <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" > <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" ></circle> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" ></path> </svg> {children} </> ) : ( <> {icon && iconPosition === 'left' && <span>{icon}</span>} <span>{children}</span> {icon && iconPosition === 'right' && <span>{icon}</span>} </> )} </button> ); }; export default Button; import React, { ReactNode } from 'react'; interface CardProps { title?: string; children: ReactNode; className?: string; footer?: ReactNode; noPadding?: boolean; loading?: boolean; } const Card: React.FC<CardProps> = ({ title, children, className = '', footer, noPadding = false, loading = false }) => { return ( <div className={`bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden ${className}`}> {title && ( <div className="px-6 py-4 border-b border-gray-200"> <h3 className="text-lg font-medium text-gray-900">{title}</h3> </div> )} <div className={`${noPadding ? '' : 'p-6'} ${loading ? 'opacity-50' : ''}`}> {loading ? ( <div className="flex items-center justify-center py-8"> <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div> </div> ) : ( children )} </div> {footer && ( <div className="px-6 py-3 bg-gray-50 border-t border-gray-200"> {footer} </div> )} </div> ); }; export default Card; import React, { useState, useEffect } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { Menu, X, UserCircle, LogOut, ChevronDown } from 'lucide-react'; import { useAppContext } from '../../contexts/AppContext'; const Header: React.FC = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const [isUserMenuOpen, setIsUserMenuOpen] = useState(false); const [scrolled, setScrolled] = useState(false); const { currentUser, logout } = useAppContext(); const location = useLocation(); // Handle scroll effect for header useEffect(() => { const handleScroll = () => { if (window.scrollY > 10) { setScrolled(true); } else { setScrolled(false); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); // Close mobile menu when route changes useEffect(() => { setIsMenuOpen(false); }, [location]); return ( <header className={`fixed top-0 left-0 right-0 z-10 transition-all duration-300 ${ scrolled ? 'bg-white shadow-md py-2' : 'bg-transparent py-4' }`} > <div className="container mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex justify-between items-center"> {/* Logo */} <Link to="/" className="flex items-center"> <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-xl mr-2"> EE </div> <span className="text-xl font-bold text-gray-800">EquityTool</span> </Link> {/* Desktop Navigation */} <nav className="hidden md:flex space-x-8"> <NavLink to="/" active={location.pathname === '/'}>Dashboard</NavLink> <NavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</NavLink> <NavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</NavLink> <NavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</NavLink> <NavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</NavLink> </nav> {/* User Menu (Desktop) */} <div className="hidden md:flex items-center"> {currentUser ? ( <div className="relative"> <button className="flex items-center space-x-2 text-gray-700 hover:text-emerald-600 focus:outline-none" onClick={() => setIsUserMenuOpen(!isUserMenuOpen)} > <UserCircle className="w-6 h-6" /> <span>{currentUser.name}</span> <ChevronDown className={`w-4 h-4 transition-transform ${isUserMenuOpen ? 'rotate-180' : ''}`} /> </button> {isUserMenuOpen && ( <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20"> <div className="px-4 py-2 text-sm text-gray-500 border-b"> Logged in as <span className="font-semibold">{currentUser.role}</span> </div> <Link to="/profile" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" onClick={() => setIsUserMenuOpen(false)} > Profile Settings </Link> <button className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsUserMenuOpen(false); }} > <div className="flex items-center"> <LogOut className="w-4 h-4 mr-2" /> Sign Out </div> </button> </div> )} </div> ) : ( <Link to="/login" className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-emerald-600 hover:bg-emerald-700" > Sign In </Link> )} </div> {/* Mobile Menu Button */} <button className="md:hidden text-gray-700 focus:outline-none" onClick={() => setIsMenuOpen(!isMenuOpen)} > {isMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />} </button> </div> </div> {/* Mobile Menu */} {isMenuOpen && ( <div className="md:hidden bg-white border-t shadow-lg"> <div className="px-2 pt-2 pb-3 space-y-1"> <MobileNavLink to="/" active={location.pathname === '/'}>Dashboard</MobileNavLink> <MobileNavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</MobileNavLink> <MobileNavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</MobileNavLink> <MobileNavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</MobileNavLink> <MobileNavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</MobileNavLink> </div> {/* User Menu (Mobile) */} <div className="px-5 pt-4 pb-3 border-t border-gray-200"> {currentUser ? ( <> <div className="flex items-center mb-3"> <div className="flex-shrink-0"> <UserCircle className="w-10 h-10 text-gray-400" /> </div> <div className="ml-3"> <div className="text-base font-medium text-gray-800">{currentUser.name}</div> <div className="text-sm font-medium text-gray-500">{currentUser.email}</div> </div> </div> <div className="space-y-1"> <Link to="/profile" className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:bg-gray-100" > Profile Settings </Link> <button className="block w-full text-left px-3 py-2 rounded-md text-base font-medium text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsMenuOpen(false); }} > Sign Out </button> </div> </> ) : ( <Link to="/login" className="block w-full px-5 py-3 text-center font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-md" > Sign In </Link> )} </div> </div> )} </header> ); }; interface NavLinkProps { to: string; active: boolean; children: React.ReactNode; } const NavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`relative px-2 py-1 transition-colors ${ active ? 'text-emerald-600 font-medium' : 'text-gray-600 hover:text-emerald-600' }`} > {children} {active && ( <span className="absolute bottom-0 left-0 w-full h-0.5 bg-emerald-600 rounded-full"></span> )} </Link> ); }; const MobileNavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`block px-3 py-2 rounded-md text-base font-medium ${ active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-700 hover:bg-gray-50 hover:text-emerald-600' }`} > {children} </Link> ); }; export default Header; import React, { createContext, useContext, useState, ReactNode } from 'react'; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { mockEmployees, mockCompanyInfo, mockEquityGoals, mockDemographicSummary, mockUsers } from '../utils/mockData'; import { calculateDemographicSummary } from '../utils/calculations'; interface AppContextType { employees: Employee[]; addEmployee: (employee: Employee) => void; updateEmployee: (employee: Employee) => void; deleteEmployee: (id: string) => void; companyInfo: CompanyInfo; updateCompanyInfo: (info: CompanyInfo) => void; equityGoals: EquityGoal[]; addEquityGoal: (goal: EquityGoal) => void; updateEquityGoal: (goal: EquityGoal) => void; deleteEquityGoal: (id: string) => void; demographicSummary: DemographicSummary[]; refreshDemographicSummary: () => void; users: User[]; addUser: (user: User) => void; updateUser: (user: User) => void; deleteUser: (id: string) => void; currentUser: User | null; login: (email: string, role?: string) => void; logout: () => void; } const AppContext = createContext<AppContextType | undefined>(undefined); export const AppProvider: React.FC<{children: ReactNode}> = ({ children }) => { const [employees, setEmployees] = useState<Employee[]>(mockEmployees); const [companyInfo, setCompanyInfo] = useState<CompanyInfo>(mockCompanyInfo); const [equityGoals, setEquityGoals] = useState<EquityGoal[]>(mockEquityGoals); const [demographicSummary, setDemographicSummary] = useState<DemographicSummary[]>(mockDemographicSummary); const [users, setUsers] = useState<User[]>(mockUsers); const [currentUser, setCurrentUser] = useState<User | null>(null); // Employee functions const addEmployee = (employee: Employee) => { setEmployees(prev => [...prev, employee]); refreshDemographicSummary(); }; const updateEmployee = (employee: Employee) => { setEmployees(prev => prev.map(emp => emp.id === employee.id ? employee : emp)); refreshDemographicSummary(); }; const deleteEmployee = (id: string) => { setEmployees(prev => prev.filter(emp => emp.id !== id)); refreshDemographicSummary(); }; // Company info functions const updateCompanyInfo = (info: CompanyInfo) => { setCompanyInfo(info); }; // Equity goal functions const addEquityGoal = (goal: EquityGoal) => { setEquityGoals(prev => [...prev, goal]); }; const updateEquityGoal = (goal: EquityGoal) => { setEquityGoals(prev => prev.map(g => g.id === goal.id ? goal : g)); }; const deleteEquityGoal = (id: string) => { setEquityGoals(prev => prev.filter(g => g.id !== id)); }; // Demographic summary functions const refreshDemographicSummary = () => { const summary = calculateDemographicSummary(employees); setDemographicSummary(summary); }; // User management functions const addUser = (user: User) => { setUsers(prev => [...prev, user]); }; const updateUser = (user: User) => { setUsers(prev => prev.map(u => u.id === user.id ? user : u)); }; const deleteUser = (id: string) => { setUsers(prev => prev.filter(u => u.id !== id)); }; // Authentication functions const login = (email: string, role?: string) => { // For demo purposes, auto-login with the first user or specified role let userToLogin; if (role) { userToLogin = users.find(u => u.role === role); } else { userToLogin = users.find(u => u.email === email); } if (userToLogin) { setCurrentUser(userToLogin); return true; } return false; }; const logout = () => { setCurrentUser(null); }; const value = { employees, addEmployee, updateEmployee, deleteEmployee, companyInfo, updateCompanyInfo, equityGoals, addEquityGoal, updateEquityGoal, deleteEquityGoal, demographicSummary, refreshDemographicSummary, users, addUser, updateUser, deleteUser, currentUser, login, logout }; return <AppContext.Provider value={value}>{children}</AppContext.Provider>; }; export const useAppContext = (): AppContextType => { const context = useContext(AppContext); if (context === undefined) { throw new Error('useAppContext must be used within an AppProvider'); } return context; }; { "name": "equity-compliance-tool", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint .", "preview": "vite preview" }, "dependencies": { "@headlessui/react": "^1.7.17", "chart.js": "^4.4.1", "date-fns": "^2.30.0", "lucide-react": "^0.344.0", "react": "^18.3.1", "react-chartjs-2": "^5.2.0", "react-dom": "^18.3.1", "react-router-dom": "^6.22.1", "uuid": "^9.0.1" }, "devDependencies": { "@eslint/js": "^9.9.1", "@types/react": "^18.3.5", "@types/react-dom": "^18.3.0", "@types/uuid": "^9.0.7", "@vitejs/plugin-react": "^4.3.1", "autoprefixer": "^10.4.18", "eslint": "^9.9.1", "eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-refresh": "^0.4.11", "globals": "^15.9.0", "postcss": "^8.4.35", "tailwindcss": "^3.4.1", "typescript": "^5.5.3", "typescript-eslint": "^8.3.0", "vite": "^5.4.2" } } import { Employee, DemographicSummary, OccupationalLevel, Race, Gender } from '../types'; /** * Calculates demographic summary by occupational level */ export const calculateDemographicSummary = ( employees: Employee[] ): DemographicSummary[] => { // Get unique occupational levels const occupationalLevels = [ 'Top Management', 'Senior Management', 'Professionally Qualified', 'Skilled Technical', 'Semi-skilled', 'Unskilled', 'Temporary Employees' ] as OccupationalLevel[]; return occupationalLevels.map(level => { const levelEmployees = employees.filter(emp => emp.occupationalLevel === level); // Initialize summary const summary: DemographicSummary = { occupationalLevel: level, maleBlack: 0, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: levelEmployees.length }; // Count by demographics levelEmployees.forEach(emp => { // Count by gender and race if (emp.gender === 'Male') { if (emp.race === 'Black') summary.maleBlack++; else if (emp.race === 'Coloured') summary.maleColoured++; else if (emp.race === 'Indian') summary.maleIndian++; else if (emp.race === 'White') summary.maleWhite++; else if (emp.race === 'Foreign National') summary.maleForeignNational++; } else if (emp.gender === 'Female') { if (emp.race === 'Black') summary.femaleBlack++; else if (emp.race === 'Coloured') summary.femaleColoured++; else if (emp.race === 'Indian') summary.femaleIndian++; else if (emp.race === 'White') summary.femaleWhite++; else if (emp.race === 'Foreign National') summary.femaleForeignNational++; } // Count people with disabilities if (emp.hasDisability) { summary.disabledCount++; } }); return summary; }); }; /** * Calculate percentage of employees by race */ export const calculateRacePercentages = (employees: Employee[]): Record<Race, number> => { const total = employees.length; const counts: Record<Race, number> = { 'Black': 0, 'Coloured': 0, 'Indian': 0, 'White': 0, 'Foreign National': 0 }; employees.forEach(emp => { counts[emp.race]++; }); const percentages: Record<Race, number> = {} as Record<Race, number>; Object.keys(counts).forEach(race => { percentages[race as Race] = total > 0 ? Math.round((counts[race as Race] / total) * 100) : 0; }); return percentages; }; /** * Calculate percentage of employees by gender */ export const calculateGenderPercentages = (employees: Employee[]): Record<string, number> => { const total = employees.length; const counts: Record<string, number> = { 'Male': 0, 'Female': 0, 'Non-binary': 0 }; employees.forEach(emp => { counts[emp.gender]++; }); const percentages: Record<string, number> = {}; Object.keys(counts).forEach(gender => { percentages[gender] = total > 0 ? Math.round((counts[gender] / total) * 100) : 0; }); return percentages; }; /** * Calculate percentage of employees with disabilities */ export const calculateDisabilityPercentage = (employees: Employee[]): number => { const total = employees.length; const disabledCount = employees.filter(emp => emp.hasDisability).length; return total > 0 ? Math.round((disabledCount / total) * 100) : 0; }; /** * Filter employees by department */ export const filterByDepartment = (employees: Employee[], department: string): Employee[] => { if (!department || department === 'All Departments') { return employees; } return employees.filter(emp => emp.department === department); }; /** * Get unique departments from employee data */ export const getUniqueDepartments = (employees: Employee[]): string[] => { const departments = new Set<string>(); employees.forEach(emp => departments.add(emp.department)); return Array.from(departments).sort(); }; /** * Calculate progress towards goals */ export const calculateGoalProgress = ( targetPercentage: number, currentPercentage: number ): number => { if (targetPercentage <= 0) return 100; return Math.min(Math.round((currentPercentage / targetPercentage) * 100), 100); }; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { v4 as uuidv4 } from 'uuid'; // Mock Company Information - Updated for 2024 legislation export const mockCompanyInfo: CompanyInfo = { name: 'Exemplar Holdings', registrationNumber: '2010/123456/07', industry: 'Financial Services', sectorCode: 'K', address: '123 Main Street, Sandton, Johannesburg, 2196', province: 'Gauteng', contactPerson: 'Jane Smith', contactEmail: 'jane.smith@exemplar.co.za', contactPhone: '011 123 4567', employeeCount: 245, designatedEmployer: true, complianceOfficer: 'John Doe', complianceOfficerContact: 'john.doe@exemplar.co.za' }; // Mock Employees export const mockEmployees: Employee[] = [ { id: uuidv4(), firstName: 'Thabo', lastName: 'Mbeki', idNumber: '7501015800082', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Top Management', department: 'Executive', salary: 1200000, joinDate: '2020-01-15' }, { id: uuidv4(), firstName: 'Sarah', lastName: 'Johnson', idNumber: '8012045800082', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Senior Management', department: 'Finance', salary: 850000, joinDate: '2019-04-12' }, { id: uuidv4(), firstName: 'Lerato', lastName: 'Nkosi', idNumber: '8909235800083', race: 'Black', gender: 'Female', hasDisability: true, disabilityDetails: 'Hearing impairment', occupationalLevel: 'Professionally Qualified', department: 'Human Resources', salary: 620000, joinDate: '2018-06-01' }, { id: uuidv4(), firstName: 'Ahmed', lastName: 'Patel', idNumber: '7705125800084', race: 'Indian', gender: 'Male', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 450000, joinDate: '2021-03-15' }, { id: uuidv4(), firstName: 'Jessica', lastName: 'De Villiers', idNumber: '9012055800086', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Professionally Qualified', department: 'Marketing', salary: 580000, joinDate: '2019-11-01' }, { id: uuidv4(), firstName: 'Sipho', lastName: 'Ndlovu', idNumber: '8504175800087', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Semi-skilled', department: 'Operations', salary: 320000, joinDate: '2020-08-15' }, { id: uuidv4(), firstName: 'Fatima', lastName: 'Mohammed', idNumber: '9108235800088', race: 'Indian', gender: 'Female', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 470000, joinDate: '2019-05-20' }, { id: uuidv4(), firstName: 'James', lastName: 'Wilson', idNumber: '8306155800089', race: 'Coloured', gender: 'Male', hasDisability: true, disabilityDetails: 'Mobility impairment', occupationalLevel: 'Skilled Technical', department: 'Finance', salary: 420000, joinDate: '2018-10-10' } ]; // Mock Equity Goals export const mockEquityGoals: EquityGoal[] = [ { id: uuidv4(), occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 25, targetPercentage: 50, targetDate: '2025-12-31', notes: 'Focus on internal promotions and external recruitment' }, { id: uuidv4(), occupationalLevel: 'Senior Management', targetGroup: 'Female', currentPercentage: 30, targetPercentage: 45, targetDate: '2024-12-31', notes: 'Implement mentorship program to prepare for promotions' }, { id: uuidv4(), occupationalLevel: 'Professionally Qualified', targetGroup: 'People with Disabilities', currentPercentage: 2, targetPercentage: 7, targetDate: '2025-06-30', notes: 'Improve workplace accessibility and targeted recruitment' } ]; // Mock Demographic Summary export const mockDemographicSummary: DemographicSummary[] = [ { occupationalLevel: 'Top Management', maleBlack: 1, maleColoured: 0, maleIndian: 0, maleWhite: 3, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 1, femaleForeignNational: 0, disabledCount: 0, total: 5 }, { occupationalLevel: 'Senior Management', maleBlack: 2, maleColoured: 1, maleIndian: 1, maleWhite: 5, maleForeignNational: 1, femaleBlack: 1, femaleColoured: 1, femaleIndian: 0, femaleWhite: 3, femaleForeignNational: 0, disabledCount: 1, total: 15 }, { occupationalLevel: 'Professionally Qualified', maleBlack: 15, maleColoured: 6, maleIndian: 8, maleWhite: 12, maleForeignNational: 2, femaleBlack: 12, femaleColoured: 5, femaleIndian: 7, femaleWhite: 10, femaleForeignNational: 1, disabledCount: 4, total: 78 }, { occupationalLevel: 'Skilled Technical', maleBlack: 25, maleColoured: 8, maleIndian: 6, maleWhite: 10, maleForeignNational: 3, femaleBlack: 18, femaleColoured: 7, femaleIndian: 5, femaleWhite: 8, femaleForeignNational: 2, disabledCount: 5, total: 92 }, { occupationalLevel: 'Semi-skilled', maleBlack: 18, maleColoured: 5, maleIndian: 2, maleWhite: 3, maleForeignNational: 4, femaleBlack: 12, femaleColoured: 3, femaleIndian: 1, femaleWhite: 2, femaleForeignNational: 0, disabledCount: 2, total: 50 }, { occupationalLevel: 'Unskilled', maleBlack: 3, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 2, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: 5 } ]; // Mock Users - Updated with analyst role export const mockUsers: User[] = [ { id: uuidv4(), name: 'Admin User', email: 'admin@exemplar.co.za', cellphone: '+27821234567', role: 'admin', lastLogin: '2023-06-15T08:30:00Z', isVerified: true }, { id: uuidv4(), name: 'HR Manager', email: 'hr@exemplar.co.za', cellphone: '+27829876543', role: 'manager', lastLogin: '2023-06-14T11:45:00Z', isVerified: true }, { id: uuidv4(), name: 'Department Head', email: 'department@exemplar.co.za', cellphone: '+27835551234', role: 'viewer', lastLogin: '2023-06-10T09:15:00Z', isVerified: true }, { id: uuidv4(), name: 'Equity Analyst', email: 'analyst@exemplar.co.za', cellphone: '+27847778888', role: 'analyst', lastLogin: '2023-06-16T14:20:00Z', isVerified: true } ]; // Employment Equity Types export type Race = 'Black' | 'Coloured' | 'Indian' | 'White' | 'Foreign National'; export type Gender = 'Male' | 'Female' | 'Non-binary'; export type OccupationalLevel = | 'Top Management' | 'Senior Management' | 'Professionally Qualified' | 'Skilled Technical' | 'Semi-skilled' | 'Unskilled' | 'Temporary Employees'; export interface Employee { id: string; firstName: string; lastName: string; idNumber: string; race: Race; gender: Gender; hasDisability: boolean; disabilityDetails?: string; occupationalLevel: OccupationalLevel; department: string; salary: number; joinDate: string; terminationDate?: string; jobTitle?: string; yearsOfExperience?: number; qualifications?: string[]; performanceRating?: number; } export interface CompanyInfo { name: string; registrationNumber: string; industry: string; sectorCode: string; address: string; province: string; contactPerson: string; contactEmail: string; contactPhone: string; employeeCount: number; designatedEmployer: boolean; complianceOfficer: string; complianceOfficerContact: string; } export interface EquityGoal { id: string; occupationalLevel: OccupationalLevel; targetGroup: Race | Gender | 'People with Disabilities'; currentPercentage: number; targetPercentage: number; targetDate: string; notes?: string; } export interface DemographicSummary { occupationalLevel: OccupationalLevel; maleBlack: number; maleColoured: number; maleIndian: number; maleWhite: number; maleForeignNational: number; femaleBlack: number; femaleColoured: number; femaleIndian: number; femaleWhite: number; femaleForeignNational: number; disabledCount: number; total: number; } export interface User { id: string; name: string; email: string; cellphone?: string; role: 'admin' | 'manager' | 'viewer' | 'analyst'; lastLogin?: string; isVerified?: boolean; } export interface BarrierAnalysis { id: string; category: BarrierCategory; description: string; affectedGroups: (Race | Gender | 'People with Disabilities')[]; impact: 'High' | 'Medium' | 'Low'; remedialActions: string[]; timeframe: string; status: 'Identified' | 'In Progress' | 'Completed'; responsiblePerson: string; dateIdentified: string; completionDate?: string; } export type BarrierCategory = | 'Recruitment Procedures' | 'Advertising Positions' | 'Selection Criteria' | 'Appointments' | 'Job Classification' | 'Remuneration' | 'Terms & Conditions' | 'Job Assignments' | 'Work Environment' | 'Training & Development' | 'Performance Evaluation' | 'Promotions' | 'Transfers' | 'Succession Planning' | 'Disciplinary Measures' | 'Company Culture' | 'Reasonable Accommodation' | 'HIV & AIDS Prevention' | 'Other'; export interface PayAnalysis { id: string; occupationalLevel: OccupationalLevel; jobTitle: string; differenceReason?: PayDifferenceReason[]; averageSalaryByRace: Record<Race, number>; averageSalaryByGender: Record<Gender, number>; payGapPercentage: number; justificationNotes?: string; actionPlan?: string; reviewDate: string; } export type PayDifferenceReason = | 'Seniority' | 'Experience' | 'Qualifications' | 'Performance' | 'Scarce Skills' | 'Market Forces' | 'Responsibility Level' | 'Other'; // New types for enhanced functionality export interface BarrierQuestionnaire { id: string; respondentId: string; respondentName: string; respondentEmail: string; respondentCellphone: string; department: string; position: string; dateCompleted: string; responses: QuestionnaireResponse[]; status: 'Draft' | 'Submitted' | 'Reviewed'; } export interface QuestionnaireResponse { questionId: string; question: string; category: BarrierCategory; response: 'Yes' | 'No' | 'Partially' | 'Not Applicable'; comments?: string; severity?: 'Low' | 'Medium' | 'High'; } export interface BarrierQuestion { id: string; category: BarrierCategory; question: string; description?: string; isRequired: boolean; } export interface EconomicActivePopulation { province: string; sectorCode: string; sectorName: string; nationalData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; provincialData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; sectorData: { blackMale: number; blackFemale: number; colouredMale: number; colouredFemale: number; indianMale: number; indianFemale: number; whiteMale: number; whiteFemale: number; total: number; }; } export interface CellphoneVerification { cellphone: string; verificationCode: string; isVerified: boolean; expiresAt: string; } export interface AnalysisResult { id: string; questionnaireId: string; overallScore: number; categoryScores: Record<BarrierCategory, number>; identifiedBarriers: string[]; recommendations: string[]; priorityActions: string[]; complianceRisk: 'Low' | 'Medium' | 'High'; generatedDate: string; } import { BarrierQuestion, BarrierCategory } from '../types'; export const barrierQuestions: BarrierQuestion[] = [ // Recruitment Procedures { id: 'rec_001', category: 'Recruitment Procedures', question: 'Are recruitment procedures documented and consistently applied across all positions?', description: 'Assess whether standardized recruitment processes exist', isRequired: true }, { id: 'rec_002', category: 'Recruitment Procedures', question: 'Do recruitment procedures include specific measures to attract designated groups?', description: 'Evaluate proactive recruitment strategies for equity', isRequired: true }, { id: 'rec_003', category: 'Recruitment Procedures', question: 'Are recruitment sources diverse and include platforms that reach designated groups?', description: 'Check if recruitment channels are inclusive', isRequired: true }, // Advertising Positions { id: 'adv_001', category: 'Advertising Positions', question: 'Are job advertisements placed in media that reach designated groups?', description: 'Assess advertising reach to diverse communities', isRequired: true }, { id: 'adv_002', category: 'Advertising Positions', question: 'Do job advertisements include employment equity statements?', description: 'Check for inclusive language in job postings', isRequired: true }, { id: 'adv_003', category: 'Advertising Positions', question: 'Are job requirements clearly justified and not unnecessarily restrictive?', description: 'Evaluate if requirements create unfair barriers', isRequired: true }, // Selection Criteria { id: 'sel_001', category: 'Selection Criteria', question: 'Are selection criteria job-related and consistently applied?', description: 'Assess fairness and relevance of selection standards', isRequired: true }, { id: 'sel_002', category: 'Selection Criteria', question: 'Do selection panels include diverse representation?', description: 'Check composition of interview panels', isRequired: true }, { id: 'sel_003', category: 'Selection Criteria', question: 'Are unconscious bias training provided to selection panel members?', description: 'Evaluate bias mitigation measures', isRequired: true }, // Appointments { id: 'app_001', category: 'Appointments', question: 'Are appointment decisions documented with clear justifications?', description: 'Assess transparency in hiring decisions', isRequired: true }, { id: 'app_002', category: 'Appointments', question: 'Is preference given to designated group members when candidates are equally qualified?', description: 'Check implementation of affirmative action', isRequired: true }, // Job Classification { id: 'job_001', category: 'Job Classification', question: 'Are job classifications based on objective job evaluation systems?', description: 'Assess fairness in job grading', isRequired: true }, { id: 'job_002', category: 'Job Classification', question: 'Are job classifications regularly reviewed for bias?', description: 'Check for systematic review processes', isRequired: true }, // Remuneration { id: 'rem_001', category: 'Remuneration', question: 'Is there a transparent remuneration policy applied consistently?', description: 'Assess pay equity policies', isRequired: true }, { id: 'rem_002', category: 'Remuneration', question: 'Are regular pay equity analyses conducted?', description: 'Check for systematic pay gap monitoring', isRequired: true }, { id: 'rem_003', category: 'Remuneration', question: 'Are unjustifiable pay differences addressed promptly?', description: 'Evaluate remedial action processes', isRequired: true }, // Terms & Conditions { id: 'terms_001', category: 'Terms & Conditions', question: 'Are terms and conditions of employment applied equally to all employees?', description: 'Assess consistency in employment terms', isRequired: true }, { id: 'terms_002', category: 'Terms & Conditions', question: 'Are flexible work arrangements available to accommodate diverse needs?', description: 'Check for inclusive work policies', isRequired: true }, // Training & Development { id: 'train_001', category: 'Training & Development', question: 'Are training and development opportunities equally accessible to all employees?', description: 'Assess equity in skills development', isRequired: true }, { id: 'train_002', category: 'Training & Development', question: 'Are there specific development programs for designated groups?', description: 'Check for targeted development initiatives', isRequired: true }, { id: 'train_003', category: 'Training & Development', question: 'Is training provided in accessible formats for people with disabilities?', description: 'Evaluate accessibility of training materials', isRequired: true }, // Performance Evaluation { id: 'perf_001', category: 'Performance Evaluation', question: 'Are performance evaluation criteria objective and job-related?', description: 'Assess fairness in performance management', isRequired: true }, { id: 'perf_002', category: 'Performance Evaluation', question: 'Are evaluators trained to avoid bias in performance assessments?', description: 'Check for bias mitigation in evaluations', isRequired: true }, // Promotions { id: 'prom_001', category: 'Promotions', question: 'Are promotion criteria transparent and consistently applied?', description: 'Assess fairness in advancement opportunities', isRequired: true }, { id: 'prom_002', category: 'Promotions', question: 'Are designated group members given preference when equally qualified?', description: 'Check implementation of affirmative action in promotions', isRequired: true }, // Work Environment { id: 'env_001', category: 'Work Environment', question: 'Is the workplace free from discrimination and harassment?', description: 'Assess workplace culture and safety', isRequired: true }, { id: 'env_002', category: 'Work Environment', question: 'Are reasonable accommodations provided for people with disabilities?', description: 'Check accessibility and accommodation measures', isRequired: true }, { id: 'env_003', category: 'Work Environment', question: 'Are cultural and religious practices respected and accommodated?', description: 'Evaluate cultural inclusivity', isRequired: true }, // Company Culture { id: 'culture_001', category: 'Company Culture', question: 'Does leadership demonstrate visible commitment to employment equity?', description: 'Assess leadership engagement in equity initiatives', isRequired: true }, { id: 'culture_002', category: 'Company Culture', question: 'Are diversity and inclusion values embedded in company policies?', description: 'Check integration of equity principles', isRequired: true } ]; export const getQuestionsByCategory = (category: BarrierCategory): BarrierQuestion[] => { return barrierQuestions.filter(q => q.category === category); }; export const getAllCategories = (): BarrierCategory[] => { return Array.from(new Set(barrierQuestions.map(q => q.category))); }; import { EconomicActivePopulation } from '../types'; // Mock data based on Stats SA Quarterly Labour Force Survey export const economicActivePopulationData: EconomicActivePopulation[] = [ { province: 'Gauteng', sectorCode: 'J', sectorName: 'Information and Communication', nationalData: { blackMale: 285000, blackFemale: 195000, colouredMale: 25000, colouredFemale: 18000, indianMale: 35000, indianFemale: 22000, whiteMale: 125000, whiteFemale: 85000, total: 790000 }, provincialData: { blackMale: 95000, blackFemale: 65000, colouredMale: 8000, colouredFemale: 6000, indianMale: 15000, indianFemale: 9000, whiteMale: 45000, whiteFemale: 32000, total: 275000 }, sectorData: { blackMale: 142500, blackFemale: 97500, colouredMale: 12500, colouredFemale: 9000, indianMale: 17500, indianFemale: 11000, whiteMale: 62500, whiteFemale: 42500, total: 395000 } }, { province: 'Western Cape', sectorCode: 'K', sectorName: 'Financial and Insurance Activities', nationalData: { blackMale: 195000, blackFemale: 285000, colouredMale: 45000, colouredFemale: 65000, indianMale: 25000, indianFemale: 35000, whiteMale: 85000, whiteFemale: 125000, total: 860000 }, provincialData: { blackMale: 35000, blackFemale: 52000, colouredMale: 28000, colouredFemale: 42000, indianMale: 8000, indianFemale: 12000, whiteMale: 32000, whiteFemale: 48000, total: 257000 }, sectorData: { blackMale: 97500, blackFemale: 142500, colouredMale: 22500, colouredFemale: 32500, indianMale: 12500, indianFemale: 17500, whiteMale: 42500, whiteFemale: 62500, total: 430000 } }, { province: 'KwaZulu-Natal', sectorCode: 'C', sectorName: 'Manufacturing', nationalData: { blackMale: 850000, blackFemale: 425000, colouredMale: 95000, colouredFemale: 48000, indianMale: 65000, indianFemale: 32000, whiteMale: 125000, whiteFemale: 62000, total: 1702000 }, provincialData: { blackMale: 185000, blackFemale: 92000, colouredMale: 12000, colouredFemale: 6000, indianMale: 35000, indianFemale: 18000, whiteMale: 25000, whiteFemale: 12000, total: 385000 }, sectorData: { blackMale: 425000, blackFemale: 212500, colouredMale: 47500, colouredFemale: 24000, indianMale: 32500, indianFemale: 16000, whiteMale: 62500, whiteFemale: 31000, total: 851000 } } ]; export const getEconomicDataByProvince = (province: string): EconomicActivePopulation[] => { return economicActivePopulationData.filter(data => data.province === province); }; export const getEconomicDataBySector = (sectorCode: string): EconomicActivePopulation[] => { return economicActivePopulationData.filter(data => data.sectorCode === sectorCode); }; export const getAllProvinces = (): string[] => { return Array.from(new Set(economicActivePopulationData.map(data => data.province))); }; export const getAllSectors = (): { code: string; name: string }[] => { const sectors = new Map(); economicActivePopulationData.forEach(data => { sectors.set(data.sectorCode, data.sectorName); }); return Array.from(sectors.entries()).map(([code, name]) => ({ code, name })); }; import { BarrierQuestionnaire, QuestionnaireResponse, AnalysisResult, BarrierCategory } from '../types'; import { barrierQuestions } from './barrierQuestions'; export const analyzeQuestionnaire = (questionnaire: BarrierQuestionnaire): AnalysisResult => { const categoryScores: Record<BarrierCategory, number> = {} as Record<BarrierCategory, number>; const identifiedBarriers: string[] = []; const recommendations: string[] = []; const priorityActions: string[] = []; // Initialize category scores const categories = Array.from(new Set(barrierQuestions.map(q => q.category))); categories.forEach(category => { categoryScores[category] = 0; }); // Calculate scores by category categories.forEach(category => { const categoryResponses = questionnaire.responses.filter(r => r.category === category); const categoryQuestions = barrierQuestions.filter(q => q.category === category); if (categoryQuestions.length === 0) return; let categoryScore = 0; let totalPossible = categoryQuestions.length * 100; categoryResponses.forEach(response => { switch (response.response) { case 'Yes': categoryScore += 100; break; case 'Partially': categoryScore += 50; if (response.severity === 'High') { identifiedBarriers.push(`${category}: ${response.question}`); priorityActions.push(`Address partial compliance in ${category}`); } break; case 'No': categoryScore += 0; identifiedBarriers.push(`${category}: ${response.question}`); if (response.severity === 'High') { priorityActions.push(`Urgent action required: ${response.question}`); } break; case 'Not Applicable': totalPossible -= 100; break; } }); categoryScores[category] = totalPossible > 0 ? Math.round((categoryScore / totalPossible) * 100) : 100; }); // Calculate overall score const validScores = Object.values(categoryScores).filter(score => score >= 0); const overallScore = validScores.length > 0 ? Math.round(validScores.reduce((sum, score) => sum + score, 0) / validScores.length) : 0; // Generate recommendations based on scores Object.entries(categoryScores).forEach(([category, score]) => { if (score < 70) { recommendations.push(generateRecommendation(category as BarrierCategory, score)); } }); // Determine compliance risk let complianceRisk: 'Low' | 'Medium' | 'High' = 'Low'; if (overallScore < 60) { complianceRisk = 'High'; } else if (overallScore < 80) { complianceRisk = 'Medium'; } return { id: `analysis_${Date.now()}`, questionnaireId: questionnaire.id, overallScore, categoryScores, identifiedBarriers, recommendations, priorityActions, complianceRisk, generatedDate: new Date().toISOString() }; }; const generateRecommendation = (category: BarrierCategory, score: number): string => { const recommendations: Record<BarrierCategory, string> = { 'Recruitment Procedures': 'Develop standardized, inclusive recruitment procedures with clear documentation and training for hiring managers.', 'Advertising Positions': 'Expand job advertising to diverse media channels and include employment equity statements in all job postings.', 'Selection Criteria': 'Review and validate selection criteria for job-relatedness and implement diverse interview panels.', 'Appointments': 'Establish clear appointment decision documentation and implement affirmative action preferences.', 'Job Classification': 'Implement objective job evaluation systems and conduct regular bias reviews of job classifications.', 'Remuneration': 'Develop transparent pay policies and conduct regular pay equity analyses with remedial action plans.', 'Terms & Conditions': 'Ensure consistent application of employment terms and implement flexible work arrangements.', 'Job Assignments': 'Review job assignment processes for fairness and eliminate discriminatory practices.', 'Work Environment': 'Create inclusive workplace policies and provide reasonable accommodations for all employees.', 'Training & Development': 'Ensure equal access to development opportunities and create targeted programs for designated groups.', 'Performance Evaluation': 'Implement objective performance criteria and provide bias training for evaluators.', 'Promotions': 'Establish transparent promotion criteria and implement affirmative action in advancement decisions.', 'Transfers': 'Develop fair transfer policies that consider employee development and organizational needs.', 'Succession Planning': 'Create inclusive succession planning that identifies and develops diverse talent.', 'Disciplinary Measures': 'Ensure consistent and fair application of disciplinary procedures across all employee groups.', 'Company Culture': 'Foster inclusive leadership and embed diversity values in organizational policies and practices.', 'Reasonable Accommodation': 'Develop comprehensive accommodation policies and ensure accessibility in all workplace aspects.', 'HIV & AIDS Prevention': 'Implement non-discriminatory HIV/AIDS policies and provide education and support programs.', 'Other': 'Address specific barriers identified through targeted interventions and policy development.' }; return recommendations[category] || 'Implement targeted interventions to address identified barriers.'; }; export const generateComplianceReport = (analysis: AnalysisResult): string => { return ` Employment Equity Barrier Analysis Report Overall Compliance Score: ${analysis.overallScore}% Compliance Risk Level: ${analysis.complianceRisk} Category Breakdown: ${Object.entries(analysis.categoryScores) .map(([category, score]) => `- ${category}: ${score}%`) .join('\n')} Identified Barriers (${analysis.identifiedBarriers.length}): ${analysis.identifiedBarriers.map(barrier => `- ${barrier}`).join('\n')} Priority Actions Required: ${analysis.priorityActions.map(action => `- ${action}`).join('\n')} Recommendations: ${analysis.recommendations.map(rec => `- ${rec}`).join('\n')} Generated: ${new Date(analysis.generatedDate).toLocaleDateString()} `.trim(); }; import React, { useState, useEffect } from 'react'; import { CheckCircle, AlertTriangle, FileText, Send } from 'lucide-react'; import Button from '../common/Button'; import Card from '../common/Card'; import { BarrierQuestionnaire as BarrierQuestionnaireType, QuestionnaireResponse, BarrierCategory } from '../../types'; import { barrierQuestions, getAllCategories } from '../../utils/barrierQuestions'; import { v4 as uuidv4 } from 'uuid'; interface BarrierQuestionnaireProps { respondentName: string; respondentEmail: string; respondentCellphone: string; // Keep for compatibility but not used onSubmit: (questionnaire: BarrierQuestionnaireType) => void; onSaveDraft?: (questionnaire: BarrierQuestionnaireType) => void; } const BarrierQuestionnaire: React.FC<BarrierQuestionnaireProps> = ({ respondentName, respondentEmail, respondentCellphone, onSubmit, onSaveDraft }) => { const [currentCategory, setCurrentCategory] = useState<BarrierCategory>('Recruitment Procedures'); const [responses, setResponses] = useState<QuestionnaireResponse[]>([]); const [department, setDepartment] = useState(''); const [position, setPosition] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); const categories = getAllCategories(); const currentQuestions = barrierQuestions.filter(q => q.category === currentCategory); const currentCategoryIndex = categories.indexOf(currentCategory); const isLastCategory = currentCategoryIndex === categories.length - 1; // Initialize responses for current category useEffect(() => { const categoryResponses = responses.filter(r => r.category === currentCategory); const missingQuestions = currentQuestions.filter( q => !categoryResponses.find(r => r.questionId === q.id) ); if (missingQuestions.length > 0) { const newResponses = missingQuestions.map(q => ({ questionId: q.id, question: q.question, category: q.category, response: 'Not Applicable' as const, comments: '', severity: 'Medium' as const })); setResponses(prev => [...prev, ...newResponses]); } }, [currentCategory, currentQuestions, responses]); const handleResponseChange = ( questionId: string, field: keyof QuestionnaireResponse, value: string ) => { setResponses(prev => prev.map(response => response.questionId === questionId ? { ...response, [field]: value } : response )); }; const getResponseForQuestion = (questionId: string): QuestionnaireResponse | undefined => { return responses.find(r => r.questionId === questionId); }; const getCategoryProgress = (category: BarrierCategory): number => { const categoryQuestions = barrierQuestions.filter(q => q.category === category); const categoryResponses = responses.filter(r => r.category === category); const answeredQuestions = categoryResponses.filter(r => r.response !== 'Not Applicable'); return categoryQuestions.length > 0 ? Math.round((answeredQuestions.length / categoryQuestions.length) * 100) : 0; }; const getOverallProgress = (): number => { const totalQuestions = barrierQuestions.length; const answeredQuestions = responses.filter(r => r.response !== 'Not Applicable').length; return totalQuestions > 0 ? Math.round((answeredQuestions / totalQuestions) * 100) : 0; }; const handleNextCategory = () => { if (!isLastCategory) { setCurrentCategory(categories[currentCategoryIndex + 1]); } }; const handlePreviousCategory = () => { if (currentCategoryIndex > 0) { setCurrentCategory(categories[currentCategoryIndex - 1]); } }; const handleSubmit = async () => { if (!department || !position) { alert('Please fill in your department and position'); return; } setIsSubmitting(true); const questionnaire: BarrierQuestionnaireType = { id: uuidv4(), respondentId: uuidv4(), respondentName, respondentEmail, respondentCellphone: '', // No longer required department, position, dateCompleted: new Date().toISOString(), responses, status: 'Submitted' }; try { await onSubmit(questionnaire); } finally { setIsSubmitting(false); } }; const handleSaveDraft = () => { if (!onSaveDraft) return; const questionnaire: BarrierQuestionnaireType = { id: uuidv4(), respondentId: uuidv4(), respondentName, respondentEmail, respondentCellphone: '', // No longer required department, position, dateCompleted: new Date().toISOString(), responses, status: 'Draft' }; onSaveDraft(questionnaire); }; return ( <div className="space-y-6"> {/* Progress Overview */} <Card title="Barrier Analysis Questionnaire"> <div className="space-y-4"> <div className="flex justify-between items-center"> <h3 className="text-lg font-medium text-gray-900">Overall Progress</h3> <span className="text-sm font-medium text-emerald-600"> {getOverallProgress()}% Complete </span> </div> <div className="w-full bg-gray-200 rounded-full h-2"> <div className="bg-emerald-600 h-2 rounded-full transition-all duration-300" style={{ width: `${getOverallProgress()}%` }} /> </div> {/* Respondent Information */} <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t"> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" id="department" value={department} onChange={(e) => setDepartment(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your department" /> </div> <div> <label htmlFor="position" className="block text-sm font-medium text-gray-700"> Position/Job Title * </label> <input type="text" id="position" value={position} onChange={(e) => setPosition(e.target.value)} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your position" /> </div> </div> </div> </Card> {/* Category Navigation */} <Card title="Categories"> <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3"> {categories.map((category, index) => { const progress = getCategoryProgress(category); const isActive = category === currentCategory; return ( <button key={category} onClick={() => setCurrentCategory(category)} className={`p-3 rounded-lg border text-left transition-colors ${ isActive ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-gray-200 hover:border-gray-300' }`} > <div className="flex items-center justify-between mb-2"> <span className="text-xs font-medium"> {index + 1}. {category} </span> {progress === 100 && ( <CheckCircle className="h-4 w-4 text-green-500" /> )} </div> <div className="w-full bg-gray-200 rounded-full h-1"> <div className="bg-emerald-600 h-1 rounded-full transition-all duration-300" style={{ width: `${progress}%` }} /> </div> </button> ); })} </div> </Card> {/* Current Category Questions */} <Card title={`${currentCategoryIndex + 1}. ${currentCategory}`}> <div className="space-y-6"> {currentQuestions.map((question, index) => { const response = getResponseForQuestion(question.id); return ( <div key={question.id} className="border border-gray-200 rounded-lg p-4"> <div className="space-y-4"> <div> <h4 className="text-sm font-medium text-gray-900 mb-2"> {index + 1}. {question.question} {question.isRequired && <span className="text-red-500 ml-1">*</span>} </h4> {question.description && ( <p className="text-sm text-gray-600 mb-3">{question.description}</p> )} </div> <div className="grid grid-cols-2 md:grid-cols-4 gap-3"> {['Yes', 'No', 'Partially', 'Not Applicable'].map((option) => ( <label key={option} className="inline-flex items-center"> <input type="radio" name={`question_${question.id}`} value={option} checked={response?.response === option} onChange={(e) => handleResponseChange(question.id, 'response', e.target.value)} className="h-4 w-4 text-emerald-600 border-gray-300 focus:ring-emerald-500" /> <span className="ml-2 text-sm text-gray-700">{option}</span> </label> ))} </div> {response?.response === 'No' || response?.response === 'Partially' ? ( <div className="space-y-3"> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Severity Level </label> <select value={response.severity || 'Medium'} onChange={(e) => handleResponseChange(question.id, 'severity', e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > <option value="Low">Low</option> <option value="Medium">Medium</option> <option value="High">High</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-1"> Comments (Optional) </label> <textarea value={response.comments || ''} onChange={(e) => handleResponseChange(question.id, 'comments', e.target.value)} rows={2} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Provide additional details about this barrier..." /> </div> </div> ) : null} </div> </div> ); })} </div> {/* Navigation */} <div className="flex justify-between items-center mt-6 pt-6 border-t"> <Button variant="outline" onClick={handlePreviousCategory} disabled={currentCategoryIndex === 0} > Previous </Button> <div className="flex space-x-3"> {onSaveDraft && ( <Button variant="outline" onClick={handleSaveDraft} icon={<FileText className="w-4 h-4" />} > Save Draft </Button> )} {isLastCategory ? ( <Button onClick={handleSubmit} isLoading={isSubmitting} icon={<Send className="w-4 h-4" />} disabled={!department || !position} > Submit Questionnaire </Button> ) : ( <Button onClick={handleNextCategory}> Next </Button> )} </div> </div> </Card> </div> ); }; export default BarrierQuestionnaire; import React from 'react'; import { BarChart, AlertTriangle, CheckCircle, TrendingUp, Download } from 'lucide-react'; import Card from '../common/Card'; import Button from '../common/Button'; import { AnalysisResult, BarrierCategory } from '../../types'; import { generateComplianceReport } from '../../utils/analysisEngine'; interface AnalysisResultsProps { analysis: AnalysisResult; onDownloadReport?: () => void; } const AnalysisResults: React.FC<AnalysisResultsProps> = ({ analysis, onDownloadReport }) => { const getRiskColor = (risk: string) => { switch (risk) { case 'High': return 'text-red-600 bg-red-100'; case 'Medium': return 'text-amber-600 bg-amber-100'; case 'Low': return 'text-green-600 bg-green-100'; default: return 'text-gray-600 bg-gray-100'; } }; const getScoreColor = (score: number) => { if (score >= 80) return 'text-green-600'; if (score >= 60) return 'text-amber-600'; return 'text-red-600'; }; const getScoreIcon = (score: number) => { if (score >= 80) return <CheckCircle className="h-5 w-5 text-green-500" />; if (score >= 60) return <AlertTriangle className="h-5 w-5 text-amber-500" />; return <AlertTriangle className="h-5 w-5 text-red-500" />; }; return ( <div className="space-y-6"> {/* Overall Score */} <Card title="Analysis Results"> <div className="grid grid-cols-1 md:grid-cols-3 gap-6"> <div className="text-center"> <div className="flex items-center justify-center mb-2"> {getScoreIcon(analysis.overallScore)} </div> <div className={`text-3xl font-bold ${getScoreColor(analysis.overallScore)}`}> {analysis.overallScore}% </div> <p className="text-sm text-gray-500">Overall Compliance Score</p> </div> <div className="text-center"> <div className="flex items-center justify-center mb-2"> <AlertTriangle className="h-5 w-5 text-amber-500" /> </div> <div className="text-3xl font-bold text-gray-900"> {analysis.identifiedBarriers.length} </div> <p className="text-sm text-gray-500">Barriers Identified</p> </div> <div className="text-center"> <div className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${getRiskColor(analysis.complianceRisk)}`}> {analysis.complianceRisk} Risk </div> <p className="text-sm text-gray-500 mt-2">Compliance Risk Level</p> </div> </div> <div className="mt-6 flex justify-end"> <Button onClick={onDownloadReport} icon={<Download className="w-4 h-4" />} variant="outline" > Download Report </Button> </div> </Card> {/* Category Scores */} <Card title="Category Breakdown"> <div className="space-y-4"> {Object.entries(analysis.categoryScores).map(([category, score]) => ( <div key={category} className="flex items-center justify-between"> <div className="flex-1"> <div className="flex items-center justify-between mb-1"> <span className="text-sm font-medium text-gray-900">{category}</span> <span className={`text-sm font-medium ${getScoreColor(score)}`}> {score}% </span> </div> <div className="w-full bg-gray-200 rounded-full h-2"> <div className={`h-2 rounded-full transition-all duration-300 ${ score >= 80 ? 'bg-green-500' : score >= 60 ? 'bg-amber-500' : 'bg-red-500' }`} style={{ width: `${score}%` }} /> </div> </div> </div> ))} </div> </Card> {/* Priority Actions */} {analysis.priorityActions.length > 0 && ( <Card title="Priority Actions Required"> <div className="space-y-3"> {analysis.priorityActions.map((action, index) => ( <div key={index} className="flex items-start"> <div className="flex-shrink-0 h-5 w-5 rounded-full bg-red-100 flex items-center justify-center mr-3 mt-0.5"> <span className="text-xs font-medium text-red-600">{index + 1}</span> </div> <p className="text-sm text-gray-700">{action}</p> </div> ))} </div> </Card> )} {/* Identified Barriers */} {analysis.identifiedBarriers.length > 0 && ( <Card title="Identified Barriers"> <div className="space-y-2"> {analysis.identifiedBarriers.map((barrier, index) => ( <div key={index} className="flex items-start"> <AlertTriangle className="h-4 w-4 text-amber-500 mr-2 mt-0.5 flex-shrink-0" /> <p className="text-sm text-gray-700">{barrier}</p> </div> ))} </div> </Card> )} {/* Recommendations */} <Card title="Recommendations"> <div className="space-y-4"> {analysis.recommendations.map((recommendation, index) => ( <div key={index} className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <TrendingUp className="h-5 w-5 text-blue-600 mr-3 mt-0.5 flex-shrink-0" /> <p className="text-sm text-blue-700">{recommendation}</p> </div> </div> ))} </div> </Card> {/* Compliance Summary */} <Card title="Compliance Summary"> <div className="bg-gray-50 rounded-lg p-4"> <pre className="text-xs text-gray-700 whitespace-pre-wrap font-mono"> {generateComplianceReport(analysis)} </pre> </div> </Card> </div> ); }; export default AnalysisResults; import React, { useState } from 'react'; import { BarChart3, Users, TrendingUp } from 'lucide-react'; import Card from '../common/Card'; import { EconomicActivePopulation } from '../../types'; import { economicActivePopulationData, getAllProvinces, getAllSectors } from '../../utils/economicActivePopulation'; const EconomicActivePopulationView: React.FC = () => { const [selectedProvince, setSelectedProvince] = useState<string>('All'); const [selectedSector, setSelectedSector] = useState<string>('All'); const provinces = ['All', ...getAllProvinces()]; const sectors = [{ code: 'All', name: 'All Sectors' }, ...getAllSectors()]; const filteredData = economicActivePopulationData.filter(data => { const provinceMatch = selectedProvince === 'All' || data.province === selectedProvince; const sectorMatch = selectedSector === 'All' || data.sectorCode === selectedSector; return provinceMatch && sectorMatch; }); const calculateTotals = (data: EconomicActivePopulation[]) => { return data.reduce((acc, curr) => ({ nationalData: { blackMale: acc.nationalData.blackMale + curr.nationalData.blackMale, blackFemale: acc.nationalData.blackFemale + curr.nationalData.blackFemale, colouredMale: acc.nationalData.colouredMale + curr.nationalData.colouredMale, colouredFemale: acc.nationalData.colouredFemale + curr.nationalData.colouredFemale, indianMale: acc.nationalData.indianMale + curr.nationalData.indianMale, indianFemale: acc.nationalData.indianFemale + curr.nationalData.indianFemale, whiteMale: acc.nationalData.whiteMale + curr.nationalData.whiteMale, whiteFemale: acc.nationalData.whiteFemale + curr.nationalData.whiteFemale, total: acc.nationalData.total + curr.nationalData.total }, provincialData: { blackMale: acc.provincialData.blackMale + curr.provincialData.blackMale, blackFemale: acc.provincialData.blackFemale + curr.provincialData.blackFemale, colouredMale: acc.provincialData.colouredMale + curr.provincialData.colouredMale, colouredFemale: acc.provincialData.colouredFemale + curr.provincialData.colouredFemale, indianMale: acc.provincialData.indianMale + curr.provincialData.indianMale, indianFemale: acc.provincialData.indianFemale + curr.provincialData.indianFemale, whiteMale: acc.provincialData.whiteMale + curr.provincialData.whiteMale, whiteFemale: acc.provincialData.whiteFemale + curr.provincialData.whiteFemale, total: acc.provincialData.total + curr.provincialData.total }, sectorData: { blackMale: acc.sectorData.blackMale + curr.sectorData.blackMale, blackFemale: acc.sectorData.blackFemale + curr.sectorData.blackFemale, colouredMale: acc.sectorData.colouredMale + curr.sectorData.colouredMale, colouredFemale: acc.sectorData.colouredFemale + curr.sectorData.colouredFemale, indianMale: acc.sectorData.indianMale + curr.sectorData.indianMale, indianFemale: acc.sectorData.indianFemale + curr.sectorData.indianFemale, whiteMale: acc.sectorData.whiteMale + curr.sectorData.whiteMale, whiteFemale: acc.sectorData.whiteFemale + curr.sectorData.whiteFemale, total: acc.sectorData.total + curr.sectorData.total } }), { nationalData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 }, provincialData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 }, sectorData: { blackMale: 0, blackFemale: 0, colouredMale: 0, colouredFemale: 0, indianMale: 0, indianFemale: 0, whiteMale: 0, whiteFemale: 0, total: 0 } }); }; const totals = calculateTotals(filteredData); const formatNumber = (num: number) => num.toLocaleString(); const calculatePercentage = (value: number, total: number) => { return total > 0 ? ((value / total) * 100).toFixed(1) : '0.0'; }; return ( <div className="space-y-6"> {/* Filters */} <Card title="Economic Active Population Analysis"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6"> <div> <label htmlFor="province" className="block text-sm font-medium text-gray-700 mb-1"> Province </label> <select id="province" value={selectedProvince} onChange={(e) => setSelectedProvince(e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {provinces.map(province => ( <option key={province} value={province}>{province}</option> ))} </select> </div> <div> <label htmlFor="sector" className="block text-sm font-medium text-gray-700 mb-1"> Sector </label> <select id="sector" value={selectedSector} onChange={(e) => setSelectedSector(e.target.value)} className="block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" > {sectors.map(sector => ( <option key={sector.code} value={sector.code}> {sector.code !== 'All' ? `${sector.code} - ${sector.name}` : sector.name} </option> ))} </select> </div> </div> <div className="bg-blue-50 border border-blue-200 rounded-md p-4"> <div className="flex"> <Users className="h-5 w-5 text-blue-600 mr-3 mt-0.5" /> <div> <h3 className="text-sm font-medium text-blue-800">About Economic Active Population Data</h3> <p className="text-sm text-blue-700 mt-1"> This data is based on Statistics South Africa's Quarterly Labour Force Survey and represents the economically active population by race, gender, province, and economic sector. Use this data to set realistic employment equity targets based on labour market availability. </p> </div> </div> </div> </Card> {/* National Data */} <Card title="National Economic Active Population"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Demographic Group </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Count </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Percentage </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Black Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.blackMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.blackMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Black Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.blackFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.blackFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Coloured Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.colouredMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.colouredMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Coloured Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.colouredFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.colouredFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Indian Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.indianMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.indianMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">Indian Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.indianFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.indianFemale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">White Male</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.whiteMale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.whiteMale, totals.nationalData.total)}% </td> </tr> <tr> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">White Female</td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(totals.nationalData.whiteFemale)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {calculatePercentage(totals.nationalData.whiteFemale, totals.nationalData.total)}% </td> </tr> <tr className="bg-gray-50"> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">Total</td> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 text-right"> {formatNumber(totals.nationalData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 text-right"> 100.0% </td> </tr> </tbody> </table> </div> </Card> {/* Provincial and Sector Comparison */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <Card title={`Provincial Data${selectedProvince !== 'All' ? ` - ${selectedProvince}` : ''}`}> <div className="space-y-3"> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Black (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.blackMale + totals.provincialData.blackFemale)} ({calculatePercentage(totals.provincialData.blackMale + totals.provincialData.blackFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Coloured (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.colouredMale + totals.provincialData.colouredFemale)} ({calculatePercentage(totals.provincialData.colouredMale + totals.provincialData.colouredFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Indian (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.indianMale + totals.provincialData.indianFemale)} ({calculatePercentage(totals.provincialData.indianMale + totals.provincialData.indianFemale, totals.provincialData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">White (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.provincialData.whiteMale + totals.provincialData.whiteFemale)} ({calculatePercentage(totals.provincialData.whiteMale + totals.provincialData.whiteFemale, totals.provincialData.total)}%) </span> </div> <div className="pt-2 border-t border-gray-200"> <div className="flex justify-between items-center"> <span className="text-sm font-medium text-gray-900">Total Provincial</span> <span className="text-sm font-bold text-gray-900"> {formatNumber(totals.provincialData.total)} </span> </div> </div> </div> </Card> <Card title={`Sector Data${selectedSector !== 'All' ? ` - ${sectors.find(s => s.code === selectedSector)?.name}` : ''}`}> <div className="space-y-3"> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Black (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.blackMale + totals.sectorData.blackFemale)} ({calculatePercentage(totals.sectorData.blackMale + totals.sectorData.blackFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Coloured (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.colouredMale + totals.sectorData.colouredFemale)} ({calculatePercentage(totals.sectorData.colouredMale + totals.sectorData.colouredFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">Indian (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.indianMale + totals.sectorData.indianFemale)} ({calculatePercentage(totals.sectorData.indianMale + totals.sectorData.indianFemale, totals.sectorData.total)}%) </span> </div> <div className="flex justify-between items-center"> <span className="text-sm text-gray-600">White (Male + Female)</span> <span className="text-sm font-medium"> {formatNumber(totals.sectorData.whiteMale + totals.sectorData.whiteFemale)} ({calculatePercentage(totals.sectorData.whiteMale + totals.sectorData.whiteFemale, totals.sectorData.total)}%) </span> </div> <div className="pt-2 border-t border-gray-200"> <div className="flex justify-between items-center"> <span className="text-sm font-medium text-gray-900">Total Sector</span> <span className="text-sm font-bold text-gray-900"> {formatNumber(totals.sectorData.total)} </span> </div> </div> </div> </Card> </div> {/* Detailed Breakdown */} {filteredData.length > 0 && ( <Card title="Detailed Breakdown by Location and Sector"> <div className="overflow-x-auto"> <table className="min-w-full divide-y divide-gray-200"> <thead className="bg-gray-50"> <tr> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Province </th> <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"> Sector </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> National Total </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Provincial Total </th> <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"> Sector Total </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {filteredData.map((data, index) => ( <tr key={index}> <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> {data.province} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {data.sectorCode} - {data.sectorName} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.nationalData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.provincialData.total)} </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-right"> {formatNumber(data.sectorData.total)} </td> </tr> ))} </tbody> </table> </div> </Card> )} </div> ); }; export default EconomicActivePopulationView; import React, { useState } from 'react'; import { ClipboardList, Users, BarChart3, Download } from 'lucide-react'; import Button from '../components/common/Button'; import Card from '../components/common/Card'; import BarrierQuestionnaire from '../components/questionnaire/BarrierQuestionnaire'; import AnalysisResults from '../components/analysis/AnalysisResults'; import EconomicActivePopulationView from '../components/analysis/EconomicActivePopulationView'; import { BarrierQuestionnaire as BarrierQuestionnaireType, AnalysisResult } from '../types'; import { analyzeQuestionnaire, generateComplianceReport } from '../utils/analysisEngine'; const BarrierAnalysisPage: React.FC = () => { const [currentStep, setCurrentStep] = useState<'questionnaire' | 'results' | 'population'>('questionnaire'); const [respondentInfo, setRespondentInfo] = useState({ name: '', email: '', department: '', position: '' }); const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null); const [activeTab, setActiveTab] = useState<'questionnaire' | 'population'>('questionnaire'); const handleQuestionnaireSubmit = (questionnaire: BarrierQuestionnaireType) => { // Analyze the questionnaire const analysis = analyzeQuestionnaire(questionnaire); setAnalysisResult(analysis); setCurrentStep('results'); }; const handleDownloadReport = () => { if (!analysisResult) return; const report = generateComplianceReport(analysisResult); const blob = new Blob([report], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `barrier-analysis-report-${new Date().toISOString().split('T')[0]}.txt`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; const renderStepContent = () => { switch (currentStep) { case 'questionnaire': return ( <div className="max-w-4xl mx-auto"> <div className="text-center mb-8"> <ClipboardList className="mx-auto h-16 w-16 text-emerald-600 mb-4" /> <h1 className="text-3xl font-bold text-gray-900 mb-2"> Employment Equity Barrier Analysis </h1> <p className="text-lg text-gray-600"> Complete our comprehensive questionnaire to identify potential barriers to employment equity in your organization. </p> </div> <Card title="Get Started"> <div className="space-y-4 mb-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <label htmlFor="name" className="block text-sm font-medium text-gray-700"> Full Name * </label> <input type="text" id="name" value={respondentInfo.name} onChange={(e) => setRespondentInfo(prev => ({ ...prev, name: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your full name" /> </div> <div> <label htmlFor="email" className="block text-sm font-medium text-gray-700"> Email Address * </label> <input type="email" id="email" value={respondentInfo.email} onChange={(e) => setRespondentInfo(prev => ({ ...prev, email: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your email address" /> </div> <div> <label htmlFor="department" className="block text-sm font-medium text-gray-700"> Department * </label> <input type="text" id="department" value={respondentInfo.department} onChange={(e) => setRespondentInfo(prev => ({ ...prev, department: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your department" /> </div> <div> <label htmlFor="position" className="block text-sm font-medium text-gray-700"> Position/Job Title * </label> <input type="text" id="position" value={respondentInfo.position} onChange={(e) => setRespondentInfo(prev => ({ ...prev, position: e.target.value }))} className="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500 sm:text-sm" placeholder="Enter your position" /> </div> </div> {respondentInfo.name && respondentInfo.email && respondentInfo.department && respondentInfo.position && ( <div className="mt-6"> <Button onClick={() => { // Start the questionnaire directly setCurrentStep('questionnaire'); }} icon={<ClipboardList className="w-4 h-4" />} fullWidth > Start Barrier Analysis Questionnaire </Button> </div> )} </div> </Card> {respondentInfo.name && respondentInfo.email && respondentInfo.department && respondentInfo.position && ( <BarrierQuestionnaire respondentName={respondentInfo.name} respondentEmail={respondentInfo.email} respondentCellphone="" // No longer required onSubmit={handleQuestionnaireSubmit} /> )} </div> ); case 'results': return analysisResult ? ( <AnalysisResults analysis={analysisResult} onDownloadReport={handleDownloadReport} /> ) : null; default: return null; } }; if (currentStep === 'questionnaire' || currentStep === 'results') { return ( <div className="space-y-6"> {/* Navigation */} {currentStep !== 'questionnaire' && ( <div className="flex justify-between items-center"> <Button variant="outline" onClick={() => { if (currentStep === 'results') { setCurrentStep('questionnaire'); } }} > Back </Button> <div className="flex space-x-4"> <Button variant={activeTab === 'questionnaire' ? 'primary' : 'outline'} onClick={() => setActiveTab('questionnaire')} icon={<ClipboardList className="w-4 h-4" />} > Barrier Analysis </Button> <Button variant={activeTab === 'population' ? 'primary' : 'outline'} onClick={() => { setActiveTab('population'); setCurrentStep('population'); }} icon={<Users className="w-4 h-4" />} > Economic Active Population </Button> </div> </div> )} {renderStepContent()} </div> ); } return ( <div className="space-y-6"> {/* Page Header */} <div className="flex justify-between items-center"> <div> <h1 className="text-2xl font-bold text-gray-900">Employment Equity Analysis</h1> <p className="mt-1 text-sm text-gray-500"> Comprehensive barrier analysis and economic active population data </p> </div> <div className="flex space-x-4"> <Button variant={activeTab === 'questionnaire' ? 'primary' : 'outline'} onClick={() => { setActiveTab('questionnaire'); setCurrentStep('questionnaire'); }} icon={<ClipboardList className="w-4 h-4" />} > Barrier Analysis </Button> <Button variant={activeTab === 'population' ? 'primary' : 'outline'} onClick={() => setActiveTab('population')} icon={<Users className="w-4 h-4" />} > Economic Active Population </Button> </div> </div> {/* Content */} {activeTab === 'population' && <EconomicActivePopulationView />} </div> ); }; export default BarrierAnalysisPage; import React, { useEffect } from 'react'; import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { AppProvider, useAppContext } from './contexts/AppContext'; import Header from './components/layout/Header'; import DashboardPage from './pages/DashboardPage'; import EmployeesPage from './pages/EmployeesPage'; import ReportsPage from './pages/ReportsPage'; import GoalsPage from './pages/GoalsPage'; import LoginPage from './pages/LoginPage'; import BarrierAnalysisPage from './pages/BarrierAnalysisPage'; // Protected route component const ProtectedRoute: React.FC<{children: React.ReactNode}> = ({ children }) => { const { currentUser } = useAppContext(); const location = useLocation(); if (!currentUser) { // Redirect to login if not authenticated return <Navigate to="/login\" state={{ from: location }} replace />; } import React, { useState, useEffect } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { Menu, X, UserCircle, LogOut, ChevronDown } from 'lucide-react'; import { useAppContext } from '../../contexts/AppContext'; const Header: React.FC = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const [isUserMenuOpen, setIsUserMenuOpen] = useState(false); const [scrolled, setScrolled] = useState(false); const { currentUser, logout } = useAppContext(); const location = useLocation(); // Handle scroll effect for header useEffect(() => { const handleScroll = () => { if (window.scrollY > 10) { setScrolled(true); } else { setScrolled(false); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); // Close mobile menu when route changes useEffect(() => { setIsMenuOpen(false); }, [location]); return ( <header className={`fixed top-0 left-0 right-0 z-10 transition-all duration-300 ${ scrolled ? 'bg-white shadow-md py-2' : 'bg-transparent py-4' }`} > <div className="container mx-auto px-4 sm:px-6 lg:px-8"> <div className="flex justify-between items-center"> {/* Logo */} <Link to="/" className="flex items-center"> <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white font-bold text-xl mr-2"> EE </div> <span className="text-xl font-bold text-gray-800">EquityTool</span> </Link> {/* Desktop Navigation */} <nav className="hidden md:flex space-x-8"> <NavLink to="/" active={location.pathname === '/'}>Dashboard</NavLink> <NavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</NavLink> <NavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</NavLink> <NavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</NavLink> <NavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</NavLink> </nav> {/* User Menu (Desktop) */} <div className="hidden md:flex items-center"> {currentUser ? ( <div className="relative"> <button className="flex items-center space-x-2 text-gray-700 hover:text-emerald-600 focus:outline-none" onClick={() => setIsUserMenuOpen(!isUserMenuOpen)} > <UserCircle className="w-6 h-6" /> <span>{currentUser.name}</span> <ChevronDown className={`w-4 h-4 transition-transform ${isUserMenuOpen ? 'rotate-180' : ''}`} /> </button> {isUserMenuOpen && ( <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20"> <div className="px-4 py-2 text-sm text-gray-500 border-b"> Logged in as <span className="font-semibold">{currentUser.role}</span> </div> <Link to="/profile" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" onClick={() => setIsUserMenuOpen(false)} > Profile Settings </Link> <button className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsUserMenuOpen(false); }} > <div className="flex items-center"> <LogOut className="w-4 h-4 mr-2" /> Sign Out </div> </button> </div> )} </div> ) : ( <Link to="/login" className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-emerald-600 hover:bg-emerald-700" > Sign In </Link> )} </div> {/* Mobile Menu Button */} <button className="md:hidden text-gray-700 focus:outline-none" onClick={() => setIsMenuOpen(!isMenuOpen)} > {isMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />} </button> </div> </div> {/* Mobile Menu */} {isMenuOpen && ( <div className="md:hidden bg-white border-t shadow-lg"> <div className="px-2 pt-2 pb-3 space-y-1"> <MobileNavLink to="/" active={location.pathname === '/'}>Dashboard</MobileNavLink> <MobileNavLink to="/employees" active={location.pathname.startsWith('/employees')}>Employees</MobileNavLink> <MobileNavLink to="/reports" active={location.pathname.startsWith('/reports')}>Reports</MobileNavLink> <MobileNavLink to="/goals" active={location.pathname.startsWith('/goals')}>Goals</MobileNavLink> <MobileNavLink to="/barrier-analysis" active={location.pathname.startsWith('/barrier-analysis')}>Barrier Analysis</MobileNavLink> </div> {/* User Menu (Mobile) */} <div className="px-5 pt-4 pb-3 border-t border-gray-200"> {currentUser ? ( <> <div className="flex items-center mb-3"> <div className="flex-shrink-0"> <UserCircle className="w-10 h-10 text-gray-400" /> </div> <div className="ml-3"> <div className="text-base font-medium text-gray-800">{currentUser.name}</div> <div className="text-sm font-medium text-gray-500">{currentUser.email}</div> </div> </div> <div className="space-y-1"> <Link to="/profile" className="block px-3 py-2 rounded-md text-base font-medium text-gray-700 hover:bg-gray-100" > Profile Settings </Link> <button className="block w-full text-left px-3 py-2 rounded-md text-base font-medium text-red-600 hover:bg-gray-100" onClick={() => { logout(); setIsMenuOpen(false); }} > Sign Out </button> </div> </> ) : ( <Link to="/login" className="block w-full px-5 py-3 text-center font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-md" > Sign In </Link> )} </div> </div> )} </header> ); }; interface NavLinkProps { to: string; active: boolean; children: React.ReactNode; } const NavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`relative px-2 py-1 transition-colors ${ active ? 'text-emerald-600 font-medium' : 'text-gray-600 hover:text-emerald-600' }`} > {children} {active && ( <span className="absolute bottom-0 left-0 w-full h-0.5 bg-emerald-600 rounded-full"></span> )} </Link> ); }; const MobileNavLink: React.FC<NavLinkProps> = ({ to, active, children }) => { return ( <Link to={to} className={`block px-3 py-2 rounded-md text-base font-medium ${ active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-700 hover:bg-gray-50 hover:text-emerald-600' }`} > {children} </Link> ); }; export default Header; import { Employee, CompanyInfo, EquityGoal, DemographicSummary, User } from '../types'; import { v4 as uuidv4 } from 'uuid'; // Mock Company Information - Updated for 2024 legislation export const mockCompanyInfo: CompanyInfo = { name: 'Exemplar Holdings', registrationNumber: '2010/123456/07', industry: 'Financial Services', sectorCode: 'K', address: '123 Main Street, Sandton, Johannesburg, 2196', province: 'Gauteng', contactPerson: 'Jane Smith', contactEmail: 'jane.smith@exemplar.co.za', contactPhone: '011 123 4567', employeeCount: 245, designatedEmployer: true, complianceOfficer: 'John Doe', complianceOfficerContact: 'john.doe@exemplar.co.za' }; // Mock Employees export const mockEmployees: Employee[] = [ { id: uuidv4(), firstName: 'Thabo', lastName: 'Mbeki', idNumber: '7501015800082', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Top Management', department: 'Executive', salary: 1200000, joinDate: '2020-01-15' }, { id: uuidv4(), firstName: 'Sarah', lastName: 'Johnson', idNumber: '8012045800082', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Senior Management', department: 'Finance', salary: 850000, joinDate: '2019-04-12' }, { id: uuidv4(), firstName: 'Lerato', lastName: 'Nkosi', idNumber: '8909235800083', race: 'Black', gender: 'Female', hasDisability: true, disabilityDetails: 'Hearing impairment', occupationalLevel: 'Professionally Qualified', department: 'Human Resources', salary: 620000, joinDate: '2018-06-01' }, { id: uuidv4(), firstName: 'Ahmed', lastName: 'Patel', idNumber: '7705125800084', race: 'Indian', gender: 'Male', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 450000, joinDate: '2021-03-15' }, { id: uuidv4(), firstName: 'Jessica', lastName: 'De Villiers', idNumber: '9012055800086', race: 'White', gender: 'Female', hasDisability: false, occupationalLevel: 'Professionally Qualified', department: 'Marketing', salary: 580000, joinDate: '2019-11-01' }, { id: uuidv4(), firstName: 'Sipho', lastName: 'Ndlovu', idNumber: '8504175800087', race: 'Black', gender: 'Male', hasDisability: false, occupationalLevel: 'Semi-skilled', department: 'Operations', salary: 320000, joinDate: '2020-08-15' }, { id: uuidv4(), firstName: 'Fatima', lastName: 'Mohammed', idNumber: '9108235800088', race: 'Indian', gender: 'Female', hasDisability: false, occupationalLevel: 'Skilled Technical', department: 'IT', salary: 470000, joinDate: '2019-05-20' }, { id: uuidv4(), firstName: 'James', lastName: 'Wilson', idNumber: '8306155800089', race: 'Coloured', gender: 'Male', hasDisability: true, disabilityDetails: 'Mobility impairment', occupationalLevel: 'Skilled Technical', department: 'Finance', salary: 420000, joinDate: '2018-10-10' } ]; // Mock Equity Goals export const mockEquityGoals: EquityGoal[] = [ { id: uuidv4(), occupationalLevel: 'Top Management', targetGroup: 'Black', currentPercentage: 25, targetPercentage: 50, targetDate: '2025-12-31', notes: 'Focus on internal promotions and external recruitment' }, { id: uuidv4(), occupationalLevel: 'Senior Management', targetGroup: 'Female', currentPercentage: 30, targetPercentage: 45, targetDate: '2024-12-31', notes: 'Implement mentorship program to prepare for promotions' }, { id: uuidv4(), occupationalLevel: 'Professionally Qualified', targetGroup: 'People with Disabilities', currentPercentage: 2, targetPercentage: 7, targetDate: '2025-06-30', notes: 'Improve workplace accessibility and targeted recruitment' } ]; // Mock Demographic Summary export const mockDemographicSummary: DemographicSummary[] = [ { occupationalLevel: 'Top Management', maleBlack: 1, maleColoured: 0, maleIndian: 0, maleWhite: 3, maleForeignNational: 0, femaleBlack: 0, femaleColoured: 0, femaleIndian: 0, femaleWhite: 1, femaleForeignNational: 0, disabledCount: 0, total: 5 }, { occupationalLevel: 'Senior Management', maleBlack: 2, maleColoured: 1, maleIndian: 1, maleWhite: 5, maleForeignNational: 1, femaleBlack: 1, femaleColoured: 1, femaleIndian: 0, femaleWhite: 3, femaleForeignNational: 0, disabledCount: 1, total: 15 }, { occupationalLevel: 'Professionally Qualified', maleBlack: 15, maleColoured: 6, maleIndian: 8, maleWhite: 12, maleForeignNational: 2, femaleBlack: 12, femaleColoured: 5, femaleIndian: 7, femaleWhite: 10, femaleForeignNational: 1, disabledCount: 4, total: 78 }, { occupationalLevel: 'Skilled Technical', maleBlack: 25, maleColoured: 8, maleIndian: 6, maleWhite: 10, maleForeignNational: 3, femaleBlack: 18, femaleColoured: 7, femaleIndian: 5, femaleWhite: 8, femaleForeignNational: 2, disabledCount: 5, total: 92 }, { occupationalLevel: 'Semi-skilled', maleBlack: 18, maleColoured: 5, maleIndian: 2, maleWhite: 3, maleForeignNational: 4, femaleBlack: 12, femaleColoured: 3, femaleIndian: 1, femaleWhite: 2, femaleForeignNational: 0, disabledCount: 2, total: 50 }, { occupationalLevel: 'Unskilled', maleBlack: 3, maleColoured: 0, maleIndian: 0, maleWhite: 0, maleForeignNational: 0, femaleBlack: 2, femaleColoured: 0, femaleIndian: 0, femaleWhite: 0, femaleForeignNational: 0, disabledCount: 0, total: 5 } ]; // Mock Users - Updated with analyst role export const mockUsers: User[] = [ { id: uuidv4(), name: 'Admin User', email: 'admin@exemplar.co.za', cellphone: '+27821234567', role: 'admin', lastLogin: '2023-06-15T08:30:00Z', isVerified: true }, { id: uuidv4(), name: 'HR Manager', email: 'hr@exemplar.co.za', cellphone: '+27829876543', role: 'manager', lastLogin: '2023-06-14T11:45:00Z', isVerified: true }, { id: uuidv4(), name: 'Department Head', email: 'department@exemplar.co.za', cellphone: '+27835551234', role: 'viewer', lastLogin: '2023-06-10T09:15:00Z', isVerified: true }, { id: uuidv4(), name: 'Equity Analyst', email: 'analyst@exemplar.co.za', cellphone: '+27847778888', role: 'analyst', lastLogin: '2023-06-16T14:20:00Z', isVerified: true } ]; - Initial Deployment
- 388 Bytes initial commit