(Feat-Fix): Lots of fixes done, reporting system fixed, stricter types

This commit is contained in:
2025-12-19 18:48:05 +00:00
parent 01400ad4e1
commit 865e0bf00e
61 changed files with 10072 additions and 6645 deletions

View File

@@ -1,46 +1,56 @@
import React, { useState } from 'react';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { Sidebar } from './components/layout/Sidebar';
import { Header } from './components/layout/Header';
import { DashboardPage } from './pages/DashboardPage';
import { UsersPage } from './pages/UsersPage';
import { WorkAllocationPage } from './pages/WorkAllocationPage';
import { AttendancePage } from './pages/AttendancePage';
import { RatesPage } from './pages/RatesPage';
import { EmployeeSwapPage } from './pages/EmployeeSwapPage';
import { LoginPage } from './pages/LoginPage';
import { ReportingPage } from './pages/ReportingPage';
import { StandardRatesPage } from './pages/StandardRatesPage';
import { AllRatesPage } from './pages/AllRatesPage';
import { ActivitiesPage } from './pages/ActivitiesPage';
import React, { useState } from "react";
import { AuthProvider, useAuth } from "./contexts/AuthContext.tsx";
import { Sidebar } from "./components/layout/Sidebar.tsx";
import { Header } from "./components/layout/Header.tsx";
import { DashboardPage } from "./pages/DashboardPage.tsx";
import { UsersPage } from "./pages/UsersPage.tsx";
import { WorkAllocationPage } from "./pages/WorkAllocationPage.tsx";
import { AttendancePage } from "./pages/AttendancePage.tsx";
import { RatesPage } from "./pages/RatesPage.tsx";
import { EmployeeSwapPage } from "./pages/EmployeeSwapPage.tsx";
import { LoginPage } from "./pages/LoginPage.tsx";
import { ReportingPage } from "./pages/ReportingPage.tsx";
import { StandardRatesPage } from "./pages/StandardRatesPage.tsx";
import { AllRatesPage } from "./pages/AllRatesPage.tsx";
import { ActivitiesPage } from "./pages/ActivitiesPage.tsx";
type PageType = 'dashboard' | 'users' | 'allocation' | 'attendance' | 'rates' | 'swaps' | 'reports' | 'standard-rates' | 'all-rates' | 'activities';
type PageType =
| "dashboard"
| "users"
| "allocation"
| "attendance"
| "rates"
| "swaps"
| "reports"
| "standard-rates"
| "all-rates"
| "activities";
const AppContent: React.FC = () => {
const [activePage, setActivePage] = useState<PageType>('dashboard');
const [activePage, setActivePage] = useState<PageType>("dashboard");
const { isAuthenticated, isLoading } = useAuth();
const renderPage = () => {
switch (activePage) {
case 'dashboard':
case "dashboard":
return <DashboardPage />;
case 'users':
case "users":
return <UsersPage />;
case 'allocation':
case "allocation":
return <WorkAllocationPage />;
case 'attendance':
case "attendance":
return <AttendancePage />;
case 'rates':
case "rates":
return <RatesPage />;
case 'swaps':
case "swaps":
return <EmployeeSwapPage />;
case 'reports':
case "reports":
return <ReportingPage />;
case 'standard-rates':
case "standard-rates":
return <StandardRatesPage />;
case 'all-rates':
case "all-rates":
return <AllRatesPage />;
case 'activities':
case "activities":
return <ActivitiesPage />;
default:
return <DashboardPage />;
@@ -52,7 +62,8 @@ const AppContent: React.FC = () => {
return (
<div className="flex h-screen items-center justify-center bg-gray-100">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4">
</div>
<p className="text-gray-600">Loading...</p>
</div>
</div>
@@ -67,11 +78,14 @@ const AppContent: React.FC = () => {
// Show main app if authenticated
return (
<div className="flex h-screen bg-gray-100">
<Sidebar activePage={activePage} onNavigate={(page) => setActivePage(page as PageType)} />
<Sidebar
activePage={activePage}
onNavigate={(page) => setActivePage(page as PageType)}
/>
<div className="flex-1 flex flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto">
{renderPage()}
</main>
@@ -88,4 +102,4 @@ function App() {
);
}
export default App;
export default App;

View File

@@ -1 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
role="img"
class="iconify iconify--logos"
width="35.93"
height="32"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 256 228"
>
<path
fill="#00D8FF"
d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"
></path>
</svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

View File

@@ -1,9 +1,24 @@
import React, { useState, useEffect } from 'react';
import { Bell, LogOut, X, Camera, Shield, User, Mail, Building2, ChevronDown, ChevronUp, Phone, CreditCard, Landmark, FileText } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { useDepartments } from '../../hooks/useDepartments';
import { api } from '../../services/api';
import type { User as UserType } from '../../types';
import React, { useEffect, useState } from "react";
import {
Bell,
Building2,
Camera,
ChevronDown,
ChevronUp,
CreditCard,
FileText,
Landmark,
LogOut,
Mail,
Phone,
Shield,
User,
X,
} from "lucide-react";
import { useAuth } from "../../contexts/AuthContext.tsx";
import { useDepartments } from "../../hooks/useDepartments.ts";
import { api } from "../../services/api.ts";
import type { User as UserType } from "../../types.ts";
interface ProfilePopupProps {
isOpen: boolean;
@@ -12,47 +27,52 @@ interface ProfilePopupProps {
}
// Permission definitions for each role
const rolePermissions: Record<string, { title: string; permissions: string[] }> = {
const rolePermissions: Record<
string,
{ title: string; permissions: string[] }
> = {
Supervisor: {
title: 'Supervisor Permissions',
title: "Supervisor Permissions",
permissions: [
'View and manage employees in your department',
'Create and manage work allocations',
'Set contractor rates for your department',
'View attendance records',
'Manage check-in/check-out for employees',
]
"View and manage employees in your department",
"Create and manage work allocations",
"Set contractor rates for your department",
"View attendance records",
"Manage check-in/check-out for employees",
],
},
Employee: {
title: 'Employee Permissions',
title: "Employee Permissions",
permissions: [
'View your work allocations',
'View your attendance records',
'Check-in and check-out',
'View assigned tasks',
]
"View your work allocations",
"View your attendance records",
"Check-in and check-out",
"View assigned tasks",
],
},
Contractor: {
title: 'Contractor Permissions',
title: "Contractor Permissions",
permissions: [
'View assigned work allocations',
'View your rate configurations',
'Track work completion status',
]
"View assigned work allocations",
"View your rate configurations",
"Track work completion status",
],
},
SuperAdmin: {
title: 'Super Admin Permissions',
title: "Super Admin Permissions",
permissions: [
'Full system access',
'Manage all users and departments',
'Configure all contractor rates',
'View all work allocations and reports',
'System configuration and settings',
]
}
"Full system access",
"Manage all users and departments",
"Configure all contractor rates",
"View all work allocations and reports",
"System configuration and settings",
],
},
};
const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }) => {
const ProfilePopup: React.FC<ProfilePopupProps> = (
{ isOpen, onClose, onLogout },
) => {
const { user } = useAuth();
const { departments } = useDepartments();
const [showPermissions, setShowPermissions] = useState(false);
@@ -68,10 +88,11 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
if (!isOpen) return null;
const userDepartment = departments.find(d => d.id === user?.department_id);
const userPermissions = rolePermissions[user?.role || 'Employee'];
const isEmployeeOrContractor = user?.role === 'Employee' || user?.role === 'Contractor';
const isContractor = user?.role === 'Contractor';
const userDepartment = departments.find((d) => d.id === user?.department_id);
const userPermissions = rolePermissions[user?.role || "Employee"];
const isEmployeeOrContractor = user?.role === "Employee" ||
user?.role === "Contractor";
const isContractor = user?.role === "Contractor";
return (
<div className="absolute right-4 top-16 w-[400px] bg-gradient-to-b from-slate-50 to-white rounded-2xl shadow-2xl z-50 border border-gray-200 overflow-hidden font-sans text-sm text-gray-800 max-h-[85vh] overflow-y-auto">
@@ -79,22 +100,27 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<div className="bg-gradient-to-r from-teal-600 to-teal-500 px-6 py-4">
<div className="flex justify-between items-start">
<div className="flex-1" />
<button onClick={onClose} className="text-white/80 hover:text-white hover:bg-white/20 rounded-full p-1 transition-colors">
<button
onClick={onClose}
className="text-white/80 hover:text-white hover:bg-white/20 rounded-full p-1 transition-colors"
>
<X size={20} />
</button>
</div>
<div className="flex flex-col items-center -mt-2">
<div className="relative mb-3">
<div className="w-20 h-20 bg-white rounded-full flex items-center justify-center text-teal-600 text-4xl font-bold shadow-lg">
{user?.name?.charAt(0).toUpperCase() || 'U'}
{user?.name?.charAt(0).toUpperCase() || "U"}
</div>
<div className="absolute bottom-0 right-0 bg-teal-700 rounded-full p-1.5 shadow-md cursor-pointer hover:bg-teal-800 transition-colors">
<Camera size={12} className="text-white" />
</div>
</div>
<h3 className="text-xl text-white font-semibold">Hi, {user?.name || 'User'}!</h3>
<h3 className="text-xl text-white font-semibold">
Hi, {user?.name || "User"}!
</h3>
<span className="mt-1 px-3 py-1 bg-white/20 text-white text-xs font-semibold rounded-full uppercase tracking-wider">
{user?.role || 'User'}
{user?.role || "User"}
</span>
</div>
</div>
@@ -107,7 +133,9 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
</div>
<div>
<p className="text-xs text-gray-500 font-medium">Username</p>
<p className="text-sm font-semibold text-gray-800">{user?.username || 'N/A'}</p>
<p className="text-sm font-semibold text-gray-800">
{user?.username || "N/A"}
</p>
</div>
</div>
@@ -117,18 +145,22 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
</div>
<div className="flex-1 min-w-0">
<p className="text-xs text-gray-500 font-medium">Email</p>
<p className="text-sm font-semibold text-gray-800 truncate">{user?.email || 'No email'}</p>
<p className="text-sm font-semibold text-gray-800 truncate">
{user?.email || "No email"}
</p>
</div>
</div>
{user?.role !== 'SuperAdmin' && userDepartment && (
{user?.role !== "SuperAdmin" && userDepartment && (
<div className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
<div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
<Building2 size={18} className="text-green-600" />
</div>
<div>
<p className="text-xs text-gray-500 font-medium">Department</p>
<p className="text-sm font-semibold text-gray-800">{userDepartment.name}</p>
<p className="text-sm font-semibold text-gray-800">
{userDepartment.name}
</p>
</div>
</div>
)}
@@ -144,11 +176,17 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<CreditCard size={18} className="text-teal-600" />
</div>
<div className="text-left">
<p className="text-xs text-gray-500 font-medium">Personal & Bank Details</p>
<p className="text-sm font-semibold text-gray-800">View your information</p>
<p className="text-xs text-gray-500 font-medium">
Personal & Bank Details
</p>
<p className="text-sm font-semibold text-gray-800">
View your information
</p>
</div>
</div>
{showDetails ? <ChevronUp size={18} className="text-teal-600" /> : <ChevronDown size={18} className="text-teal-600" />}
{showDetails
? <ChevronUp size={18} className="text-teal-600" />
: <ChevronDown size={18} className="text-teal-600" />}
</button>
)}
@@ -162,14 +200,16 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-600">Phone Number</span>
<span className="font-medium text-gray-800">{fullUserData.phone_number || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.phone_number || "Not provided"}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">Aadhar Number</span>
<span className="font-medium text-gray-800">
{fullUserData.aadhar_number
? `XXXX-XXXX-${fullUserData.aadhar_number.slice(-4)}`
: 'Not provided'}
{fullUserData.aadhar_number
? `XXXX-XXXX-${fullUserData.aadhar_number.slice(-4)}`
: "Not provided"}
</span>
</div>
</div>
@@ -183,19 +223,23 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-600">Bank Name</span>
<span className="font-medium text-gray-800">{fullUserData.bank_name || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.bank_name || "Not provided"}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">Account Number</span>
<span className="font-medium text-gray-800">
{fullUserData.bank_account_number
? `XXXX${fullUserData.bank_account_number.slice(-4)}`
: 'Not provided'}
{fullUserData.bank_account_number
? `XXXX${fullUserData.bank_account_number.slice(-4)}`
: "Not provided"}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">IFSC Code</span>
<span className="font-medium text-gray-800">{fullUserData.bank_ifsc || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.bank_ifsc || "Not provided"}
</span>
</div>
</div>
</div>
@@ -209,15 +253,22 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-600">Agreement No.</span>
<span className="font-medium text-gray-800">{fullUserData.contractor_agreement_number || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.contractor_agreement_number ||
"Not provided"}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">PF Number</span>
<span className="font-medium text-gray-800">{fullUserData.pf_number || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.pf_number || "Not provided"}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-600">ESIC Number</span>
<span className="font-medium text-gray-800">{fullUserData.esic_number || 'Not provided'}</span>
<span className="font-medium text-gray-800">
{fullUserData.esic_number || "Not provided"}
</span>
</div>
</div>
</div>
@@ -235,19 +286,30 @@ const ProfilePopup: React.FC<ProfilePopupProps> = ({ isOpen, onClose, onLogout }
<Shield size={18} className="text-amber-600" />
</div>
<div className="text-left">
<p className="text-xs text-gray-500 font-medium">Your Permissions</p>
<p className="text-sm font-semibold text-gray-800">View what you can do</p>
<p className="text-xs text-gray-500 font-medium">
Your Permissions
</p>
<p className="text-sm font-semibold text-gray-800">
View what you can do
</p>
</div>
</div>
{showPermissions ? <ChevronUp size={18} className="text-amber-600" /> : <ChevronDown size={18} className="text-amber-600" />}
{showPermissions
? <ChevronUp size={18} className="text-amber-600" />
: <ChevronDown size={18} className="text-amber-600" />}
</button>
{showPermissions && userPermissions && (
<div className="bg-amber-50 rounded-xl p-4 border border-amber-200">
<h4 className="font-semibold text-amber-800 mb-2">{userPermissions.title}</h4>
<h4 className="font-semibold text-amber-800 mb-2">
{userPermissions.title}
</h4>
<ul className="space-y-2">
{userPermissions.permissions.map((perm, idx) => (
<li key={idx} className="flex items-start gap-2 text-sm text-amber-700">
<li
key={idx}
className="flex items-start gap-2 text-sm text-amber-700"
>
<span className="text-amber-500 mt-0.5"></span>
{perm}
</li>
@@ -284,18 +346,21 @@ export const Header: React.FC = () => {
<header className="bg-white border-b border-gray-200 px-6 py-4 relative">
<div className="flex items-center justify-between">
<div className="flex-1">
<h1 className="text-2xl font-bold text-gray-800">Work Allocation System</h1>
<h1 className="text-2xl font-bold text-gray-800">
Work Allocation System
</h1>
</div>
<div className="flex items-center space-x-4">
<button className="p-2 text-gray-600 hover:bg-gray-100 rounded-full relative">
<Bell size={20} />
<span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
<span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full">
</span>
</button>
<button
onClick={() => setIsProfileOpen(!isProfileOpen)}
className="w-10 h-10 bg-teal-600 rounded-full flex items-center justify-center text-white font-medium hover:bg-teal-700"
>
{user?.name?.charAt(0).toUpperCase() || 'U'}
{user?.name?.charAt(0).toUpperCase() || "U"}
</button>
</div>
</div>

View File

@@ -1,6 +1,18 @@
import React from 'react';
import { LayoutDashboard, Users, Briefcase, CalendarCheck, DollarSign, ClipboardList, ArrowRightLeft, FileSpreadsheet, Scale, Eye, Layers } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import React from "react";
import {
ArrowRightLeft,
Briefcase,
CalendarCheck,
ClipboardList,
DollarSign,
Eye,
FileSpreadsheet,
Layers,
LayoutDashboard,
Scale,
Users,
} from "lucide-react";
import { useAuth } from "../../contexts/AuthContext.tsx";
interface SidebarItemProps {
icon: React.ElementType;
@@ -9,13 +21,15 @@ interface SidebarItemProps {
onClick: () => void;
}
const SidebarItem: React.FC<SidebarItemProps> = ({ icon: Icon, label, active, onClick }) => (
const SidebarItem: React.FC<SidebarItemProps> = (
{ icon: Icon, label, active, onClick },
) => (
<button
onClick={onClick}
className={`w-full flex items-center space-x-3 px-6 py-4 cursor-pointer transition-colors duration-200 outline-none focus:outline-none ${
active
? 'bg-blue-900 border-l-4 border-blue-400 text-white'
: 'text-gray-400 hover:bg-gray-800 hover:text-white border-l-4 border-transparent'
? "bg-blue-900 border-l-4 border-blue-400 text-white"
: "text-gray-400 hover:bg-gray-800 hover:text-white border-l-4 border-transparent"
}`}
>
<Icon size={20} />
@@ -30,11 +44,11 @@ interface SidebarProps {
export const Sidebar: React.FC<SidebarProps> = ({ activePage, onNavigate }) => {
const { user } = useAuth();
const isSuperAdmin = user?.role === 'SuperAdmin';
const isSupervisor = user?.role === 'Supervisor';
const isContractor = user?.role === 'Contractor';
const isEmployee = user?.role === 'Employee';
const isSuperAdmin = user?.role === "SuperAdmin";
const isSupervisor = user?.role === "Supervisor";
const isContractor = user?.role === "Contractor";
const isEmployee = user?.role === "Employee";
// Role-based access
const canManageUsers = isSuperAdmin || isSupervisor;
const canManageAllocations = isSuperAdmin || isSupervisor;
@@ -49,7 +63,9 @@ export const Sidebar: React.FC<SidebarProps> = ({ activePage, onNavigate }) => {
<ClipboardList size={24} className="text-white" />
</div>
<div>
<h1 className="text-white text-lg font-bold tracking-wide">Work Allocation</h1>
<h1 className="text-white text-lg font-bold tracking-wide">
Work Allocation
</h1>
<p className="text-gray-400 text-xs">Management System</p>
</div>
</div>
@@ -59,111 +75,120 @@ export const Sidebar: React.FC<SidebarProps> = ({ activePage, onNavigate }) => {
<SidebarItem
icon={LayoutDashboard}
label="Dashboard"
active={activePage === 'dashboard'}
onClick={() => onNavigate('dashboard')}
active={activePage === "dashboard"}
onClick={() => onNavigate("dashboard")}
/>
{/* User Management - SuperAdmin and Supervisor only */}
{canManageUsers && (
<SidebarItem
icon={Users}
label="User Management"
active={activePage === 'users'}
onClick={() => onNavigate('users')}
active={activePage === "users"}
onClick={() => onNavigate("users")}
/>
)}
{/* Work Allocation - SuperAdmin and Supervisor only */}
{canManageAllocations && (
<SidebarItem
icon={Briefcase}
label="Work Allocation"
active={activePage === 'allocation'}
onClick={() => onNavigate('allocation')}
active={activePage === "allocation"}
onClick={() => onNavigate("allocation")}
/>
)}
{/* Attendance - SuperAdmin and Supervisor only */}
{canManageAttendance && (
<SidebarItem
icon={CalendarCheck}
label="Attendance"
active={activePage === 'attendance'}
onClick={() => onNavigate('attendance')}
active={activePage === "attendance"}
onClick={() => onNavigate("attendance")}
/>
)}
{/* Contractor Rates - SuperAdmin and Supervisor only */}
{canManageRates && (
<SidebarItem
icon={DollarSign}
label="Contractor Rates"
active={activePage === 'rates'}
onClick={() => onNavigate('rates')}
active={activePage === "rates"}
onClick={() => onNavigate("rates")}
/>
)}
{/* Employee Swap - SuperAdmin only */}
{isSuperAdmin && (
<SidebarItem
icon={ArrowRightLeft}
label="Employee Swap"
active={activePage === 'swaps'}
onClick={() => onNavigate('swaps')}
active={activePage === "swaps"}
onClick={() => onNavigate("swaps")}
/>
)}
{/* Reports - SuperAdmin and Supervisor */}
{canManageRates && (
<SidebarItem
icon={FileSpreadsheet}
label="Reports"
active={activePage === 'reports'}
onClick={() => onNavigate('reports')}
active={activePage === "reports"}
onClick={() => onNavigate("reports")}
/>
)}
{/* Standard Rates - SuperAdmin and Supervisor */}
{canManageRates && (
<SidebarItem
icon={Scale}
label="Standard Rates"
active={activePage === 'standard-rates'}
onClick={() => onNavigate('standard-rates')}
active={activePage === "standard-rates"}
onClick={() => onNavigate("standard-rates")}
/>
)}
{/* All Rates View - SuperAdmin only */}
{isSuperAdmin && (
<SidebarItem
icon={Eye}
label="All Rates"
active={activePage === 'all-rates'}
onClick={() => onNavigate('all-rates')}
active={activePage === "all-rates"}
onClick={() => onNavigate("all-rates")}
/>
)}
{/* Activities Management - SuperAdmin and Supervisor */}
{(isSuperAdmin || isSupervisor) && (
<SidebarItem
icon={Layers}
label="Activities"
active={activePage === 'activities'}
onClick={() => onNavigate('activities')}
active={activePage === "activities"}
onClick={() => onNavigate("activities")}
/>
)}
</nav>
{/* Role indicator at bottom */}
<div className="p-4 border-t border-gray-700">
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Logged in as</div>
<div className={`text-sm font-medium ${
isSuperAdmin ? 'text-purple-400' :
isSupervisor ? 'text-blue-400' :
isContractor ? 'text-orange-400' :
isEmployee ? 'text-green-400' : 'text-gray-400'
}`}>
{user?.role || 'Unknown'}
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">
Logged in as
</div>
<div
className={`text-sm font-medium ${
isSuperAdmin
? "text-purple-400"
: isSupervisor
? "text-blue-400"
: isContractor
? "text-orange-400"
: isEmployee
? "text-green-400"
: "text-gray-400"
}`}
>
{user?.role || "Unknown"}
</div>
</div>
</div>

View File

@@ -1,40 +1,45 @@
import React, { ReactNode, ButtonHTMLAttributes } from 'react';
import React, { ButtonHTMLAttributes, ReactNode } from "react";
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
size?: 'sm' | 'md' | 'lg';
variant?: "primary" | "secondary" | "danger" | "ghost";
size?: "sm" | "md" | "lg";
fullWidth?: boolean;
}
export const Button: React.FC<ButtonProps> = ({
children,
variant = 'primary',
size = 'md',
variant = "primary",
size = "md",
fullWidth = false,
className = '',
className = "",
...props
}) => {
const baseStyles = 'inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2';
const baseStyles =
"inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2";
const variantStyles = {
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-500',
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-red-500',
ghost: 'bg-transparent border border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-gray-500',
primary: "bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",
secondary:
"bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-500",
danger: "bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",
ghost:
"bg-transparent border border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-gray-500",
};
const sizeStyles = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-sm',
lg: 'px-6 py-3 text-base',
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2 text-sm",
lg: "px-6 py-3 text-base",
};
const widthStyle = fullWidth ? 'w-full' : '';
const widthStyle = fullWidth ? "w-full" : "";
return (
<button
className={`${baseStyles} ${variantStyles[variant]} ${sizeStyles[size]} ${widthStyle} ${className}`}
className={`${baseStyles} ${variantStyles[variant]} ${
sizeStyles[size]
} ${widthStyle} ${className}`}
{...props}
>
{children}

View File

@@ -1,11 +1,11 @@
import React, { ReactNode } from 'react';
import React, { ReactNode } from "react";
interface CardProps {
children: ReactNode;
className?: string;
}
export const Card: React.FC<CardProps> = ({ children, className = '' }) => {
export const Card: React.FC<CardProps> = ({ children, className = "" }) => {
return (
<div className={`bg-white rounded-lg shadow-sm ${className}`}>
{children}
@@ -19,9 +19,13 @@ interface CardHeaderProps {
className?: string;
}
export const CardHeader: React.FC<CardHeaderProps> = ({ title, action, className = '' }) => {
export const CardHeader: React.FC<CardHeaderProps> = (
{ title, action, className = "" },
) => {
return (
<div className={`flex justify-between items-center p-6 border-b border-gray-200 ${className}`}>
<div
className={`flex justify-between items-center p-6 border-b border-gray-200 ${className}`}
>
<h2 className="text-xl font-semibold text-gray-800">{title}</h2>
{action && <div>{action}</div>}
</div>
@@ -33,6 +37,8 @@ interface CardContentProps {
className?: string;
}
export const CardContent: React.FC<CardContentProps> = ({ children, className = '' }) => {
export const CardContent: React.FC<CardContentProps> = (
{ children, className = "" },
) => {
return <div className={`p-6 ${className}`}>{children}</div>;
};

View File

@@ -1,5 +1,5 @@
import React, { InputHTMLAttributes, useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
import React, { InputHTMLAttributes, useState } from "react";
import { Eye, EyeOff } from "lucide-react";
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string;
@@ -7,7 +7,9 @@ interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
required?: boolean;
}
export const Input: React.FC<InputProps> = ({ label, error, required, className = '', disabled, ...props }) => {
export const Input: React.FC<InputProps> = (
{ label, error, required, className = "", disabled, ...props },
) => {
return (
<div className="w-full">
{label && (
@@ -17,8 +19,10 @@ export const Input: React.FC<InputProps> = ({ label, error, required, className
)}
<input
className={`w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
error ? 'border-red-500' : ''
} ${disabled ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : ''} ${className}`}
error ? "border-red-500" : ""
} ${
disabled ? "bg-gray-100 text-gray-600 cursor-not-allowed" : ""
} ${className}`}
disabled={disabled}
{...props}
/>
@@ -27,13 +31,16 @@ export const Input: React.FC<InputProps> = ({ label, error, required, className
);
};
interface PasswordInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'type'> {
interface PasswordInputProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, "type"> {
label?: string;
error?: string;
required?: boolean;
}
export const PasswordInput: React.FC<PasswordInputProps> = ({ label, error, required, className = '', disabled, ...props }) => {
export const PasswordInput: React.FC<PasswordInputProps> = (
{ label, error, required, className = "", disabled, ...props },
) => {
const [showPassword, setShowPassword] = useState(false);
return (
@@ -45,10 +52,12 @@ export const PasswordInput: React.FC<PasswordInputProps> = ({ label, error, requ
)}
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
type={showPassword ? "text" : "password"}
className={`w-full px-4 py-2 pr-10 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
error ? 'border-red-500' : ''
} ${disabled ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : ''} ${className}`}
error ? "border-red-500" : ""
} ${
disabled ? "bg-gray-100 text-gray-600 cursor-not-allowed" : ""
} ${className}`}
disabled={disabled}
{...props}
/>
@@ -73,7 +82,9 @@ interface SelectProps extends InputHTMLAttributes<HTMLSelectElement> {
options: { value: string; label: string }[];
}
export const Select: React.FC<SelectProps> = ({ label, error, required, options, className = '', disabled, ...props }) => {
export const Select: React.FC<SelectProps> = (
{ label, error, required, options, className = "", disabled, ...props },
) => {
return (
<div className="w-full">
{label && (
@@ -83,8 +94,10 @@ export const Select: React.FC<SelectProps> = ({ label, error, required, options,
)}
<select
className={`w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
error ? 'border-red-500' : ''
} ${disabled ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : ''} ${className}`}
error ? "border-red-500" : ""
} ${
disabled ? "bg-gray-100 text-gray-600 cursor-not-allowed" : ""
} ${className}`}
disabled={disabled}
{...props}
>
@@ -106,7 +119,9 @@ interface TextAreaProps extends InputHTMLAttributes<HTMLTextAreaElement> {
rows?: number;
}
export const TextArea: React.FC<TextAreaProps> = ({ label, error, required, rows = 3, className = '', ...props }) => {
export const TextArea: React.FC<TextAreaProps> = (
{ label, error, required, rows = 3, className = "", ...props },
) => {
return (
<div className="w-full">
{label && (
@@ -117,7 +132,7 @@ export const TextArea: React.FC<TextAreaProps> = ({ label, error, required, rows
<textarea
rows={rows}
className={`w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent ${
error ? 'border-red-500' : ''
error ? "border-red-500" : ""
} ${className}`}
{...props}
/>

View File

@@ -1,11 +1,11 @@
import React, { ReactNode } from 'react';
import React, { ReactNode } from "react";
interface TableProps {
children: ReactNode;
className?: string;
}
export const Table: React.FC<TableProps> = ({ children, className = '' }) => {
export const Table: React.FC<TableProps> = ({ children, className = "" }) => {
return (
<div className="overflow-x-auto">
<table className={`w-full ${className}`}>{children}</table>
@@ -39,11 +39,15 @@ interface TableRowProps {
className?: string;
}
export const TableRow: React.FC<TableRowProps> = ({ children, onClick, className = '' }) => {
export const TableRow: React.FC<TableRowProps> = (
{ children, onClick, className = "" },
) => {
return (
<tr
onClick={onClick}
className={`border-b border-gray-100 hover:bg-gray-50 ${onClick ? 'cursor-pointer' : ''} ${className}`}
className={`border-b border-gray-100 hover:bg-gray-50 ${
onClick ? "cursor-pointer" : ""
} ${className}`}
>
{children}
</tr>
@@ -55,9 +59,13 @@ interface TableHeadProps {
className?: string;
}
export const TableHead: React.FC<TableHeadProps> = ({ children, className = '' }) => {
export const TableHead: React.FC<TableHeadProps> = (
{ children, className = "" },
) => {
return (
<th className={`text-left py-3 px-4 text-sm font-medium text-gray-600 ${className}`}>
<th
className={`text-left py-3 px-4 text-sm font-medium text-gray-600 ${className}`}
>
{children}
</th>
);
@@ -68,6 +76,12 @@ interface TableCellProps {
className?: string;
}
export const TableCell: React.FC<TableCellProps> = ({ children, className = '' }) => {
return <td className={`py-3 px-4 text-sm text-gray-700 ${className}`}>{children}</td>;
export const TableCell: React.FC<TableCellProps> = (
{ children, className = "" },
) => {
return (
<td className={`py-3 px-4 text-sm text-gray-700 ${className}`}>
{children}
</td>
);
};

View File

@@ -1,76 +1,60 @@
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { api } from '../services/api';
import type { User } from '../types';
import React, { ReactNode, useState } from "react";
import { api } from "../services/api.ts";
import type { User } from "../types.ts";
import { AuthContext } from "./authContext.ts";
interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (username: string, password: string) => Promise<void>;
logout: () => void;
updateUser: (user: User) => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within AuthProvider');
}
return context;
};
// Re-export useAuth for convenience
export { useAuth } from "./authContext.ts";
interface AuthProviderProps {
children: ReactNode;
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Helper to get initial user from localStorage
const getInitialUser = (): User | null => {
const token = localStorage.getItem("token");
const storedUser = localStorage.getItem("user");
useEffect(() => {
// Check for existing session
const token = localStorage.getItem('token');
const storedUser = localStorage.getItem('user');
if (token && storedUser) {
try {
const parsedUser = JSON.parse(storedUser);
setUser(parsedUser);
} catch (error) {
console.error('Failed to parse stored user:', error);
localStorage.removeItem('user');
localStorage.removeItem('token');
}
if (token && storedUser) {
try {
return JSON.parse(storedUser);
} catch (error) {
console.error("Failed to parse stored user:", error);
localStorage.removeItem("user");
localStorage.removeItem("token");
}
setIsLoading(false);
}, []);
}
return null;
};
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [user, setUser] = useState<User | null>(getInitialUser);
const [isLoading] = useState(false);
const login = async (username: string, password: string) => {
try {
const response = await api.login(username, password);
// Store token and user
localStorage.setItem('token', response.token);
localStorage.setItem('user', JSON.stringify(response.user));
localStorage.setItem("token", response.token);
localStorage.setItem("user", JSON.stringify(response.user));
setUser(response.user);
} catch (error) {
console.error('Login failed:', error);
console.error("Login failed:", error);
throw error;
}
};
const logout = () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem("token");
localStorage.removeItem("user");
setUser(null);
};
const updateUser = (updatedUser: User) => {
setUser(updatedUser);
localStorage.setItem('user', JSON.stringify(updatedUser));
localStorage.setItem("user", JSON.stringify(updatedUser));
};
return (

View File

@@ -0,0 +1,23 @@
import { createContext, useContext } from "react";
import type { User } from "../types";
export interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (username: string, password: string) => Promise<void>;
logout: () => void;
updateUser: (user: User) => void;
}
export const AuthContext = createContext<AuthContextType | undefined>(
undefined,
);
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within AuthProvider");
}
return context;
};

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { api } from '../services/api';
import { Activity } from '../types';
import { useCallback, useEffect, useState } from "react";
import { api } from "../services/api.ts";
import { Activity } from "../types.ts";
export const useActivities = (subDepartmentId?: string | number) => {
const [activities, setActivities] = useState<Activity[]>([]);
@@ -18,7 +18,9 @@ export const useActivities = (subDepartmentId?: string | number) => {
const data = await api.getActivities(params);
setActivities(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch activities');
setError(
err instanceof Error ? err.message : "Failed to fetch activities",
);
setActivities([]);
} finally {
setLoading(false);
@@ -42,14 +44,18 @@ export const useActivitiesByDepartment = (departmentId?: string | number) => {
setActivities([]);
return;
}
setLoading(true);
setError(null);
try {
const data = await api.getActivities({ departmentId: Number(departmentId) });
const data = await api.getActivities({
departmentId: Number(departmentId),
});
setActivities(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch activities');
setError(
err instanceof Error ? err.message : "Failed to fetch activities",
);
setActivities([]);
} finally {
setLoading(false);

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { api } from '../services/api';
import type { Department, SubDepartment } from '../types';
import { useCallback, useEffect, useState } from "react";
import { api } from "../services/api.ts";
import type { Department, SubDepartment } from "../types.ts";
export const useDepartments = () => {
const [departments, setDepartments] = useState<Department[]>([]);
@@ -13,8 +13,8 @@ export const useDepartments = () => {
try {
const data = await api.getDepartments();
setDepartments(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch departments');
} catch (err: never) {
setError(err.message || "Failed to fetch departments");
} finally {
setLoading(false);
}
@@ -37,7 +37,7 @@ export const useSubDepartments = (departmentId?: string) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchSubDepartments = async () => {
const fetchSubDepartments = useCallback(async () => {
if (!departmentId) {
setSubDepartments([]);
return;
@@ -48,16 +48,16 @@ export const useSubDepartments = (departmentId?: string) => {
try {
const data = await api.getSubDepartments(parseInt(departmentId));
setSubDepartments(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch subdepartments');
} catch (err: never) {
setError(err.message || "Failed to fetch subdepartments");
} finally {
setLoading(false);
}
};
}, [departmentId]);
useEffect(() => {
fetchSubDepartments();
}, [departmentId]);
}, [fetchSubDepartments]);
return {
subDepartments,
@@ -65,4 +65,4 @@ export const useSubDepartments = (departmentId?: string) => {
error,
refresh: fetchSubDepartments,
};
};
};

View File

@@ -1,56 +1,61 @@
import { useState, useEffect } from 'react';
import { api } from '../services/api';
import type { User } from '../types';
import { useCallback, useEffect, useState } from "react";
import { api } from "../services/api";
import type { User } from "../types";
export const useEmployees = (filters?: { role?: string; departmentId?: number }) => {
export const useEmployees = (
filters?: { role?: string; departmentId?: number },
) => {
const [employees, setEmployees] = useState<User[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchEmployees = async () => {
const fetchEmployees = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await api.getUsers(filters);
setEmployees(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch employees');
console.error('Failed to fetch employees:', err);
} catch (err: never) {
setError(err.message || "Failed to fetch employees");
console.error("Failed to fetch employees:", err);
} finally {
setLoading(false);
}
};
}, [filters]);
useEffect(() => {
fetchEmployees();
}, [JSON.stringify(filters)]);
}, [fetchEmployees]);
const createEmployee = async (data: any) => {
const createEmployee = async (data: Omit<User, "id">) => {
setLoading(true);
setError(null);
try {
const newEmployee = await api.createUser(data);
await fetchEmployees(); // Refresh list
return newEmployee;
} catch (err: any) {
setError(err.message || 'Failed to create employee');
console.error('Failed to create employee:', err);
} catch (err: never) {
setError(err.message || "Failed to create employee");
console.error("Failed to create employee:", err);
throw err;
} finally {
setLoading(false);
}
};
const updateEmployee = async (id: number, data: any) => {
const updateEmployee = async (
id: number,
data: Partial<Omit<User, "id">>,
) => {
setLoading(true);
setError(null);
try {
const updated = await api.updateUser(id, data);
await fetchEmployees(); // Refresh list
return updated;
} catch (err: any) {
setError(err.message || 'Failed to update employee');
console.error('Failed to update employee:', err);
} catch (err: never) {
setError(err.message || "Failed to update employee");
console.error("Failed to update employee:", err);
throw err;
} finally {
setLoading(false);
@@ -63,9 +68,9 @@ export const useEmployees = (filters?: { role?: string; departmentId?: number })
try {
await api.deleteUser(id);
await fetchEmployees(); // Refresh list
} catch (err: any) {
setError(err.message || 'Failed to delete employee');
console.error('Failed to delete employee:', err);
} catch (err: never) {
setError(err.message || "Failed to delete employee");
console.error("Failed to delete employee:", err);
throw err;
} finally {
setLoading(false);

View File

@@ -1,56 +1,66 @@
import { useState, useEffect } from 'react';
import { api } from '../services/api';
import type { WorkAllocation } from '../types';
import { useCallback, useEffect, useState } from "react";
import { api } from "../services/api.ts";
import type { WorkAllocation } from "../types.ts";
export const useWorkAllocations = (filters?: { employeeId?: number; status?: string; departmentId?: number }) => {
export const useWorkAllocations = (
filters?: { employeeId?: number; status?: string; departmentId?: number },
) => {
const [allocations, setAllocations] = useState<WorkAllocation[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchAllocations = async () => {
const fetchAllocations = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await api.getWorkAllocations(filters);
setAllocations(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch work allocations');
console.error('Failed to fetch work allocations:', err);
} catch (err: never) {
setError(err.message || "Failed to fetch work allocations");
console.error("Failed to fetch work allocations:", err);
} finally {
setLoading(false);
}
};
}, [filters]);
useEffect(() => {
fetchAllocations();
}, [JSON.stringify(filters)]);
}, [fetchAllocations]);
const createAllocation = async (data: any) => {
const createAllocation = async (data: Omit<WorkAllocation, "id">) => {
setLoading(true);
setError(null);
try {
const newAllocation = await api.createWorkAllocation(data);
await fetchAllocations(); // Refresh list
return newAllocation;
} catch (err: any) {
setError(err.message || 'Failed to create work allocation');
console.error('Failed to create work allocation:', err);
} catch (err: never) {
setError(err.message || "Failed to create work allocation");
console.error("Failed to create work allocation:", err);
throw err;
} finally {
setLoading(false);
}
};
const updateAllocation = async (id: number, status: string, completionDate?: string) => {
const updateAllocation = async (
id: number,
status: string,
completionDate?: string,
) => {
setLoading(true);
setError(null);
try {
const updated = await api.updateWorkAllocationStatus(id, status, completionDate);
const updated = await api.updateWorkAllocationStatus(
id,
status,
completionDate,
);
await fetchAllocations(); // Refresh list
return updated;
} catch (err: any) {
setError(err.message || 'Failed to update work allocation');
console.error('Failed to update work allocation:', err);
} catch (err: never) {
setError(err.message || "Failed to update work allocation");
console.error("Failed to update work allocation:", err);
throw err;
} finally {
setLoading(false);
@@ -63,9 +73,9 @@ export const useWorkAllocations = (filters?: { employeeId?: number; status?: str
try {
await api.deleteWorkAllocation(id);
await fetchAllocations(); // Refresh list
} catch (err: any) {
setError(err.message || 'Failed to delete work allocation');
console.error('Failed to delete work allocation:', err);
} catch (err: never) {
setError(err.message || "Failed to delete work allocation");
console.error("Failed to delete work allocation:", err);
throw err;
} finally {
setLoading(false);

View File

@@ -1,9 +1,9 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
import React from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
createRoot(document.getElementById('root')!).render(
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,

View File

@@ -1,43 +1,62 @@
import React, { useState, useEffect } from 'react';
import { Plus, RefreshCw, Trash2, Layers, Activity as ActivityIcon } from 'lucide-react';
import { Card, CardHeader, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select } from '../components/ui/Input';
import { useDepartments, useSubDepartments } from '../hooks/useDepartments';
import { useActivitiesByDepartment } from '../hooks/useActivities';
import { useAuth } from '../contexts/AuthContext';
import { api } from '../services/api';
import { SubDepartment, Activity } from '../types';
import React, { useEffect, useState } from "react";
import {
Activity as ActivityIcon,
Layers,
Plus,
RefreshCw,
Trash2,
} from "lucide-react";
import { Card, CardContent, CardHeader } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { useDepartments, useSubDepartments } from "../hooks/useDepartments.ts";
import { useActivitiesByDepartment } from "../hooks/useActivities.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
import { api } from "../services/api.ts";
import { Activity, SubDepartment } from "../types.ts";
export const ActivitiesPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'subDepartments' | 'activities'>('subDepartments');
const [activeTab, setActiveTab] = useState<"subDepartments" | "activities">(
"subDepartments",
);
const { user } = useAuth();
const { departments } = useDepartments();
// Role-based access
const isSupervisor = user?.role === 'Supervisor';
const isSuperAdmin = user?.role === 'SuperAdmin';
const isSupervisor = user?.role === "Supervisor";
const isSuperAdmin = user?.role === "SuperAdmin";
const canAccess = isSupervisor || isSuperAdmin;
// Department selection - supervisors are locked to their department
const [selectedDeptId, setSelectedDeptId] = useState<string>('');
const [selectedDeptId, setSelectedDeptId] = useState<string>("");
// Get sub-departments and activities for selected department
const { subDepartments, refresh: refreshSubDepts } = useSubDepartments(selectedDeptId);
const { activities, refresh: refreshActivities } = useActivitiesByDepartment(selectedDeptId);
const { subDepartments, refresh: refreshSubDepts } = useSubDepartments(
selectedDeptId,
);
const { activities, refresh: refreshActivities } = useActivitiesByDepartment(
selectedDeptId,
);
// Form states
const [subDeptForm, setSubDeptForm] = useState({ name: '' });
const [activityForm, setActivityForm] = useState({
subDepartmentId: '',
name: '',
unitOfMeasurement: 'Per Bag' as 'Per Bag' | 'Fixed Rate-Per Person'
const [subDeptForm, setSubDeptForm] = useState({ name: "" });
const [activityForm, setActivityForm] = useState({
subDepartmentId: "",
name: "",
unitOfMeasurement: "Per Bag" as "Per Bag" | "Fixed Rate-Per Person",
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [error, setError] = useState("");
const [success, setSuccess] = useState("");
// Auto-select department for supervisors
useEffect(() => {
@@ -50,8 +69,8 @@ export const ActivitiesPage: React.FC = () => {
useEffect(() => {
if (success || error) {
const timer = setTimeout(() => {
setSuccess('');
setError('');
setSuccess("");
setError("");
}, 3000);
return () => clearTimeout(timer);
}
@@ -59,44 +78,52 @@ export const ActivitiesPage: React.FC = () => {
const handleCreateSubDepartment = async () => {
if (!subDeptForm.name.trim()) {
setError('Sub-department name is required');
setError("Sub-department name is required");
return;
}
if (!selectedDeptId) {
setError('Please select a department first');
setError("Please select a department first");
return;
}
setLoading(true);
setError('');
setError("");
try {
await api.createSubDepartment({
department_id: parseInt(selectedDeptId),
name: subDeptForm.name.trim()
name: subDeptForm.name.trim(),
});
setSuccess('Sub-department created successfully');
setSubDeptForm({ name: '' });
setSuccess("Sub-department created successfully");
setSubDeptForm({ name: "" });
refreshSubDepts();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create sub-department');
setError(
err instanceof Error ? err.message : "Failed to create sub-department",
);
} finally {
setLoading(false);
}
};
const handleDeleteSubDepartment = async (id: number) => {
if (!confirm('Are you sure you want to delete this sub-department? This will also delete all associated activities.')) {
if (
!confirm(
"Are you sure you want to delete this sub-department? This will also delete all associated activities.",
)
) {
return;
}
setLoading(true);
try {
await api.deleteSubDepartment(id);
setSuccess('Sub-department deleted successfully');
setSuccess("Sub-department deleted successfully");
refreshSubDepts();
refreshActivities();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete sub-department');
setError(
err instanceof Error ? err.message : "Failed to delete sub-department",
);
} finally {
setLoading(false);
}
@@ -104,44 +131,52 @@ export const ActivitiesPage: React.FC = () => {
const handleCreateActivity = async () => {
if (!activityForm.name.trim()) {
setError('Activity name is required');
setError("Activity name is required");
return;
}
if (!activityForm.subDepartmentId) {
setError('Please select a sub-department');
setError("Please select a sub-department");
return;
}
setLoading(true);
setError('');
setError("");
try {
await api.createActivity({
sub_department_id: parseInt(activityForm.subDepartmentId),
name: activityForm.name.trim(),
unit_of_measurement: activityForm.unitOfMeasurement
unit_of_measurement: activityForm.unitOfMeasurement,
});
setSuccess("Activity created successfully");
setActivityForm({
subDepartmentId: "",
name: "",
unitOfMeasurement: "Per Bag",
});
setSuccess('Activity created successfully');
setActivityForm({ subDepartmentId: '', name: '', unitOfMeasurement: 'Per Bag' });
refreshActivities();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create activity');
setError(
err instanceof Error ? err.message : "Failed to create activity",
);
} finally {
setLoading(false);
}
};
const handleDeleteActivity = async (id: number) => {
if (!confirm('Are you sure you want to delete this activity?')) {
if (!confirm("Are you sure you want to delete this activity?")) {
return;
}
setLoading(true);
try {
await api.deleteActivity(id);
setSuccess('Activity deleted successfully');
setSuccess("Activity deleted successfully");
refreshActivities();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete activity');
setError(
err instanceof Error ? err.message : "Failed to delete activity",
);
} finally {
setLoading(false);
}
@@ -152,14 +187,17 @@ export const ActivitiesPage: React.FC = () => {
<div className="p-6">
<Card>
<CardContent>
<p className="text-red-600">You do not have permission to access this page.</p>
<p className="text-red-600">
You do not have permission to access this page.
</p>
</CardContent>
</Card>
</div>
);
}
const selectedDeptName = departments.find(d => d.id === parseInt(selectedDeptId))?.name || '';
const selectedDeptName =
departments.find((d) => d.id === parseInt(selectedDeptId))?.name || "";
return (
<div className="p-6 space-y-6">
@@ -168,15 +206,22 @@ export const ActivitiesPage: React.FC = () => {
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Layers className="h-6 w-6 text-blue-600" />
<h2 className="text-xl font-semibold text-gray-800">Manage Activities & Sub-Departments</h2>
<h2 className="text-xl font-semibold text-gray-800">
Manage Activities & Sub-Departments
</h2>
</div>
<Button
variant="outline"
size="sm"
onClick={() => { refreshSubDepts(); refreshActivities(); }}
onClick={() => {
refreshSubDepts();
refreshActivities();
}}
disabled={loading}
>
<RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
<RefreshCw
className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`}
/>
Refresh
</Button>
</div>
@@ -185,23 +230,33 @@ export const ActivitiesPage: React.FC = () => {
<CardContent>
{/* Department Selection */}
<div className="mb-6">
{isSupervisor ? (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Department</label>
<Input value={selectedDeptName || 'Loading...'} disabled />
<p className="text-xs text-gray-500 mt-1">As a supervisor, you can only manage your department's activities.</p>
</div>
) : (
<Select
label="Select Department"
value={selectedDeptId}
onChange={(e) => setSelectedDeptId(e.target.value)}
options={[
{ value: '', label: 'Select a Department' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
]}
/>
)}
{isSupervisor
? (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Department
</label>
<Input value={selectedDeptName || "Loading..."} disabled />
<p className="text-xs text-gray-500 mt-1">
As a supervisor, you can only manage your department's
activities.
</p>
</div>
)
: (
<Select
label="Select Department"
value={selectedDeptId}
onChange={(e) => setSelectedDeptId(e.target.value)}
options={[
{ value: "", label: "Select a Department" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
)}
</div>
{/* Messages */}
@@ -220,22 +275,22 @@ export const ActivitiesPage: React.FC = () => {
<div className="border-b border-gray-200 mb-6">
<div className="flex space-x-8">
<button
onClick={() => setActiveTab('subDepartments')}
onClick={() => setActiveTab("subDepartments")}
className={`py-3 px-1 border-b-2 font-medium text-sm ${
activeTab === 'subDepartments'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "subDepartments"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
<Layers className="h-4 w-4 inline mr-2" />
Sub-Departments ({subDepartments.length})
</button>
<button
onClick={() => setActiveTab('activities')}
onClick={() => setActiveTab("activities")}
className={`py-3 px-1 border-b-2 font-medium text-sm ${
activeTab === 'activities'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "activities"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
<ActivityIcon className="h-4 w-4 inline mr-2" />
@@ -244,165 +299,226 @@ export const ActivitiesPage: React.FC = () => {
</div>
</div>
{!selectedDeptId ? (
<p className="text-gray-500 text-center py-8">Please select a department to manage sub-departments and activities.</p>
) : (
<>
{/* Sub-Departments Tab */}
{activeTab === 'subDepartments' && (
<div className="space-y-6">
{/* Create Sub-Department Form */}
<div className="bg-gray-50 p-4 rounded-lg">
<h3 className="text-md font-semibold text-gray-700 mb-4">Add New Sub-Department</h3>
<div className="flex gap-4 items-end">
<div className="flex-1">
<Input
label="Sub-Department Name"
value={subDeptForm.name}
onChange={(e) => setSubDeptForm({ name: e.target.value })}
placeholder="e.g., Loading/Unloading, Destoner, Tank"
/>
{!selectedDeptId
? (
<p className="text-gray-500 text-center py-8">
Please select a department to manage sub-departments and
activities.
</p>
)
: (
<>
{/* Sub-Departments Tab */}
{activeTab === "subDepartments" && (
<div className="space-y-6">
{/* Create Sub-Department Form */}
<div className="bg-gray-50 p-4 rounded-lg">
<h3 className="text-md font-semibold text-gray-700 mb-4">
Add New Sub-Department
</h3>
<div className="flex gap-4 items-end">
<div className="flex-1">
<Input
label="Sub-Department Name"
value={subDeptForm.name}
onChange={(e) =>
setSubDeptForm({ name: e.target.value })}
placeholder="e.g., Loading/Unloading, Destoner, Tank"
/>
</div>
<Button
onClick={handleCreateSubDepartment}
disabled={loading}
>
<Plus className="h-4 w-4 mr-2" />
Add Sub-Department
</Button>
</div>
<Button onClick={handleCreateSubDepartment} disabled={loading}>
<Plus className="h-4 w-4 mr-2" />
Add Sub-Department
</Button>
</div>
</div>
{/* Sub-Departments List */}
<Table>
<TableHeader>
<TableHead>Sub-Department Name</TableHead>
<TableHead>Activities Count</TableHead>
<TableHead>Created At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableHeader>
<TableBody>
{subDepartments.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-center text-gray-500 py-8">
No sub-departments found. Create one above.
</TableCell>
</TableRow>
) : (
subDepartments.map((subDept: SubDepartment) => {
const activityCount = activities.filter(a => a.sub_department_id === subDept.id).length;
return (
<TableRow key={subDept.id}>
<TableCell className="font-medium">{subDept.name}</TableCell>
<TableCell>{activityCount}</TableCell>
<TableCell>{new Date(subDept.created_at).toLocaleDateString()}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteSubDepartment(subDept.id)}
className="text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4" />
</Button>
{/* Sub-Departments List */}
<Table>
<TableHeader>
<TableHead>Sub-Department Name</TableHead>
<TableHead>Activities Count</TableHead>
<TableHead>Created At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableHeader>
<TableBody>
{subDepartments.length === 0
? (
<TableRow>
<TableCell
colSpan={4}
className="text-center text-gray-500 py-8"
>
No sub-departments found. Create one above.
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
)}
{/* Activities Tab */}
{activeTab === 'activities' && (
<div className="space-y-6">
{/* Create Activity Form */}
<div className="bg-gray-50 p-4 rounded-lg">
<h3 className="text-md font-semibold text-gray-700 mb-4">Add New Activity</h3>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
<Select
label="Sub-Department"
value={activityForm.subDepartmentId}
onChange={(e) => setActivityForm(prev => ({ ...prev, subDepartmentId: e.target.value }))}
options={[
{ value: '', label: 'Select Sub-Department' },
...subDepartments.map(s => ({ value: String(s.id), label: s.name }))
]}
/>
<Input
label="Activity Name"
value={activityForm.name}
onChange={(e) => setActivityForm(prev => ({ ...prev, name: e.target.value }))}
placeholder="e.g., Mufali Aavak Katai"
/>
<Select
label="Unit of Measurement"
value={activityForm.unitOfMeasurement}
onChange={(e) => setActivityForm(prev => ({
...prev,
unitOfMeasurement: e.target.value as 'Per Bag' | 'Fixed Rate-Per Person'
}))}
options={[
{ value: 'Per Bag', label: 'Per Bag' },
{ value: 'Fixed Rate-Per Person', label: 'Fixed Rate-Per Person' }
]}
/>
<Button onClick={handleCreateActivity} disabled={loading}>
<Plus className="h-4 w-4 mr-2" />
Add Activity
</Button>
</div>
)
: (
subDepartments.map((subDept: SubDepartment) => {
const activityCount = activities.filter((a) =>
a.sub_department_id === subDept.id
).length;
return (
<TableRow key={subDept.id}>
<TableCell className="font-medium">
{subDept.name}
</TableCell>
<TableCell>{activityCount}</TableCell>
<TableCell>
{new Date(subDept.created_at)
.toLocaleDateString()}
</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={() =>
handleDeleteSubDepartment(subDept.id)}
className="text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
)}
{/* Activities List */}
<Table>
<TableHeader>
<TableHead>Activity Name</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Unit of Measurement</TableHead>
<TableHead>Created At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableHeader>
<TableBody>
{activities.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center text-gray-500 py-8">
No activities found. Create one above.
</TableCell>
</TableRow>
) : (
activities.map((activity: Activity) => (
<TableRow key={activity.id}>
<TableCell className="font-medium">{activity.name}</TableCell>
<TableCell>{activity.sub_department_name}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded-full text-xs ${
activity.unit_of_measurement === 'Per Bag'
? 'bg-blue-100 text-blue-800'
: 'bg-green-100 text-green-800'
}`}>
{activity.unit_of_measurement}
</span>
</TableCell>
<TableCell>{new Date(activity.created_at).toLocaleDateString()}</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={() => handleDeleteActivity(activity.id)}
className="text-red-600 hover:text-red-800"
{/* Activities Tab */}
{activeTab === "activities" && (
<div className="space-y-6">
{/* Create Activity Form */}
<div className="bg-gray-50 p-4 rounded-lg">
<h3 className="text-md font-semibold text-gray-700 mb-4">
Add New Activity
</h3>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
<Select
label="Sub-Department"
value={activityForm.subDepartmentId}
onChange={(e) =>
setActivityForm((prev) => ({
...prev,
subDepartmentId: e.target.value,
}))}
options={[
{ value: "", label: "Select Sub-Department" },
...subDepartments.map((s) => ({
value: String(s.id),
label: s.name,
})),
]}
/>
<Input
label="Activity Name"
value={activityForm.name}
onChange={(e) =>
setActivityForm((prev) => ({
...prev,
name: e.target.value,
}))}
placeholder="e.g., Mufali Aavak Katai"
/>
<Select
label="Unit of Measurement"
value={activityForm.unitOfMeasurement}
onChange={(e) =>
setActivityForm((prev) => ({
...prev,
unitOfMeasurement: e.target.value as
| "Per Bag"
| "Fixed Rate-Per Person",
}))}
options={[
{ value: "Per Bag", label: "Per Bag" },
{
value: "Fixed Rate-Per Person",
label: "Fixed Rate-Per Person",
},
]}
/>
<Button
onClick={handleCreateActivity}
disabled={loading}
>
<Plus className="h-4 w-4 mr-2" />
Add Activity
</Button>
</div>
</div>
{/* Activities List */}
<Table>
<TableHeader>
<TableHead>Activity Name</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Unit of Measurement</TableHead>
<TableHead>Created At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableHeader>
<TableBody>
{activities.length === 0
? (
<TableRow>
<TableCell
colSpan={5}
className="text-center text-gray-500 py-8"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
)}
</>
)}
No activities found. Create one above.
</TableCell>
</TableRow>
)
: (
activities.map((activity: Activity) => (
<TableRow key={activity.id}>
<TableCell className="font-medium">
{activity.name}
</TableCell>
<TableCell>
{activity.sub_department_name}
</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded-full text-xs ${
activity.unit_of_measurement === "Per Bag"
? "bg-blue-100 text-blue-800"
: "bg-green-100 text-green-800"
}`}
>
{activity.unit_of_measurement}
</span>
</TableCell>
<TableCell>
{new Date(activity.created_at)
.toLocaleDateString()}
</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
onClick={() =>
handleDeleteActivity(activity.id)}
className="text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
)}
</>
)}
</CardContent>
</Card>
</div>

View File

@@ -1,39 +1,54 @@
import React, { useState, useEffect, useMemo } from 'react';
import { RefreshCw, Search, Filter, Eye, Calendar } from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select } from '../components/ui/Input';
import { api } from '../services/api';
import { useDepartments } from '../hooks/useDepartments';
import { useAuth } from '../contexts/AuthContext';
import React, { useEffect, useMemo, useState } from "react";
import { Calendar, Eye, Filter, RefreshCw, Search } from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useDepartments } from "../hooks/useDepartments.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
export const AllRatesPage: React.FC = () => {
const { user } = useAuth();
const { departments } = useDepartments();
const [allRates, setAllRates] = useState<any[]>([]);
const [summary, setSummary] = useState<{ totalContractorRates: number; totalStandardRates: number; totalRates: number } | null>(null);
const [summary, setSummary] = useState<
{
totalContractorRates: number;
totalStandardRates: number;
totalRates: number;
} | null
>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [error, setError] = useState("");
const [searchQuery, setSearchQuery] = useState("");
// Filters
const [filters, setFilters] = useState({
departmentId: '',
startDate: '',
endDate: '',
rateType: '', // 'contractor' | 'standard' | ''
departmentId: "",
startDate: "",
endDate: "",
rateType: "", // 'contractor' | 'standard' | ''
});
const isSuperAdmin = user?.role === 'SuperAdmin';
const isSuperAdmin = user?.role === "SuperAdmin";
// Fetch all rates
const fetchAllRates = async () => {
setLoading(true);
setError('');
setError("");
try {
const params: any = {};
if (filters.departmentId) params.departmentId = parseInt(filters.departmentId);
if (filters.departmentId) {
params.departmentId = parseInt(filters.departmentId);
}
if (filters.startDate) params.startDate = filters.startDate;
if (filters.endDate) params.endDate = filters.endDate;
@@ -41,7 +56,7 @@ export const AllRatesPage: React.FC = () => {
setAllRates(data.allRates);
setSummary(data.summary);
} catch (err: any) {
setError(err.message || 'Failed to fetch rates');
setError(err.message || "Failed to fetch rates");
} finally {
setLoading(false);
}
@@ -53,9 +68,11 @@ export const AllRatesPage: React.FC = () => {
}
}, [isSuperAdmin]);
const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const handleFilterChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { name, value } = e.target;
setFilters(prev => ({ ...prev, [name]: value }));
setFilters((prev) => ({ ...prev, [name]: value }));
};
const applyFilters = () => {
@@ -64,10 +81,10 @@ export const AllRatesPage: React.FC = () => {
const clearFilters = () => {
setFilters({
departmentId: '',
startDate: '',
endDate: '',
rateType: '',
departmentId: "",
startDate: "",
endDate: "",
rateType: "",
});
setTimeout(fetchAllRates, 0);
};
@@ -75,16 +92,16 @@ export const AllRatesPage: React.FC = () => {
// Filter rates based on search and rate type
const filteredRates = useMemo(() => {
let rates = allRates;
// Filter by rate type
if (filters.rateType) {
rates = rates.filter(r => r.rate_type === filters.rateType);
rates = rates.filter((r) => r.rate_type === filters.rateType);
}
// Filter by search query
if (searchQuery) {
const query = searchQuery.toLowerCase();
rates = rates.filter(r =>
rates = rates.filter((r) =>
r.contractor_name?.toLowerCase().includes(query) ||
r.sub_department_name?.toLowerCase().includes(query) ||
r.department_name?.toLowerCase().includes(query) ||
@@ -92,7 +109,7 @@ export const AllRatesPage: React.FC = () => {
r.created_by_name?.toLowerCase().includes(query)
);
}
return rates;
}, [allRates, searchQuery, filters.rateType]);
@@ -104,7 +121,9 @@ export const AllRatesPage: React.FC = () => {
<CardContent>
<div className="text-center py-12">
<Eye size={48} className="mx-auto text-gray-400 mb-4" />
<h2 className="text-xl font-semibold text-gray-700 mb-2">Access Restricted</h2>
<h2 className="text-xl font-semibold text-gray-700 mb-2">
Access Restricted
</h2>
<p className="text-gray-500">
This page is only accessible to Super Admin accounts.
</p>
@@ -123,8 +142,12 @@ export const AllRatesPage: React.FC = () => {
<div className="flex items-center gap-3">
<Eye className="text-purple-600" size={24} />
<div>
<h2 className="text-xl font-semibold text-gray-800">All Rates Overview</h2>
<p className="text-sm text-gray-500">View all contractor and standard rates across all departments</p>
<h2 className="text-xl font-semibold text-gray-800">
All Rates Overview
</h2>
<p className="text-sm text-gray-500">
View all contractor and standard rates across all departments
</p>
</div>
</div>
</div>
@@ -144,8 +167,11 @@ export const AllRatesPage: React.FC = () => {
value={filters.departmentId}
onChange={handleFilterChange}
options={[
{ value: '', label: 'All Departments' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
{ value: "", label: "All Departments" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
<Select
@@ -154,13 +180,15 @@ export const AllRatesPage: React.FC = () => {
value={filters.rateType}
onChange={handleFilterChange}
options={[
{ value: '', label: 'All Types' },
{ value: 'contractor', label: 'Contractor Rates' },
{ value: 'standard', label: 'Standard Rates' },
{ value: "", label: "All Types" },
{ value: "contractor", label: "Contractor Rates" },
{ value: "standard", label: "Standard Rates" },
]}
/>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<label className="block text-sm font-medium text-gray-700 mb-1">
Start Date
</label>
<Input
type="date"
name="startDate"
@@ -169,7 +197,9 @@ export const AllRatesPage: React.FC = () => {
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
<label className="block text-sm font-medium text-gray-700 mb-1">
End Date
</label>
<Input
type="date"
name="endDate"
@@ -192,16 +222,28 @@ export const AllRatesPage: React.FC = () => {
{summary && (
<div className="grid grid-cols-3 gap-4 mb-6">
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div className="text-sm text-blue-600 font-medium">Total Rates</div>
<div className="text-2xl font-bold text-blue-800">{summary.totalRates}</div>
<div className="text-sm text-blue-600 font-medium">
Total Rates
</div>
<div className="text-2xl font-bold text-blue-800">
{summary.totalRates}
</div>
</div>
<div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
<div className="text-sm text-orange-600 font-medium">Contractor Rates</div>
<div className="text-2xl font-bold text-orange-800">{summary.totalContractorRates}</div>
<div className="text-sm text-orange-600 font-medium">
Contractor Rates
</div>
<div className="text-2xl font-bold text-orange-800">
{summary.totalContractorRates}
</div>
</div>
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
<div className="text-sm text-green-600 font-medium">Standard Rates</div>
<div className="text-2xl font-bold text-green-800">{summary.totalStandardRates}</div>
<div className="text-sm text-green-600 font-medium">
Standard Rates
</div>
<div className="text-2xl font-bold text-green-800">
{summary.totalStandardRates}
</div>
</div>
</div>
)}
@@ -209,7 +251,10 @@ export const AllRatesPage: React.FC = () => {
{/* Search and Refresh */}
<div className="flex gap-4 mb-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by contractor, department, activity..."
@@ -232,69 +277,80 @@ export const AllRatesPage: React.FC = () => {
)}
{/* Table */}
{loading ? (
<div className="text-center py-8">Loading all rates...</div>
) : filteredRates.length > 0 ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableHead>Type</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
<TableHead>Created By</TableHead>
</TableHeader>
<TableBody>
{filteredRates.map((rate, idx) => (
<TableRow key={`${rate.rate_type}-${rate.id}-${idx}`}>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
rate.rate_type === 'contractor'
? 'bg-orange-100 text-orange-700'
: 'bg-green-100 text-green-700'
}`}>
{rate.rate_type === 'contractor' ? 'Contractor' : 'Standard'}
</span>
</TableCell>
<TableCell className="font-medium">
{rate.contractor_name || '-'}
</TableCell>
<TableCell>{rate.department_name || '-'}</TableCell>
<TableCell>{rate.sub_department_name || '-'}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
rate.activity === 'Loading' || rate.activity === 'Unloading'
? 'bg-purple-100 text-purple-700'
: 'bg-gray-100 text-gray-700'
}`}>
{rate.activity || 'Standard'}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">{rate.rate}</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Calendar size={14} className="text-gray-400" />
{new Date(rate.effective_date).toLocaleDateString()}
</div>
</TableCell>
<TableCell className="text-gray-500">
{rate.created_by_name || '-'}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="text-center py-8 text-gray-500">
No rates found. Adjust your filters or check back later.
</div>
)}
{loading
? <div className="text-center py-8">Loading all rates...</div>
: filteredRates.length > 0
? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableHead>Type</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
<TableHead>Created By</TableHead>
</TableHeader>
<TableBody>
{filteredRates.map((rate, idx) => (
<TableRow key={`${rate.rate_type}-${rate.id}-${idx}`}>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
rate.rate_type === "contractor"
? "bg-orange-100 text-orange-700"
: "bg-green-100 text-green-700"
}`}
>
{rate.rate_type === "contractor"
? "Contractor"
: "Standard"}
</span>
</TableCell>
<TableCell className="font-medium">
{rate.contractor_name || "-"}
</TableCell>
<TableCell>{rate.department_name || "-"}</TableCell>
<TableCell>{rate.sub_department_name || "-"}</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
rate.activity === "Loading" ||
rate.activity === "Unloading"
? "bg-purple-100 text-purple-700"
: "bg-gray-100 text-gray-700"
}`}
>
{rate.activity || "Standard"}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">
{rate.rate}
</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Calendar size={14} className="text-gray-400" />
{new Date(rate.effective_date).toLocaleDateString()}
</div>
</TableCell>
<TableCell className="text-gray-500">
{rate.created_by_name || "-"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)
: (
<div className="text-center py-8 text-gray-500">
No rates found. Adjust your filters or check back later.
</div>
)}
</CardContent>
</Card>
</div>

View File

@@ -1,43 +1,68 @@
import React, { useState, useEffect, useMemo } from 'react';
import { AlertTriangle, CheckCircle, Clock, RefreshCw, LogIn, LogOut, Search, ArrowUpDown, ArrowUp, ArrowDown, UserX, Edit2, X } from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Select, Input } from '../components/ui/Input';
import { api } from '../services/api';
import { useEmployees } from '../hooks/useEmployees';
import { useAuth } from '../contexts/AuthContext';
import type { AttendanceStatus } from '../types';
import React, { useEffect, useMemo, useState } from "react";
import {
AlertTriangle,
ArrowDown,
ArrowUp,
ArrowUpDown,
CheckCircle,
Clock,
Edit2,
LogIn,
LogOut,
RefreshCw,
Search,
UserX,
X,
} from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useEmployees } from "../hooks/useEmployees.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
import type { AttendanceStatus } from "../types.ts";
export const AttendancePage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'records' | 'checkin'>('records');
const [activeTab, setActiveTab] = useState<"records" | "checkin">("records");
const [attendance, setAttendance] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [error, setError] = useState("");
const { employees } = useEmployees();
// Check-in form state
const [selectedEmployee, setSelectedEmployee] = useState('');
const [workDate, setWorkDate] = useState(new Date().toISOString().split('T')[0]);
const [selectedEmployee, setSelectedEmployee] = useState("");
const [workDate, setWorkDate] = useState(
new Date().toISOString().split("T")[0],
);
const [checkInLoading, setCheckInLoading] = useState(false);
const [employeeStatus, setEmployeeStatus] = useState<any>(null);
const [searchQuery, setSearchQuery] = useState('');
const [sortField, setSortField] = useState<'date' | 'employee' | 'status'>('date');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
const [searchQuery, setSearchQuery] = useState("");
const [sortField, setSortField] = useState<"date" | "employee" | "status">(
"date",
);
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
const [editingRecord, setEditingRecord] = useState<number | null>(null);
const [editStatus, setEditStatus] = useState<AttendanceStatus>('CheckedIn');
const [editRemark, setEditRemark] = useState('');
const [editStatus, setEditStatus] = useState<AttendanceStatus>("CheckedIn");
const [editRemark, setEditRemark] = useState("");
const { user } = useAuth();
// Fetch attendance records
const fetchAttendance = async () => {
setLoading(true);
setError('');
setError("");
try {
const data = await api.getAttendance();
setAttendance(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch attendance');
setError(err.message || "Failed to fetch attendance");
} finally {
setLoading(false);
}
@@ -51,8 +76,9 @@ export const AttendancePage: React.FC = () => {
useEffect(() => {
if (selectedEmployee && workDate) {
const record = attendance.find(
a => a.employee_id === parseInt(selectedEmployee) &&
a.work_date?.split('T')[0] === workDate
(a) =>
a.employee_id === parseInt(selectedEmployee) &&
a.work_date?.split("T")[0] === workDate,
);
setEmployeeStatus(record || null);
} else {
@@ -62,16 +88,16 @@ export const AttendancePage: React.FC = () => {
const handleCheckIn = async () => {
if (!selectedEmployee) {
alert('Please select an employee');
alert("Please select an employee");
return;
}
setCheckInLoading(true);
try {
await api.checkIn(parseInt(selectedEmployee), workDate);
await fetchAttendance();
setEmployeeStatus({ status: 'CheckedIn' });
setEmployeeStatus({ status: "CheckedIn" });
} catch (err: any) {
alert(err.message || 'Failed to check in');
alert(err.message || "Failed to check in");
} finally {
setCheckInLoading(false);
}
@@ -79,16 +105,16 @@ export const AttendancePage: React.FC = () => {
const handleCheckOut = async () => {
if (!selectedEmployee) {
alert('Please select an employee');
alert("Please select an employee");
return;
}
setCheckInLoading(true);
try {
await api.checkOut(parseInt(selectedEmployee), workDate);
await fetchAttendance();
setEmployeeStatus({ status: 'CheckedOut' });
setEmployeeStatus({ status: "CheckedOut" });
} catch (err: any) {
alert(err.message || 'Failed to check out');
alert(err.message || "Failed to check out");
} finally {
setCheckInLoading(false);
}
@@ -96,16 +122,20 @@ export const AttendancePage: React.FC = () => {
const handleMarkAbsent = async () => {
if (!selectedEmployee) {
alert('Please select an employee');
alert("Please select an employee");
return;
}
setCheckInLoading(true);
try {
await api.markAbsent(parseInt(selectedEmployee), workDate, 'Marked absent by supervisor');
await api.markAbsent(
parseInt(selectedEmployee),
workDate,
"Marked absent by supervisor",
);
await fetchAttendance();
setEmployeeStatus({ status: 'Absent' });
setEmployeeStatus({ status: "Absent" });
} catch (err: any) {
alert(err.message || 'Failed to mark absent');
alert(err.message || "Failed to mark absent");
} finally {
setCheckInLoading(false);
}
@@ -116,76 +146,82 @@ export const AttendancePage: React.FC = () => {
await api.updateAttendanceStatus(recordId, editStatus, editRemark);
await fetchAttendance();
setEditingRecord(null);
setEditRemark('');
setEditRemark("");
} catch (err: any) {
alert(err.message || 'Failed to update status');
alert(err.message || "Failed to update status");
}
};
const startEditing = (record: any) => {
setEditingRecord(record.id);
setEditStatus(record.status);
setEditRemark(record.remark || '');
setEditRemark(record.remark || "");
};
const cancelEditing = () => {
setEditingRecord(null);
setEditRemark('');
setEditRemark("");
};
const canEditAttendance = user?.role === 'SuperAdmin' || user?.role === 'Supervisor';
const canEditAttendance = user?.role === "SuperAdmin" ||
user?.role === "Supervisor";
const employeeOptions = [
{ value: '', label: 'Select Employee' },
...employees.filter(e => e.role === 'Employee').map(e => ({
value: String(e.id),
label: `${e.name} (${e.username})`
}))
{ value: "", label: "Select Employee" },
...employees.filter((e) => e.role === "Employee").map((e) => ({
value: String(e.id),
label: `${e.name} (${e.username})`,
})),
];
// Filter and sort attendance records
const filteredAndSortedAttendance = useMemo(() => {
let filtered = attendance;
// Apply search filter
if (searchQuery) {
const query = searchQuery.toLowerCase();
filtered = filtered.filter(record =>
filtered = filtered.filter((record) =>
record.employee_name?.toLowerCase().includes(query) ||
record.status?.toLowerCase().includes(query)
);
}
// Apply sorting
return [...filtered].sort((a, b) => {
let comparison = 0;
switch (sortField) {
case 'date':
comparison = new Date(a.work_date).getTime() - new Date(b.work_date).getTime();
case "date":
comparison = new Date(a.work_date).getTime() -
new Date(b.work_date).getTime();
break;
case 'employee':
comparison = (a.employee_name || '').localeCompare(b.employee_name || '');
case "employee":
comparison = (a.employee_name || "").localeCompare(
b.employee_name || "",
);
break;
case 'status':
comparison = (a.status || '').localeCompare(b.status || '');
case "status":
comparison = (a.status || "").localeCompare(b.status || "");
break;
}
return sortDirection === 'asc' ? comparison : -comparison;
return sortDirection === "asc" ? comparison : -comparison;
});
}, [attendance, searchQuery, sortField, sortDirection]);
const handleSort = (field: 'date' | 'employee' | 'status') => {
const handleSort = (field: "date" | "employee" | "status") => {
if (sortField === field) {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
setSortDirection((prev) => prev === "asc" ? "desc" : "asc");
} else {
setSortField(field);
setSortDirection('asc');
setSortDirection("asc");
}
};
const SortIcon = ({ field }: { field: 'date' | 'employee' | 'status' }) => {
if (sortField !== field) return <ArrowUpDown size={14} className="ml-1 text-gray-400" />;
return sortDirection === 'asc'
const SortIcon = ({ field }: { field: "date" | "employee" | "status" }) => {
if (sortField !== field) {
return <ArrowUpDown size={14} className="ml-1 text-gray-400" />;
}
return sortDirection === "asc"
? <ArrowUp size={14} className="ml-1 text-blue-600" />
: <ArrowDown size={14} className="ml-1 text-blue-600" />;
};
@@ -196,21 +232,21 @@ export const AttendancePage: React.FC = () => {
<div className="border-b border-gray-200">
<div className="flex space-x-8 px-6">
<button
onClick={() => setActiveTab('records')}
onClick={() => setActiveTab("records")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'records'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "records"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
Attendance Records
</button>
<button
onClick={() => setActiveTab('checkin')}
onClick={() => setActiveTab("checkin")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'checkin'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "checkin"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
Check In/Out
@@ -219,11 +255,14 @@ export const AttendancePage: React.FC = () => {
</div>
<CardContent>
{activeTab === 'records' && (
{activeTab === "records" && (
<div>
<div className="flex gap-4 mb-4">
<div className="relative min-w-[300px] flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by employee name or status..."
@@ -237,7 +276,7 @@ export const AttendancePage: React.FC = () => {
Refresh
</Button>
</div>
<div className="mb-4 text-sm text-gray-600">
Total Records: {filteredAndSortedAttendance.length}
</div>
@@ -248,144 +287,186 @@ export const AttendancePage: React.FC = () => {
</div>
)}
{loading ? (
<div className="text-center py-8">Loading attendance records...</div>
) : filteredAndSortedAttendance.length > 0 ? (
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>
<button
onClick={() => handleSort('employee')}
className="flex items-center hover:text-blue-600 transition-colors"
>
Employee <SortIcon field="employee" />
</button>
</TableHead>
<TableHead>
<button
onClick={() => handleSort('date')}
className="flex items-center hover:text-blue-600 transition-colors"
>
Date <SortIcon field="date" />
</button>
</TableHead>
<TableHead>Check In</TableHead>
<TableHead>Check Out</TableHead>
<TableHead>
<button
onClick={() => handleSort('status')}
className="flex items-center hover:text-blue-600 transition-colors"
>
Status <SortIcon field="status" />
</button>
</TableHead>
<TableHead>Remark</TableHead>
{canEditAttendance && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredAndSortedAttendance.map((record) => (
<TableRow key={record.id}>
<TableCell>{record.id}</TableCell>
<TableCell>{record.employee_name || '-'}</TableCell>
<TableCell>{new Date(record.work_date).toLocaleDateString()}</TableCell>
<TableCell>
{record.check_in_time
? new Date(record.check_in_time).toLocaleTimeString()
: '-'}
</TableCell>
<TableCell>
{record.check_out_time
? new Date(record.check_out_time).toLocaleTimeString()
: '-'}
</TableCell>
<TableCell>
{editingRecord === record.id ? (
<select
value={editStatus}
onChange={(e) => setEditStatus(e.target.value as AttendanceStatus)}
className="px-2 py-1 border border-gray-300 rounded text-sm"
>
<option value="CheckedIn">Checked In</option>
<option value="CheckedOut">Checked Out</option>
<option value="Absent">Absent</option>
<option value="HalfDay">Half Day</option>
<option value="Late">Late</option>
</select>
) : (
<span className={`px-2 py-1 rounded text-xs font-medium ${
record.status === 'CheckedOut' ? 'bg-green-100 text-green-700' :
record.status === 'CheckedIn' ? 'bg-blue-100 text-blue-700' :
record.status === 'Absent' ? 'bg-red-100 text-red-700' :
record.status === 'HalfDay' ? 'bg-orange-100 text-orange-700' :
record.status === 'Late' ? 'bg-yellow-100 text-yellow-700' :
'bg-gray-100 text-gray-700'
}`}>
{record.status === 'CheckedOut' ? 'Completed' :
record.status === 'CheckedIn' ? 'Checked In' :
record.status === 'HalfDay' ? 'Half Day' : record.status}
</span>
)}
</TableCell>
<TableCell>
{editingRecord === record.id ? (
<input
type="text"
value={editRemark}
onChange={(e) => setEditRemark(e.target.value)}
placeholder="Add remark..."
className="px-2 py-1 border border-gray-300 rounded text-sm w-32"
/>
) : (
<span className="text-gray-500 text-sm">{record.remark || '-'}</span>
)}
</TableCell>
{canEditAttendance && (
{loading
? (
<div className="text-center py-8">
Loading attendance records...
</div>
)
: filteredAndSortedAttendance.length > 0
? (
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>
<button
onClick={() => handleSort("employee")}
className="flex items-center hover:text-blue-600 transition-colors"
>
Employee <SortIcon field="employee" />
</button>
</TableHead>
<TableHead>
<button
onClick={() => handleSort("date")}
className="flex items-center hover:text-blue-600 transition-colors"
>
Date <SortIcon field="date" />
</button>
</TableHead>
<TableHead>Check In</TableHead>
<TableHead>Check Out</TableHead>
<TableHead>
<button
onClick={() => handleSort("status")}
className="flex items-center hover:text-blue-600 transition-colors"
>
Status <SortIcon field="status" />
</button>
</TableHead>
<TableHead>Remark</TableHead>
{canEditAttendance && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredAndSortedAttendance.map((record) => (
<TableRow key={record.id}>
<TableCell>{record.id}</TableCell>
<TableCell>{record.employee_name || "-"}</TableCell>
<TableCell>
{editingRecord === record.id ? (
<div className="flex gap-1">
<button
onClick={() => handleUpdateStatus(record.id)}
className="p-1 text-green-600 hover:bg-green-50 rounded"
title="Save"
>
<CheckCircle size={16} />
</button>
<button
onClick={cancelEditing}
className="p-1 text-red-600 hover:bg-red-50 rounded"
title="Cancel"
>
<X size={16} />
</button>
</div>
) : (
<button
onClick={() => startEditing(record)}
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
title="Edit Status"
>
<Edit2 size={16} />
</button>
)}
{new Date(record.work_date).toLocaleDateString()}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="text-center py-8 text-gray-500">
{searchQuery ? 'No matching records found' : 'No attendance records found'}
</div>
)}
<TableCell>
{record.check_in_time
? new Date(record.check_in_time)
.toLocaleTimeString()
: "-"}
</TableCell>
<TableCell>
{record.check_out_time
? new Date(record.check_out_time)
.toLocaleTimeString()
: "-"}
</TableCell>
<TableCell>
{editingRecord === record.id
? (
<select
value={editStatus}
onChange={(e) =>
setEditStatus(
e.target.value as AttendanceStatus,
)}
className="px-2 py-1 border border-gray-300 rounded text-sm"
>
<option value="CheckedIn">Checked In</option>
<option value="CheckedOut">
Checked Out
</option>
<option value="Absent">Absent</option>
<option value="HalfDay">Half Day</option>
<option value="Late">Late</option>
</select>
)
: (
<span
className={`px-2 py-1 rounded text-xs font-medium ${
record.status === "CheckedOut"
? "bg-green-100 text-green-700"
: record.status === "CheckedIn"
? "bg-blue-100 text-blue-700"
: record.status === "Absent"
? "bg-red-100 text-red-700"
: record.status === "HalfDay"
? "bg-orange-100 text-orange-700"
: record.status === "Late"
? "bg-yellow-100 text-yellow-700"
: "bg-gray-100 text-gray-700"
}`}
>
{record.status === "CheckedOut"
? "Completed"
: record.status === "CheckedIn"
? "Checked In"
: record.status === "HalfDay"
? "Half Day"
: record.status}
</span>
)}
</TableCell>
<TableCell>
{editingRecord === record.id
? (
<input
type="text"
value={editRemark}
onChange={(e) =>
setEditRemark(e.target.value)}
placeholder="Add remark..."
className="px-2 py-1 border border-gray-300 rounded text-sm w-32"
/>
)
: (
<span className="text-gray-500 text-sm">
{record.remark || "-"}
</span>
)}
</TableCell>
{canEditAttendance && (
<TableCell>
{editingRecord === record.id
? (
<div className="flex gap-1">
<button
onClick={() =>
handleUpdateStatus(record.id)}
className="p-1 text-green-600 hover:bg-green-50 rounded"
title="Save"
>
<CheckCircle size={16} />
</button>
<button
onClick={cancelEditing}
className="p-1 text-red-600 hover:bg-red-50 rounded"
title="Cancel"
>
<X size={16} />
</button>
</div>
)
: (
<button
onClick={() => startEditing(record)}
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
title="Edit Status"
>
<Edit2 size={16} />
</button>
)}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)
: (
<div className="text-center py-8 text-gray-500">
{searchQuery
? "No matching records found"
: "No attendance records found"}
</div>
)}
</div>
)}
{activeTab === 'checkin' && (
{activeTab === "checkin" && (
<div className="max-w-2xl">
<h3 className="text-lg font-semibold text-gray-800 mb-2">Check In / Check Out Management</h3>
<p className="text-sm text-gray-600 mb-6">Manage employee attendance</p>
<h3 className="text-lg font-semibold text-gray-800 mb-2">
Check In / Check Out Management
</h3>
<p className="text-sm text-gray-600 mb-6">
Manage employee attendance
</p>
<div className="space-y-6">
<div className="grid grid-cols-2 gap-6">
@@ -404,66 +485,91 @@ export const AttendancePage: React.FC = () => {
</div>
{selectedEmployee && (
<div className={`border rounded-md p-4 flex items-start ${
employeeStatus?.status === 'CheckedIn'
? 'bg-blue-50 border-blue-200'
: employeeStatus?.status === 'CheckedOut'
? 'bg-green-50 border-green-200'
: 'bg-yellow-50 border-yellow-200'
}`}>
{employeeStatus?.status === 'CheckedIn' ? (
<>
<Clock size={20} className="text-blue-600 mr-2 flex-shrink-0 mt-0.5" />
<p className="text-sm text-blue-800">
Employee is currently checked in. Check-in time: {
employeeStatus.check_in_time
? new Date(employeeStatus.check_in_time).toLocaleTimeString()
: 'N/A'
}
</p>
</>
) : employeeStatus?.status === 'CheckedOut' ? (
<>
<CheckCircle size={20} className="text-green-600 mr-2 flex-shrink-0 mt-0.5" />
<p className="text-sm text-green-800">
Employee has completed attendance for this date.
</p>
</>
) : (
<>
<AlertTriangle size={20} className="text-yellow-600 mr-2 flex-shrink-0 mt-0.5" />
<p className="text-sm text-yellow-800">Employee has not checked in for this date</p>
</>
)}
<div
className={`border rounded-md p-4 flex items-start ${
employeeStatus?.status === "CheckedIn"
? "bg-blue-50 border-blue-200"
: employeeStatus?.status === "CheckedOut"
? "bg-green-50 border-green-200"
: "bg-yellow-50 border-yellow-200"
}`}
>
{employeeStatus?.status === "CheckedIn"
? (
<>
<Clock
size={20}
className="text-blue-600 mr-2 flex-shrink-0 mt-0.5"
/>
<p className="text-sm text-blue-800">
Employee is currently checked in. Check-in time:
{" "}
{employeeStatus.check_in_time
? new Date(employeeStatus.check_in_time)
.toLocaleTimeString()
: "N/A"}
</p>
</>
)
: employeeStatus?.status === "CheckedOut"
? (
<>
<CheckCircle
size={20}
className="text-green-600 mr-2 flex-shrink-0 mt-0.5"
/>
<p className="text-sm text-green-800">
Employee has completed attendance for this date.
</p>
</>
)
: (
<>
<AlertTriangle
size={20}
className="text-yellow-600 mr-2 flex-shrink-0 mt-0.5"
/>
<p className="text-sm text-yellow-800">
Employee has not checked in for this date
</p>
</>
)}
</div>
)}
<div className="flex justify-center gap-4 pt-4">
<Button
size="lg"
<Button
size="lg"
onClick={handleCheckIn}
disabled={checkInLoading || !selectedEmployee || employeeStatus?.status === 'CheckedIn' || employeeStatus?.status === 'CheckedOut' || employeeStatus?.status === 'Absent'}
disabled={checkInLoading || !selectedEmployee ||
employeeStatus?.status === "CheckedIn" ||
employeeStatus?.status === "CheckedOut" ||
employeeStatus?.status === "Absent"}
>
<LogIn size={16} className="mr-2" />
{checkInLoading ? 'Processing...' : 'Check In'}
{checkInLoading ? "Processing..." : "Check In"}
</Button>
<Button
size="lg"
<Button
size="lg"
variant="outline"
onClick={handleCheckOut}
disabled={checkInLoading || !selectedEmployee || employeeStatus?.status !== 'CheckedIn'}
disabled={checkInLoading || !selectedEmployee ||
employeeStatus?.status !== "CheckedIn"}
>
<LogOut size={16} className="mr-2" />
{checkInLoading ? 'Processing...' : 'Check Out'}
{checkInLoading ? "Processing..." : "Check Out"}
</Button>
<Button
size="lg"
<Button
size="lg"
variant="danger"
onClick={handleMarkAbsent}
disabled={checkInLoading || !selectedEmployee || employeeStatus?.status === 'CheckedIn' || employeeStatus?.status === 'CheckedOut' || employeeStatus?.status === 'Absent'}
disabled={checkInLoading || !selectedEmployee ||
employeeStatus?.status === "CheckedIn" ||
employeeStatus?.status === "CheckedOut" ||
employeeStatus?.status === "Absent"}
>
<UserX size={16} className="mr-2" />
{checkInLoading ? 'Processing...' : 'Mark Absent'}
{checkInLoading ? "Processing..." : "Mark Absent"}
</Button>
</div>
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -1,140 +1,159 @@
import React, { useState, useEffect } from 'react';
import {
ArrowRightLeft,
Plus,
CheckCircle,
XCircle,
Clock,
Building2,
User,
import React, { useCallback, useEffect, useState } from "react";
import {
AlertCircle,
ArrowRightLeft,
Building2,
CheckCircle,
Clock,
Filter,
Plus,
RefreshCw,
Search,
Filter
} from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Select, Input } from '../components/ui/Input';
import { api } from '../services/api';
import { useEmployees } from '../hooks/useEmployees';
import { useDepartments } from '../hooks/useDepartments';
import type { EmployeeSwap, SwapReason, SwapStatus } from '../types';
User,
XCircle,
} from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useEmployees } from "../hooks/useEmployees.ts";
import { useDepartments } from "../hooks/useDepartments.ts";
import type { EmployeeSwap, SwapReason, SwapStatus } from "../types.ts";
export const EmployeeSwapPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'list' | 'create'>('list');
const [activeTab, setActiveTab] = useState<"list" | "create">("list");
const [swaps, setSwaps] = useState<EmployeeSwap[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [statusFilter, setStatusFilter] = useState<SwapStatus | ''>('');
const [error, setError] = useState("");
const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<SwapStatus | "">("");
const { employees } = useEmployees();
const { departments } = useDepartments();
// Form state
const [formData, setFormData] = useState({
employeeId: '',
targetDepartmentId: '',
targetContractorId: '',
swapReason: '' as SwapReason | '',
reasonDetails: '',
employeeId: "",
targetDepartmentId: "",
targetContractorId: "",
swapReason: "" as SwapReason | "",
reasonDetails: "",
workCompletionPercentage: 0,
swapDate: new Date().toISOString().split('T')[0],
swapDate: new Date().toISOString().split("T")[0],
});
const [submitting, setSubmitting] = useState(false);
const fetchSwaps = async () => {
const fetchSwaps = useCallback(async () => {
setLoading(true);
setError('');
setError("");
try {
const params: { status?: string } = {};
if (statusFilter) params.status = statusFilter;
const data = await api.getEmployeeSwaps(params);
setSwaps(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch swaps');
setError(err.message || "Failed to fetch swaps");
} finally {
setLoading(false);
}
};
}, [statusFilter]);
useEffect(() => {
fetchSwaps();
}, [statusFilter]);
}, [fetchSwaps]);
const handleCreateSwap = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.employeeId || !formData.targetDepartmentId || !formData.swapReason) {
alert('Please fill in all required fields');
if (
!formData.employeeId || !formData.targetDepartmentId ||
!formData.swapReason
) {
alert("Please fill in all required fields");
return;
}
setSubmitting(true);
try {
await api.createEmployeeSwap({
employeeId: parseInt(formData.employeeId),
targetDepartmentId: parseInt(formData.targetDepartmentId),
targetContractorId: formData.targetContractorId ? parseInt(formData.targetContractorId) : undefined,
targetContractorId: formData.targetContractorId
? parseInt(formData.targetContractorId)
: undefined,
swapReason: formData.swapReason as SwapReason,
reasonDetails: formData.reasonDetails || undefined,
workCompletionPercentage: formData.workCompletionPercentage,
swapDate: formData.swapDate,
});
// Reset form and switch to list
setFormData({
employeeId: '',
targetDepartmentId: '',
targetContractorId: '',
swapReason: '',
reasonDetails: '',
employeeId: "",
targetDepartmentId: "",
targetContractorId: "",
swapReason: "",
reasonDetails: "",
workCompletionPercentage: 0,
swapDate: new Date().toISOString().split('T')[0],
swapDate: new Date().toISOString().split("T")[0],
});
setActiveTab('list');
setActiveTab("list");
await fetchSwaps();
} catch (err: any) {
alert(err.message || 'Failed to create swap');
alert(err.message || "Failed to create swap");
} finally {
setSubmitting(false);
}
};
const handleCompleteSwap = async (id: number) => {
if (!confirm('Complete this swap and return employee to original department?')) return;
if (
!confirm("Complete this swap and return employee to original department?")
) return;
try {
await api.completeEmployeeSwap(id);
await fetchSwaps();
} catch (err: any) {
alert(err.message || 'Failed to complete swap');
alert(err.message || "Failed to complete swap");
}
};
const handleCancelSwap = async (id: number) => {
if (!confirm('Cancel this swap and return employee to original department?')) return;
if (
!confirm("Cancel this swap and return employee to original department?")
) return;
try {
await api.cancelEmployeeSwap(id);
await fetchSwaps();
} catch (err: any) {
alert(err.message || 'Failed to cancel swap');
alert(err.message || "Failed to cancel swap");
}
};
// Filter employees (only show employees)
const employeeList = employees.filter(e => e.role === 'Employee');
const employeeList = employees.filter((e) => e.role === "Employee");
// Get contractors for selected target department
const targetContractors = employees.filter(
e => e.role === 'Contractor' &&
e.department_id === parseInt(formData.targetDepartmentId)
(e) =>
e.role === "Contractor" &&
e.department_id === parseInt(formData.targetDepartmentId),
);
// Get selected employee details
const selectedEmployee = employeeList.find(e => e.id === parseInt(formData.employeeId));
const selectedEmployee = employeeList.find((e) =>
e.id === parseInt(formData.employeeId)
);
// Filter swaps based on search
const filteredSwaps = swaps.filter(swap => {
const filteredSwaps = swaps.filter((swap) => {
if (!searchQuery) return true;
const query = searchQuery.toLowerCase();
return (
@@ -146,29 +165,47 @@ export const EmployeeSwapPage: React.FC = () => {
const getStatusBadge = (status: SwapStatus) => {
switch (status) {
case 'Active':
return <span className="px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-700">Active</span>;
case 'Completed':
return <span className="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700">Completed</span>;
case 'Cancelled':
return <span className="px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-700">Cancelled</span>;
case "Active":
return (
<span className="px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-700">
Active
</span>
);
case "Completed":
return (
<span className="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700">
Completed
</span>
);
case "Cancelled":
return (
<span className="px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-700">
Cancelled
</span>
);
}
};
const getReasonBadge = (reason: SwapReason) => {
const colors: Record<SwapReason, string> = {
'LeftWork': 'bg-orange-100 text-orange-700',
'Sick': 'bg-red-100 text-red-700',
'FinishedEarly': 'bg-green-100 text-green-700',
'Other': 'bg-gray-100 text-gray-700',
"LeftWork": "bg-orange-100 text-orange-700",
"Sick": "bg-red-100 text-red-700",
"FinishedEarly": "bg-green-100 text-green-700",
"Other": "bg-gray-100 text-gray-700",
};
const labels: Record<SwapReason, string> = {
'LeftWork': 'Left Work',
'Sick': 'Sick',
'FinishedEarly': 'Finished Early',
'Other': 'Other',
"LeftWork": "Left Work",
"Sick": "Sick",
"FinishedEarly": "Finished Early",
"Other": "Other",
};
return <span className={`px-2 py-1 rounded text-xs font-medium ${colors[reason]}`}>{labels[reason]}</span>;
return (
<span
className={`px-2 py-1 rounded text-xs font-medium ${colors[reason]}`}
>
{labels[reason]}
</span>
);
};
return (
@@ -182,8 +219,12 @@ export const EmployeeSwapPage: React.FC = () => {
<ArrowRightLeft className="text-purple-600" size={24} />
</div>
<div>
<h1 className="text-xl font-bold text-gray-800">Employee Work Swap</h1>
<p className="text-sm text-gray-500">Transfer employees between departments temporarily</p>
<h1 className="text-xl font-bold text-gray-800">
Employee Work Swap
</h1>
<p className="text-sm text-gray-500">
Transfer employees between departments temporarily
</p>
</div>
</div>
</div>
@@ -193,21 +234,21 @@ export const EmployeeSwapPage: React.FC = () => {
<div className="border-b border-gray-200">
<div className="flex space-x-8 px-6">
<button
onClick={() => setActiveTab('list')}
onClick={() => setActiveTab("list")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'list'
? 'border-purple-500 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "list"
? "border-purple-500 text-purple-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
Swap History
</button>
<button
onClick={() => setActiveTab('create')}
onClick={() => setActiveTab("create")}
className={`py-4 px-2 border-b-2 font-medium text-sm flex items-center gap-2 ${
activeTab === 'create'
? 'border-purple-500 text-purple-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "create"
? "border-purple-500 text-purple-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
<Plus size={16} />
@@ -217,12 +258,15 @@ export const EmployeeSwapPage: React.FC = () => {
</div>
<CardContent>
{activeTab === 'list' && (
{activeTab === "list" && (
<div>
{/* Filters */}
<div className="flex gap-4 mb-6">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by employee or department..."
@@ -235,7 +279,8 @@ export const EmployeeSwapPage: React.FC = () => {
<Filter size={18} className="text-gray-400" />
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value as SwapStatus | '')}
onChange={(e) =>
setStatusFilter(e.target.value as SwapStatus | "")}
className="px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
>
<option value="">All Status</option>
@@ -258,7 +303,7 @@ export const EmployeeSwapPage: React.FC = () => {
<span className="text-sm font-medium">Active</span>
</div>
<div className="text-2xl font-bold text-blue-700">
{swaps.filter(s => s.status === 'Active').length}
{swaps.filter((s) => s.status === "Active").length}
</div>
</div>
<div className="bg-green-50 rounded-lg p-4">
@@ -267,7 +312,7 @@ export const EmployeeSwapPage: React.FC = () => {
<span className="text-sm font-medium">Completed</span>
</div>
<div className="text-2xl font-bold text-green-700">
{swaps.filter(s => s.status === 'Completed').length}
{swaps.filter((s) => s.status === "Completed").length}
</div>
</div>
<div className="bg-red-50 rounded-lg p-4">
@@ -276,7 +321,7 @@ export const EmployeeSwapPage: React.FC = () => {
<span className="text-sm font-medium">Cancelled</span>
</div>
<div className="text-2xl font-bold text-red-700">
{swaps.filter(s => s.status === 'Cancelled').length}
{swaps.filter((s) => s.status === "Cancelled").length}
</div>
</div>
<div className="bg-purple-50 rounded-lg p-4">
@@ -284,7 +329,9 @@ export const EmployeeSwapPage: React.FC = () => {
<ArrowRightLeft size={18} />
<span className="text-sm font-medium">Total Swaps</span>
</div>
<div className="text-2xl font-bold text-purple-700">{swaps.length}</div>
<div className="text-2xl font-bold text-purple-700">
{swaps.length}
</div>
</div>
</div>
@@ -294,125 +341,155 @@ export const EmployeeSwapPage: React.FC = () => {
</div>
)}
{loading ? (
<div className="text-center py-8">
<div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600"></div>
<span className="ml-2 text-gray-600">Loading swaps...</span>
</div>
) : filteredSwaps.length > 0 ? (
<Table>
<TableHeader>
<TableHead>Employee</TableHead>
<TableHead>From To</TableHead>
<TableHead>Reason</TableHead>
<TableHead>Completion %</TableHead>
<TableHead>Swap Date</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableHeader>
<TableBody>
{filteredSwaps.map((swap) => (
<TableRow key={swap.id}>
<TableCell>
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
<User size={16} className="text-purple-600" />
</div>
<div>
<div className="font-medium text-gray-800">{swap.employee_name}</div>
<div className="text-xs text-gray-500">
{swap.original_contractor_name && `Under: ${swap.original_contractor_name}`}
{loading
? (
<div className="text-center py-8">
<div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600">
</div>
<span className="ml-2 text-gray-600">Loading swaps...</span>
</div>
)
: filteredSwaps.length > 0
? (
<Table>
<TableHeader>
<TableHead>Employee</TableHead>
<TableHead>From To</TableHead>
<TableHead>Reason</TableHead>
<TableHead>Completion %</TableHead>
<TableHead>Swap Date</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableHeader>
<TableBody>
{filteredSwaps.map((swap) => (
<TableRow key={swap.id}>
<TableCell>
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
<User size={16} className="text-purple-600" />
</div>
<div>
<div className="font-medium text-gray-800">
{swap.employee_name}
</div>
<div className="text-xs text-gray-500">
{swap.original_contractor_name &&
`Under: ${swap.original_contractor_name}`}
</div>
</div>
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<span className="text-gray-600">{swap.original_department_name}</span>
<ArrowRightLeft size={14} className="text-gray-400" />
<span className="font-medium text-purple-600">{swap.target_department_name}</span>
</div>
{swap.target_contractor_name && (
<div className="text-xs text-gray-500 mt-1">
New contractor: {swap.target_contractor_name}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<span className="text-gray-600">
{swap.original_department_name}
</span>
<ArrowRightLeft
size={14}
className="text-gray-400"
/>
<span className="font-medium text-purple-600">
{swap.target_department_name}
</span>
</div>
)}
</TableCell>
<TableCell>
<div className="space-y-1">
{getReasonBadge(swap.swap_reason)}
{swap.reason_details && (
<div className="text-xs text-gray-500 max-w-[150px] truncate" title={swap.reason_details}>
{swap.reason_details}
{swap.target_contractor_name && (
<div className="text-xs text-gray-500 mt-1">
New contractor: {swap.target_contractor_name}
</div>
)}
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<div className="w-16 bg-gray-200 rounded-full h-2">
<div
className="bg-purple-600 h-2 rounded-full"
style={{ width: `${swap.work_completion_percentage}%` }}
/>
</TableCell>
<TableCell>
<div className="space-y-1">
{getReasonBadge(swap.swap_reason)}
{swap.reason_details && (
<div
className="text-xs text-gray-500 max-w-[150px] truncate"
title={swap.reason_details}
>
{swap.reason_details}
</div>
)}
</div>
<span className="text-sm text-gray-600">{swap.work_completion_percentage}%</span>
</div>
</TableCell>
<TableCell>
<div className="text-sm text-gray-600">
{new Date(swap.swap_date).toLocaleDateString()}
</div>
<div className="text-xs text-gray-400">
by {swap.swapped_by_name}
</div>
</TableCell>
<TableCell>{getStatusBadge(swap.status)}</TableCell>
<TableCell>
{swap.status === 'Active' && (
<div className="flex gap-1">
<button
onClick={() => handleCompleteSwap(swap.id)}
className="p-1.5 text-green-600 hover:bg-green-50 rounded"
title="Complete & Return"
>
<CheckCircle size={18} />
</button>
<button
onClick={() => handleCancelSwap(swap.id)}
className="p-1.5 text-red-600 hover:bg-red-50 rounded"
title="Cancel Swap"
>
<XCircle size={18} />
</button>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
<div className="w-16 bg-gray-200 rounded-full h-2">
<div
className="bg-purple-600 h-2 rounded-full"
style={{
width:
`${swap.work_completion_percentage}%`,
}}
/>
</div>
<span className="text-sm text-gray-600">
{swap.work_completion_percentage}%
</span>
</div>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="text-center py-12 text-gray-500">
<ArrowRightLeft size={48} className="mx-auto mb-4 text-gray-300" />
<p>No swap records found</p>
<Button
className="mt-4"
onClick={() => setActiveTab('create')}
>
<Plus size={16} className="mr-2" />
Create First Swap
</Button>
</div>
)}
</TableCell>
<TableCell>
<div className="text-sm text-gray-600">
{new Date(swap.swap_date).toLocaleDateString()}
</div>
<div className="text-xs text-gray-400">
by {swap.swapped_by_name}
</div>
</TableCell>
<TableCell>{getStatusBadge(swap.status)}</TableCell>
<TableCell>
{swap.status === "Active" && (
<div className="flex gap-1">
<button
onClick={() => handleCompleteSwap(swap.id)}
className="p-1.5 text-green-600 hover:bg-green-50 rounded"
title="Complete & Return"
>
<CheckCircle size={18} />
</button>
<button
onClick={() => handleCancelSwap(swap.id)}
className="p-1.5 text-red-600 hover:bg-red-50 rounded"
title="Cancel Swap"
>
<XCircle size={18} />
</button>
</div>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)
: (
<div className="text-center py-12 text-gray-500">
<ArrowRightLeft
size={48}
className="mx-auto mb-4 text-gray-300"
/>
<p>No swap records found</p>
<Button
className="mt-4"
onClick={() => setActiveTab("create")}
>
<Plus size={16} className="mr-2" />
Create First Swap
</Button>
</div>
)}
</div>
)}
{activeTab === 'create' && (
{activeTab === "create" && (
<div className="max-w-3xl mx-auto">
<div className="mb-6">
<h2 className="text-lg font-semibold text-gray-800">Create Employee Swap</h2>
<p className="text-sm text-gray-500">Transfer an employee to a different department temporarily</p>
<h2 className="text-lg font-semibold text-gray-800">
Create Employee Swap
</h2>
<p className="text-sm text-gray-500">
Transfer an employee to a different department temporarily
</p>
</div>
<form onSubmit={handleCreateSwap} className="space-y-6">
@@ -425,17 +502,18 @@ export const EmployeeSwapPage: React.FC = () => {
<Select
label="Employee"
value={formData.employeeId}
onChange={(e) => setFormData({ ...formData, employeeId: e.target.value })}
onChange={(e) =>
setFormData({ ...formData, employeeId: e.target.value })}
options={[
{ value: '', label: 'Select an employee...' },
...employeeList.map(e => ({
value: String(e.id),
label: `${e.name} - ${e.department_name || 'No Dept'}`
}))
{ value: "", label: "Select an employee..." },
...employeeList.map((e) => ({
value: String(e.id),
label: `${e.name} - ${e.department_name || "No Dept"}`,
})),
]}
required
/>
{selectedEmployee && (
<div className="mt-3 p-3 bg-white rounded border border-gray-200">
<div className="flex items-center gap-3">
@@ -443,10 +521,14 @@ export const EmployeeSwapPage: React.FC = () => {
<User size={20} className="text-purple-600" />
</div>
<div>
<div className="font-medium text-gray-800">{selectedEmployee.name}</div>
<div className="font-medium text-gray-800">
{selectedEmployee.name}
</div>
<div className="text-sm text-gray-500">
Current: {selectedEmployee.department_name || 'No Department'}
{selectedEmployee.contractor_name && ` • Under: ${selectedEmployee.contractor_name}`}
Current: {selectedEmployee.department_name ||
"No Department"}
{selectedEmployee.contractor_name &&
` • Under: ${selectedEmployee.contractor_name}`}
</div>
</div>
</div>
@@ -464,26 +546,36 @@ export const EmployeeSwapPage: React.FC = () => {
<Select
label="Department"
value={formData.targetDepartmentId}
onChange={(e) => setFormData({
...formData,
targetDepartmentId: e.target.value,
targetContractorId: '' // Reset contractor when department changes
})}
onChange={(e) =>
setFormData({
...formData,
targetDepartmentId: e.target.value,
targetContractorId: "", // Reset contractor when department changes
})}
options={[
{ value: '', label: 'Select department...' },
{ value: "", label: "Select department..." },
...departments
.filter(d => d.id !== selectedEmployee?.department_id)
.map(d => ({ value: String(d.id), label: d.name }))
.filter((d) =>
d.id !== selectedEmployee?.department_id
)
.map((d) => ({ value: String(d.id), label: d.name })),
]}
required
/>
<Select
label="Assign to Contractor (Optional)"
value={formData.targetContractorId}
onChange={(e) => setFormData({ ...formData, targetContractorId: e.target.value })}
onChange={(e) =>
setFormData({
...formData,
targetContractorId: e.target.value,
})}
options={[
{ value: '', label: 'No contractor' },
...targetContractors.map(c => ({ value: String(c.id), label: c.name }))
{ value: "", label: "No contractor" },
...targetContractors.map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
disabled={!formData.targetDepartmentId}
/>
@@ -500,13 +592,20 @@ export const EmployeeSwapPage: React.FC = () => {
<Select
label="Reason"
value={formData.swapReason}
onChange={(e) => setFormData({ ...formData, swapReason: e.target.value as SwapReason })}
onChange={(e) =>
setFormData({
...formData,
swapReason: e.target.value as SwapReason,
})}
options={[
{ value: '', label: 'Select reason...' },
{ value: 'LeftWork', label: 'Left Work Early' },
{ value: 'Sick', label: 'Sick / Unwell' },
{ value: 'FinishedEarly', label: 'Finished Work Early' },
{ value: 'Other', label: 'Other Reason' },
{ value: "", label: "Select reason..." },
{ value: "LeftWork", label: "Left Work Early" },
{ value: "Sick", label: "Sick / Unwell" },
{
value: "FinishedEarly",
label: "Finished Work Early",
},
{ value: "Other", label: "Other Reason" },
]}
required
/>
@@ -521,10 +620,13 @@ export const EmployeeSwapPage: React.FC = () => {
max="100"
step="5"
value={formData.workCompletionPercentage}
onChange={(e) => setFormData({
...formData,
workCompletionPercentage: parseInt(e.target.value)
})}
onChange={(e) =>
setFormData({
...formData,
workCompletionPercentage: parseInt(
e.target.value,
),
})}
className="flex-1"
/>
<span className="text-sm font-medium text-gray-700 w-12">
@@ -537,7 +639,11 @@ export const EmployeeSwapPage: React.FC = () => {
<Input
label="Additional Details (Optional)"
value={formData.reasonDetails}
onChange={(e) => setFormData({ ...formData, reasonDetails: e.target.value })}
onChange={(e) =>
setFormData({
...formData,
reasonDetails: e.target.value,
})}
placeholder="Provide more context about the swap..."
/>
</div>
@@ -553,35 +659,40 @@ export const EmployeeSwapPage: React.FC = () => {
label="Date"
type="date"
value={formData.swapDate}
onChange={(e) => setFormData({ ...formData, swapDate: e.target.value })}
onChange={(e) =>
setFormData({ ...formData, swapDate: e.target.value })}
required
/>
</div>
{/* Submit */}
<div className="flex justify-end gap-3 pt-4">
<Button
type="button"
variant="outline"
onClick={() => setActiveTab('list')}
<Button
type="button"
variant="outline"
onClick={() => setActiveTab("list")}
>
Cancel
</Button>
<Button
type="submit"
disabled={submitting || !formData.employeeId || !formData.targetDepartmentId || !formData.swapReason}
<Button
type="submit"
disabled={submitting || !formData.employeeId ||
!formData.targetDepartmentId || !formData.swapReason}
>
{submitting ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Creating...
</>
) : (
<>
<ArrowRightLeft size={16} className="mr-2" />
Create Swap
</>
)}
{submitting
? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2">
</div>
Creating...
</>
)
: (
<>
<ArrowRightLeft size={16} className="mr-2" />
Create Swap
</>
)}
</Button>
</div>
</form>

View File

@@ -1,34 +1,42 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import {
Users, Lock, Eye, EyeOff, XCircle, Mail, ArrowRight,
CheckCircle, X, Sparkles, Shield, KeyRound
} from 'lucide-react';
import React, { useEffect, useState } from "react";
import { useAuth } from "../contexts/AuthContext.tsx";
import {
ArrowRight,
CheckCircle,
Eye,
EyeOff,
KeyRound,
Lock,
Mail,
Shield,
Sparkles,
Users,
X,
XCircle,
} from "lucide-react";
export const LoginPage: React.FC = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [rememberMe, setRememberMe] = useState(false);
const [error, setError] = useState('');
const [error, setError] = useState("");
const [showError, setShowError] = useState(false);
const [loading, setLoading] = useState(false);
const { login } = useAuth();
// Forgot password modal state
const [showForgotModal, setShowForgotModal] = useState(false);
const [forgotEmail, setForgotEmail] = useState('');
const [forgotEmail, setForgotEmail] = useState("");
const [forgotLoading, setForgotLoading] = useState(false);
const [forgotSuccess, setForgotSuccess] = useState(false);
const [forgotError, setForgotError] = useState('');
const [forgotError, setForgotError] = useState("");
// Auto-hide error after 5 seconds
useEffect(() => {
if (error) {
setShowError(true);
const timer = setTimeout(() => {
setShowError(false);
setTimeout(() => setError(''), 300);
setTimeout(() => setError(""), 300);
}, 5000);
return () => clearTimeout(timer);
}
@@ -36,18 +44,20 @@ export const LoginPage: React.FC = () => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setError("");
setLoading(true);
try {
await login(username, password);
} catch (err: unknown) {
const error = err as Error;
const errorMessage = error.message?.includes('401') || error.message?.includes('Unauthorized') || error.message?.includes('Invalid')
? 'Invalid username or password'
: error.message || 'Login failed. Please check your credentials.';
const errorMessage = error.message?.includes("401") ||
error.message?.includes("Unauthorized") ||
error.message?.includes("Invalid")
? "Invalid username or password"
: error.message || "Login failed. Please check your credentials.";
setError(errorMessage);
console.error('Login error:', err);
console.error("Login error:", err);
} finally {
setLoading(false);
}
@@ -56,15 +66,15 @@ export const LoginPage: React.FC = () => {
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault();
setForgotLoading(true);
setForgotError('');
setForgotError("");
// Simulate API call (replace with actual API call)
try {
await new Promise(resolve => setTimeout(resolve, 1500));
await new Promise((resolve) => setTimeout(resolve, 1500));
// In a real app, you'd call: await api.requestPasswordReset(forgotEmail);
setForgotSuccess(true);
} catch {
setForgotError('Failed to send reset email. Please try again.');
setForgotError("Failed to send reset email. Please try again.");
} finally {
setForgotLoading(false);
}
@@ -72,9 +82,9 @@ export const LoginPage: React.FC = () => {
const closeForgotModal = () => {
setShowForgotModal(false);
setForgotEmail('');
setForgotEmail("");
setForgotSuccess(false);
setForgotError('');
setForgotError("");
};
return (
@@ -109,10 +119,15 @@ export const LoginPage: React.FC = () => {
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl shadow-lg mb-4 relative">
<Shield size={40} className="text-white" strokeWidth={1.5} />
<Sparkles size={16} className="text-yellow-300 absolute -top-1 -right-1 animate-pulse" />
<Sparkles
size={16}
className="text-yellow-300 absolute -top-1 -right-1 animate-pulse"
/>
</div>
<h1 className="text-2xl font-bold text-white mb-1">Welcome Back</h1>
<p className="text-blue-200/70 text-sm">Sign in to your account to continue</p>
<p className="text-blue-200/70 text-sm">
Sign in to your account to continue
</p>
</div>
{/* Login Form */}
@@ -139,7 +154,7 @@ export const LoginPage: React.FC = () => {
<Lock size={20} />
</div>
<input
type={showPassword ? 'text' : 'password'}
type={showPassword ? "text" : "password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
@@ -165,7 +180,9 @@ export const LoginPage: React.FC = () => {
onChange={(e) => setRememberMe(e.target.checked)}
className="w-4 h-4 bg-white/10 border-white/30 rounded text-blue-500 focus:ring-blue-400/50 focus:ring-offset-0"
/>
<span className="ml-2 text-blue-200/70 group-hover:text-blue-200 transition-colors">Remember me</span>
<span className="ml-2 text-blue-200/70 group-hover:text-blue-200 transition-colors">
Remember me
</span>
</label>
<button
type="button"
@@ -182,17 +199,22 @@ export const LoginPage: React.FC = () => {
disabled={loading || !username || !password}
className="w-full bg-gradient-to-r from-blue-500 via-blue-600 to-purple-600 hover:from-blue-600 hover:via-blue-700 hover:to-purple-700 text-white font-semibold py-4 rounded-xl shadow-lg hover:shadow-blue-500/25 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 group"
>
{loading ? (
<>
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
Signing in...
</>
) : (
<>
Sign In
<ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
</>
)}
{loading
? (
<>
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
Signing in...
</>
)
: (
<>
Sign In
<ArrowRight
size={18}
className="group-hover:translate-x-1 transition-transform"
/>
</>
)}
</button>
</form>
@@ -217,7 +239,11 @@ export const LoginPage: React.FC = () => {
{/* Error Toast */}
{error && (
<div className={`fixed top-6 left-1/2 transform -translate-x-1/2 z-50 transition-all duration-300 ${showError ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-4'}`}>
<div
className={`fixed top-6 left-1/2 transform -translate-x-1/2 z-50 transition-all duration-300 ${
showError ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-4"
}`}
>
<div className="bg-gradient-to-r from-red-500 to-red-600 text-white px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-3 min-w-[320px] border border-red-400/30">
<div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center flex-shrink-0">
<XCircle size={24} />
@@ -234,11 +260,11 @@ export const LoginPage: React.FC = () => {
{showForgotModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
{/* Backdrop */}
<div
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={closeForgotModal}
/>
{/* Modal */}
<div className="relative bg-slate-800/90 backdrop-blur-xl rounded-2xl shadow-2xl p-8 w-full max-w-md border border-white/10 animate-in fade-in zoom-in duration-200">
{/* Close button */}
@@ -249,91 +275,105 @@ export const LoginPage: React.FC = () => {
<X size={24} />
</button>
{!forgotSuccess ? (
<>
{/* Header */}
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-amber-500 to-orange-600 rounded-2xl shadow-lg mb-4">
<KeyRound size={32} className="text-white" />
</div>
<h2 className="text-xl font-bold text-white mb-2">Forgot Password?</h2>
<p className="text-gray-400 text-sm">
Enter your email address and we'll send you instructions to reset your password.
</p>
</div>
{/* Form */}
<form onSubmit={handleForgotPassword} className="space-y-4">
<div className="relative">
<div className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
<Mail size={20} />
{!forgotSuccess
? (
<>
{/* Header */}
<div className="text-center mb-6">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-amber-500 to-orange-600 rounded-2xl shadow-lg mb-4">
<KeyRound size={32} className="text-white" />
</div>
<input
type="email"
value={forgotEmail}
onChange={(e) => setForgotEmail(e.target.value)}
placeholder="Enter your email"
required
className="w-full pl-12 pr-4 py-4 bg-white/10 border border-white/20 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all"
/>
<h2 className="text-xl font-bold text-white mb-2">
Forgot Password?
</h2>
<p className="text-gray-400 text-sm">
Enter your email address and we'll send you instructions
to reset your password.
</p>
</div>
{forgotError && (
<p className="text-red-400 text-sm text-center">{forgotError}</p>
)}
{/* Form */}
<form onSubmit={handleForgotPassword} className="space-y-4">
<div className="relative">
<div className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
<Mail size={20} />
</div>
<input
type="email"
value={forgotEmail}
onChange={(e) => setForgotEmail(e.target.value)}
placeholder="Enter your email"
required
className="w-full pl-12 pr-4 py-4 bg-white/10 border border-white/20 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-400/50 focus:border-amber-400/50 transition-all"
/>
</div>
<button
type="submit"
disabled={forgotLoading || !forgotEmail}
className="w-full bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-semibold py-4 rounded-xl shadow-lg transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{forgotLoading ? (
<>
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
Sending...
</>
) : (
<>
<Mail size={18} />
Send Reset Link
</>
{forgotError && (
<p className="text-red-400 text-sm text-center">
{forgotError}
</p>
)}
</button>
</form>
{/* Back to login */}
<button
onClick={closeForgotModal}
className="w-full mt-4 text-gray-400 hover:text-white text-sm transition-colors"
>
← Back to login
</button>
</>
) : (
/* Success State */
<div className="text-center py-4">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-full shadow-lg mb-4">
<CheckCircle size={32} className="text-white" />
<button
type="submit"
disabled={forgotLoading || !forgotEmail}
className="w-full bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-semibold py-4 rounded-xl shadow-lg transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
>
{forgotLoading
? (
<>
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
Sending...
</>
)
: (
<>
<Mail size={18} />
Send Reset Link
</>
)}
</button>
</form>
{/* Back to login */}
<button
onClick={closeForgotModal}
className="w-full mt-4 text-gray-400 hover:text-white text-sm transition-colors"
>
← Back to login
</button>
</>
)
: (
/* Success State */
<div className="text-center py-4">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-full shadow-lg mb-4">
<CheckCircle size={32} className="text-white" />
</div>
<h2 className="text-xl font-bold text-white mb-2">
Check Your Email
</h2>
<p className="text-gray-400 text-sm mb-6">
We've sent password reset instructions to<br />
<span className="text-white font-medium">
{forgotEmail}
</span>
</p>
<button
onClick={closeForgotModal}
className="w-full bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white font-semibold py-4 rounded-xl shadow-lg transition-all duration-300"
>
Back to Login
</button>
</div>
<h2 className="text-xl font-bold text-white mb-2">Check Your Email</h2>
<p className="text-gray-400 text-sm mb-6">
We've sent password reset instructions to<br />
<span className="text-white font-medium">{forgotEmail}</span>
</p>
<button
onClick={closeForgotModal}
className="w-full bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 text-white font-semibold py-4 rounded-xl shadow-lg transition-all duration-300"
>
Back to Login
</button>
</div>
)}
)}
</div>
</div>
)}
{/* CSS for floating animation */}
<style>{`
<style>
{`
@keyframes float {
0%, 100% { transform: translateY(0px) rotate(0deg); opacity: 0.2; }
50% { transform: translateY(-20px) rotate(180deg); opacity: 0.5; }
@@ -341,7 +381,8 @@ export const LoginPage: React.FC = () => {
.animate-float {
animation: float linear infinite;
}
`}</style>
`}
</style>
</div>
);
};

View File

@@ -1,36 +1,43 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Plus, RefreshCw, Trash2, Edit, DollarSign, Search } from 'lucide-react';
import { Card, CardHeader, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select } from '../components/ui/Input';
import { api } from '../services/api';
import { useDepartments, useSubDepartments } from '../hooks/useDepartments';
import { useActivities } from '../hooks/useActivities';
import { useAuth } from '../contexts/AuthContext';
import React, { useEffect, useMemo, useState } from "react";
import { DollarSign, Edit, RefreshCw, Search, Trash2 } from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useDepartments, useSubDepartments } from "../hooks/useDepartments.ts";
import { useActivities } from "../hooks/useActivities.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
export const RatesPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'list' | 'add'>('list');
const [activeTab, setActiveTab] = useState<"list" | "add">("list");
const { user } = useAuth();
const { departments } = useDepartments();
const [rates, setRates] = useState<any[]>([]);
const [contractors, setContractors] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [error, setError] = useState("");
// Form state
const [formData, setFormData] = useState({
contractorId: '',
subDepartmentId: '',
activity: '',
rate: '',
effectiveDate: new Date().toISOString().split('T')[0],
contractorId: "",
subDepartmentId: "",
activity: "",
rate: "",
effectiveDate: new Date().toISOString().split("T")[0],
});
const [selectedDept, setSelectedDept] = useState('');
const [selectedDept, setSelectedDept] = useState("");
const { subDepartments } = useSubDepartments(selectedDept);
const { activities } = useActivities(formData.subDepartmentId);
const [formError, setFormError] = useState('');
const [formError, setFormError] = useState("");
const [formLoading, setFormLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [searchQuery, setSearchQuery] = useState("");
// Edit mode
const [editingId, setEditingId] = useState<number | null>(null);
@@ -38,12 +45,12 @@ export const RatesPage: React.FC = () => {
// Fetch rates
const fetchRates = async () => {
setLoading(true);
setError('');
setError("");
try {
const data = await api.getContractorRates();
setRates(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch rates');
setError(err.message || "Failed to fetch rates");
} finally {
setLoading(false);
}
@@ -52,10 +59,10 @@ export const RatesPage: React.FC = () => {
// Fetch contractors
const fetchContractors = async () => {
try {
const data = await api.getUsers({ role: 'Contractor' });
const data = await api.getUsers({ role: "Contractor" });
setContractors(data);
} catch (err) {
console.error('Failed to fetch contractors:', err);
console.error("Failed to fetch contractors:", err);
}
};
@@ -66,54 +73,62 @@ export const RatesPage: React.FC = () => {
// Auto-select department for supervisors
useEffect(() => {
if (user?.role === 'Supervisor' && user?.department_id) {
if (user?.role === "Supervisor" && user?.department_id) {
setSelectedDept(String(user.department_id));
}
}, [user]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const handleInputChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { name, value } = e.target;
// Auto-select department when contractor is selected
if (name === 'contractorId' && value) {
const selectedContractor = contractors.find(c => String(c.id) === value);
if (name === "contractorId" && value) {
const selectedContractor = contractors.find((c) =>
String(c.id) === value
);
if (selectedContractor?.department_id) {
setSelectedDept(String(selectedContractor.department_id));
// Clear sub-department and activity when contractor changes
setFormData(prev => ({ ...prev, [name]: value, subDepartmentId: '', activity: '' }));
setFormData((prev) => ({
...prev,
[name]: value,
subDepartmentId: "",
activity: "",
}));
} else {
setFormData(prev => ({ ...prev, [name]: value }));
setFormData((prev) => ({ ...prev, [name]: value }));
}
}
// Clear activity when sub-department changes
else if (name === 'subDepartmentId') {
setFormData(prev => ({ ...prev, [name]: value, activity: '' }));
} // Clear activity when sub-department changes
else if (name === "subDepartmentId") {
setFormData((prev) => ({ ...prev, [name]: value, activity: "" }));
} else {
setFormData(prev => ({ ...prev, [name]: value }));
setFormData((prev) => ({ ...prev, [name]: value }));
}
setFormError('');
setFormError("");
};
const resetForm = () => {
setFormData({
contractorId: '',
subDepartmentId: '',
activity: '',
rate: '',
effectiveDate: new Date().toISOString().split('T')[0],
contractorId: "",
subDepartmentId: "",
activity: "",
rate: "",
effectiveDate: new Date().toISOString().split("T")[0],
});
setEditingId(null);
setFormError('');
setFormError("");
};
const handleSubmit = async () => {
if (!formData.contractorId || !formData.rate || !formData.effectiveDate) {
setFormError('Contractor, rate, and effective date are required');
setFormError("Contractor, rate, and effective date are required");
return;
}
setFormLoading(true);
setFormError('');
setFormError("");
try {
if (editingId) {
@@ -125,7 +140,9 @@ export const RatesPage: React.FC = () => {
} else {
await api.setContractorRate({
contractorId: parseInt(formData.contractorId),
subDepartmentId: formData.subDepartmentId ? parseInt(formData.subDepartmentId) : undefined,
subDepartmentId: formData.subDepartmentId
? parseInt(formData.subDepartmentId)
: undefined,
activity: formData.activity || undefined,
rate: parseFloat(formData.rate),
effectiveDate: formData.effectiveDate,
@@ -133,10 +150,10 @@ export const RatesPage: React.FC = () => {
}
resetForm();
setActiveTab('list');
setActiveTab("list");
fetchRates();
} catch (err: any) {
setFormError(err.message || 'Failed to save rate');
setFormError(err.message || "Failed to save rate");
} finally {
setFormLoading(false);
}
@@ -145,32 +162,36 @@ export const RatesPage: React.FC = () => {
const handleEdit = (rate: any) => {
setFormData({
contractorId: String(rate.contractor_id),
subDepartmentId: rate.sub_department_id ? String(rate.sub_department_id) : '',
activity: rate.activity || '',
subDepartmentId: rate.sub_department_id
? String(rate.sub_department_id)
: "",
activity: rate.activity || "",
rate: String(rate.rate),
effectiveDate: rate.effective_date?.split('T')[0] || new Date().toISOString().split('T')[0],
effectiveDate: rate.effective_date?.split("T")[0] ||
new Date().toISOString().split("T")[0],
});
setEditingId(rate.id);
setActiveTab('add');
setActiveTab("add");
};
const handleDelete = async (id: number) => {
if (!confirm('Are you sure you want to delete this rate?')) return;
if (!confirm("Are you sure you want to delete this rate?")) return;
try {
await api.deleteContractorRate(id);
fetchRates();
} catch (err: any) {
alert(err.message || 'Failed to delete rate');
alert(err.message || "Failed to delete rate");
}
};
const canManageRates = user?.role === 'SuperAdmin' || user?.role === 'Supervisor';
const canManageRates = user?.role === "SuperAdmin" ||
user?.role === "Supervisor";
// Filter rates based on search
const filteredRates = useMemo(() => {
if (!searchQuery) return rates;
const query = searchQuery.toLowerCase();
return rates.filter(rate =>
return rates.filter((rate) =>
rate.contractor_name?.toLowerCase().includes(query) ||
rate.sub_department_name?.toLowerCase().includes(query) ||
rate.activity?.toLowerCase().includes(query)
@@ -183,36 +204,42 @@ export const RatesPage: React.FC = () => {
<div className="border-b border-gray-200">
<div className="flex space-x-8 px-6">
<button
onClick={() => { setActiveTab('list'); resetForm(); }}
onClick={() => {
setActiveTab("list");
resetForm();
}}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'list'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "list"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
Rate List
</button>
{canManageRates && (
<button
onClick={() => setActiveTab('add')}
onClick={() => setActiveTab("add")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'add'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "add"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
{editingId ? 'Edit Rate' : 'Add Rate'}
{editingId ? "Edit Rate" : "Add Rate"}
</button>
)}
</div>
</div>
<CardContent>
{activeTab === 'list' && (
{activeTab === "list" && (
<div>
<div className="flex gap-4 mb-4">
<div className="relative min-w-[300px] flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by contractor, sub-department, activity..."
@@ -226,7 +253,7 @@ export const RatesPage: React.FC = () => {
Refresh
</Button>
</div>
<div className="mb-4 text-sm text-gray-600">
Total Rates: {filteredRates.length}
</div>
@@ -237,91 +264,113 @@ export const RatesPage: React.FC = () => {
</div>
)}
{loading ? (
<div className="text-center py-8">Loading rates...</div>
) : filteredRates.length > 0 ? (
<Table>
<TableHeader>
<TableHead>Contractor</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate Type</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
{canManageRates && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredRates.map((rate) => (
<TableRow key={rate.id}>
<TableCell className="font-medium">{rate.contractor_name}</TableCell>
<TableCell>{rate.sub_department_name || '-'}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
rate.unit_of_measurement === 'Per Bag'
? 'bg-blue-100 text-blue-700'
: 'bg-gray-100 text-gray-700'
}`}>
{rate.activity || 'Standard'}
</span>
</TableCell>
<TableCell>
<span className="text-xs text-gray-500">
{rate.unit_of_measurement === 'Per Bag'
? 'Per Unit'
: 'Flat Rate'}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">{rate.rate}</span>
</TableCell>
<TableCell>{new Date(rate.effective_date).toLocaleDateString()}</TableCell>
{canManageRates && (
<TableCell>
<div className="flex gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(rate)}
className="text-blue-600"
title="Edit"
>
<Edit size={14} />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(rate.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
{loading
? <div className="text-center py-8">Loading rates...</div>
: filteredRates.length > 0
? (
<Table>
<TableHeader>
<TableHead>Contractor</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate Type</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
{canManageRates && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredRates.map((rate) => (
<TableRow key={rate.id}>
<TableCell className="font-medium">
{rate.contractor_name}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="text-center py-8 text-gray-500">
{searchQuery ? 'No matching rates found' : 'No rates configured yet. Add one to get started!'}
</div>
)}
<TableCell>
{rate.sub_department_name || "-"}
</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
rate.unit_of_measurement === "Per Bag"
? "bg-blue-100 text-blue-700"
: "bg-gray-100 text-gray-700"
}`}
>
{rate.activity || "Standard"}
</span>
</TableCell>
<TableCell>
<span className="text-xs text-gray-500">
{rate.unit_of_measurement === "Per Bag"
? "Per Unit"
: "Flat Rate"}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">
{rate.rate}
</span>
</TableCell>
<TableCell>
{new Date(rate.effective_date).toLocaleDateString()}
</TableCell>
{canManageRates && (
<TableCell>
<div className="flex gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(rate)}
className="text-blue-600"
title="Edit"
>
<Edit size={14} />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(rate.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)
: (
<div className="text-center py-8 text-gray-500">
{searchQuery
? "No matching rates found"
: "No rates configured yet. Add one to get started!"}
</div>
)}
</div>
)}
{activeTab === 'add' && canManageRates && (
{activeTab === "add" && canManageRates && (
<div className="max-w-2xl space-y-6">
<h3 className="text-lg font-semibold text-gray-800">
{editingId ? 'Edit Rate' : 'Add New Rate'}
{editingId ? "Edit Rate" : "Add New Rate"}
</h3>
<div className="p-4 bg-blue-50 border border-blue-200 rounded-md">
<h4 className="font-medium text-blue-800 mb-2">Rate Calculation Info</h4>
<h4 className="font-medium text-blue-800 mb-2">
Rate Calculation Info
</h4>
<ul className="text-sm text-blue-700 space-y-1">
<li><strong>Per Bag Activities:</strong> Total = Units × Rate per Unit</li>
<li><strong>Fixed Rate Activities:</strong> Total = Flat Rate (no unit calculation)</li>
<li>
<strong>Per Bag Activities:</strong>{" "}
Total = Units × Rate per Unit
</li>
<li>
<strong>Fixed Rate Activities:</strong>{" "}
Total = Flat Rate (no unit calculation)
</li>
</ul>
</div>
@@ -340,27 +389,37 @@ export const RatesPage: React.FC = () => {
required
disabled={!!editingId}
options={[
{ value: '', label: 'Select Contractor' },
...contractors.map(c => ({ value: String(c.id), label: c.name }))
{ value: "", label: "Select Contractor" },
...contractors.map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
{user?.role === 'Supervisor' ? (
<Input
label="Department"
value={departments.find(d => d.id === user?.department_id)?.name || 'Loading...'}
disabled
/>
) : (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: '', label: 'Select Department' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
]}
/>
)}
{user?.role === "Supervisor"
? (
<Input
label="Department"
value={departments.find((d) =>
d.id === user?.department_id
)?.name || "Loading..."}
disabled
/>
)
: (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: "", label: "Select Department" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
)}
<Select
label="Sub-Department"
name="subDepartmentId"
@@ -368,8 +427,11 @@ export const RatesPage: React.FC = () => {
onChange={handleInputChange}
disabled={!!editingId}
options={[
{ value: '', label: 'Select Sub-Department (Optional)' },
...subDepartments.map(s => ({ value: String(s.id), label: s.name }))
{ value: "", label: "Select Sub-Department (Optional)" },
...subDepartments.map((s) => ({
value: String(s.id),
label: s.name,
})),
]}
/>
<Select
@@ -379,18 +441,29 @@ export const RatesPage: React.FC = () => {
onChange={handleInputChange}
disabled={!formData.subDepartmentId}
options={[
{ value: '', label: formData.subDepartmentId ? 'Select Activity (Optional)' : 'Select Sub-Department First' },
...activities.map(a => ({
value: a.name,
label: `${a.name} (${a.unit_of_measurement === 'Per Bag' ? 'per unit × rate' : 'flat rate'})`
}))
{
value: "",
label: formData.subDepartmentId
? "Select Activity (Optional)"
: "Select Sub-Department First",
},
...activities.map((a) => ({
value: a.name,
label: `${a.name} (${
a.unit_of_measurement === "Per Bag"
? "per unit × rate"
: "flat rate"
})`,
})),
]}
/>
<Input
label={(() => {
const selectedActivity = activities.find(a => a.name === formData.activity);
return selectedActivity?.unit_of_measurement === 'Per Bag'
? "Rate per Unit (₹)"
const selectedActivity = activities.find((a) =>
a.name === formData.activity
);
return selectedActivity?.unit_of_measurement === "Per Bag"
? "Rate per Unit (₹)"
: "Rate Amount (₹)";
})()}
name="rate"
@@ -411,14 +484,20 @@ export const RatesPage: React.FC = () => {
</div>
<div className="flex justify-end gap-4">
<Button variant="outline" onClick={() => { setActiveTab('list'); resetForm(); }}>
<Button
variant="outline"
onClick={() => {
setActiveTab("list");
resetForm();
}}
>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={formLoading}>
{formLoading ? 'Saving...' : (
{formLoading ? "Saving..." : (
<>
<DollarSign size={16} className="mr-2" />
{editingId ? 'Update Rate' : 'Add Rate'}
{editingId ? "Update Rate" : "Add Rate"}
</>
)}
</Button>

View File

@@ -1,55 +1,104 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Download, RefreshCw, Search, FileSpreadsheet, Filter } from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select } from '../components/ui/Input';
import { api } from '../services/api';
import { useDepartments } from '../hooks/useDepartments';
import { useAuth } from '../contexts/AuthContext';
import { exportWorkReportToXLSX, exportAllocationsToXLSX } from '../utils/excelExport';
import React, { useEffect, useMemo, useState } from "react";
import {
Download,
FileSpreadsheet,
Filter,
RefreshCw,
Search,
} from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useDepartments } from "../hooks/useDepartments.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
import {
exportAllocationsToXLSX,
exportWorkReportToXLSX,
} from "../utils/excelExport.ts";
export const ReportingPage: React.FC = () => {
const { user } = useAuth();
const { departments } = useDepartments();
const [allocations, setAllocations] = useState<any[]>([]);
const [summary, setSummary] = useState<{ totalAllocations: number; totalAmount: string; totalUnits: string } | null>(null);
const [summary, setSummary] = useState<
{ totalAllocations: number; totalAmount: string; totalUnits: string } | null
>(null);
const [contractors, setContractors] = useState<any[]>([]);
const [employees, setEmployees] = useState<any[]>([]);
const [subDepartments, setSubDepartments] = useState<any[]>([]);
const [activities, setActivities] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [error, setError] = useState("");
const [searchQuery, setSearchQuery] = useState("");
// Filters
const [filters, setFilters] = useState({
startDate: '',
endDate: '',
departmentId: '',
contractorId: '',
startDate: "",
endDate: "",
departmentId: "",
contractorId: "",
employeeId: "",
subDepartmentId: "",
activity: "",
});
const isSuperAdmin = user?.role === 'SuperAdmin';
const isSupervisor = user?.role === "Supervisor";
const isContractor = user?.role === "Contractor";
// Fetch contractors
// Fetch filter options
useEffect(() => {
api.getUsers({ role: 'Contractor' }).then(setContractors).catch(console.error);
api.getUsers({ role: "Contractor" }).then(setContractors).catch(
console.error,
);
api.getUsers({ role: "Employee" }).then(setEmployees).catch(console.error);
api.getAllSubDepartments().then(setSubDepartments).catch(console.error);
}, []);
// Fetch report data
const fetchReport = async () => {
setLoading(true);
setError('');
setError("");
try {
const params: any = {};
if (filters.startDate) params.startDate = filters.startDate;
if (filters.endDate) params.endDate = filters.endDate;
if (filters.departmentId && isSuperAdmin) params.departmentId = parseInt(filters.departmentId);
if (filters.contractorId) params.contractorId = parseInt(filters.contractorId);
// Department filter - use user's department if Supervisor, otherwise use filter
const deptId = isSupervisor
? user?.department_id
: (filters.departmentId ? parseInt(filters.departmentId) : null);
if (deptId) params.departmentId = deptId;
// Contractor filter - use user's id if Contractor, otherwise use filter
const contractorIdValue = isContractor
? user?.id
: (filters.contractorId ? parseInt(filters.contractorId) : null);
if (contractorIdValue) params.contractorId = contractorIdValue;
if (filters.employeeId) params.employeeId = parseInt(filters.employeeId);
const data = await api.getCompletedAllocationsReport(params);
setAllocations(data.allocations);
setSummary(data.summary);
// Extract unique activities from allocations for the filter dropdown
const uniqueActivities = [
...new Set(
data.allocations.map((a: any) => a.activity).filter(Boolean),
),
] as string[];
setActivities(uniqueActivities);
} catch (err: any) {
setError(err.message || 'Failed to fetch report');
setError(err.message || "Failed to fetch report");
} finally {
setLoading(false);
}
@@ -59,53 +108,75 @@ export const ReportingPage: React.FC = () => {
fetchReport();
}, []);
// Filter allocations based on search
// Filter allocations based on search and dropdown filters
const filteredAllocations = useMemo(() => {
if (!searchQuery) return allocations;
const query = searchQuery.toLowerCase();
return allocations.filter(a =>
a.employee_name?.toLowerCase().includes(query) ||
a.contractor_name?.toLowerCase().includes(query) ||
a.sub_department_name?.toLowerCase().includes(query) ||
a.activity?.toLowerCase().includes(query) ||
a.department_name?.toLowerCase().includes(query)
);
}, [allocations, searchQuery]);
let result = allocations;
// Apply search filter
if (searchQuery) {
const query = searchQuery.toLowerCase();
result = result.filter((a) =>
a.employee_name?.toLowerCase().includes(query) ||
a.contractor_name?.toLowerCase().includes(query) ||
a.sub_department_name?.toLowerCase().includes(query) ||
a.activity?.toLowerCase().includes(query) ||
a.department_name?.toLowerCase().includes(query)
);
}
// Apply sub-department filter (client-side)
if (filters.subDepartmentId) {
result = result.filter((a) =>
a.sub_department_id === parseInt(filters.subDepartmentId)
);
}
// Apply activity filter (client-side)
if (filters.activity) {
result = result.filter((a) => a.activity === filters.activity);
}
return result;
}, [allocations, searchQuery, filters.subDepartmentId, filters.activity]);
// Get selected department name
const selectedDeptName = filters.departmentId
? departments.find(d => d.id === parseInt(filters.departmentId))?.name || 'All Departments'
: user?.role === 'Supervisor'
? departments.find(d => d.id === user?.department_id)?.name || 'Department'
: 'All Departments';
const selectedDeptName = filters.departmentId
? departments.find((d) => d.id === parseInt(filters.departmentId))?.name ||
"All Departments"
: user?.role === "Supervisor"
? departments.find((d) => d.id === user?.department_id)?.name ||
"Department"
: "All Departments";
// Export to Excel (XLSX format) - Formatted Report
const exportFormattedReport = () => {
if (filteredAllocations.length === 0) {
alert('No data to export');
alert("No data to export");
return;
}
exportWorkReportToXLSX(
filteredAllocations,
selectedDeptName,
{ startDate: filters.startDate, endDate: filters.endDate }
{ startDate: filters.startDate, endDate: filters.endDate },
);
};
// Export to Excel (XLSX format) - Simple List
const exportSimpleList = () => {
if (filteredAllocations.length === 0) {
alert('No data to export');
alert("No data to export");
return;
}
exportAllocationsToXLSX(filteredAllocations);
};
const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const handleFilterChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { name, value } = e.target;
setFilters(prev => ({ ...prev, [name]: value }));
setFilters((prev) => ({ ...prev, [name]: value }));
};
const applyFilters = () => {
@@ -114,10 +185,13 @@ export const ReportingPage: React.FC = () => {
const clearFilters = () => {
setFilters({
startDate: '',
endDate: '',
departmentId: '',
contractorId: '',
startDate: "",
endDate: "",
departmentId: "",
contractorId: "",
employeeId: "",
subDepartmentId: "",
activity: "",
});
setTimeout(fetchReport, 0);
};
@@ -129,14 +203,23 @@ export const ReportingPage: React.FC = () => {
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<FileSpreadsheet className="text-green-600" size={24} />
<h2 className="text-xl font-semibold text-gray-800">Work Allocation Reports</h2>
<h2 className="text-xl font-semibold text-gray-800">
Work Allocation Reports
</h2>
</div>
<div className="flex gap-2">
<Button onClick={exportFormattedReport} disabled={filteredAllocations.length === 0}>
<Button
onClick={exportFormattedReport}
disabled={filteredAllocations.length === 0}
>
<Download size={16} className="mr-2" />
Export Report (XLSX)
</Button>
<Button variant="outline" onClick={exportSimpleList} disabled={filteredAllocations.length === 0}>
<Button
variant="outline"
onClick={exportSimpleList}
disabled={filteredAllocations.length === 0}
>
<Download size={16} className="mr-2" />
Export List
</Button>
@@ -153,7 +236,9 @@ export const ReportingPage: React.FC = () => {
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<label className="block text-sm font-medium text-gray-700 mb-1">
Start Date
</label>
<Input
type="date"
name="startDate"
@@ -162,7 +247,9 @@ export const ReportingPage: React.FC = () => {
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
<label className="block text-sm font-medium text-gray-700 mb-1">
End Date
</label>
<Input
type="date"
name="endDate"
@@ -170,26 +257,74 @@ export const ReportingPage: React.FC = () => {
onChange={handleFilterChange}
/>
</div>
{isSuperAdmin && (
<Select
label="Department"
name="departmentId"
value={filters.departmentId}
onChange={handleFilterChange}
options={[
{ value: '', label: 'All Departments' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
]}
/>
)}
<Select
label="Department"
name="departmentId"
value={isSupervisor
? String(user?.department_id || "")
: filters.departmentId}
onChange={handleFilterChange}
disabled={isSupervisor}
options={[
{ value: "", label: "All Departments" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
<Select
label="Contractor"
name="contractorId"
value={filters.contractorId}
value={isContractor
? String(user?.id || "")
: filters.contractorId}
onChange={handleFilterChange}
disabled={isContractor}
options={[
{ value: "", label: "All Contractors" },
...contractors.map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
</div>
<div className="grid grid-cols-2 md:grid-cols-3 gap-4 mt-4">
<Select
label="Employee"
name="employeeId"
value={filters.employeeId}
onChange={handleFilterChange}
options={[
{ value: '', label: 'All Contractors' },
...contractors.map(c => ({ value: String(c.id), label: c.name }))
{ value: "", label: "All Employees" },
...employees.map((e) => ({
value: String(e.id),
label: e.name,
})),
]}
/>
<Select
label="Sub-Department"
name="subDepartmentId"
value={filters.subDepartmentId}
onChange={handleFilterChange}
options={[
{ value: "", label: "All Sub-Departments" },
...subDepartments.map((sd) => ({
value: String(sd.id),
label: sd.name,
})),
]}
/>
<Select
label="Activity"
name="activity"
value={filters.activity}
onChange={handleFilterChange}
options={[
{ value: "", label: "All Activities" },
...activities.map((a) => ({ value: a, label: a })),
]}
/>
</div>
@@ -207,16 +342,28 @@ export const ReportingPage: React.FC = () => {
{summary && (
<div className="grid grid-cols-3 gap-4 mb-6">
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div className="text-sm text-blue-600 font-medium">Total Completed</div>
<div className="text-2xl font-bold text-blue-800">{summary.totalAllocations}</div>
<div className="text-sm text-blue-600 font-medium">
Total Completed
</div>
<div className="text-2xl font-bold text-blue-800">
{summary.totalAllocations}
</div>
</div>
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
<div className="text-sm text-green-600 font-medium">Total Amount</div>
<div className="text-2xl font-bold text-green-800">{parseFloat(summary.totalAmount).toLocaleString()}</div>
<div className="text-sm text-green-600 font-medium">
Total Amount
</div>
<div className="text-2xl font-bold text-green-800">
{parseFloat(summary.totalAmount).toLocaleString()}
</div>
</div>
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
<div className="text-sm text-purple-600 font-medium">Total Units</div>
<div className="text-2xl font-bold text-purple-800">{parseFloat(summary.totalUnits).toLocaleString()}</div>
<div className="text-sm text-purple-600 font-medium">
Total Units
</div>
<div className="text-2xl font-bold text-purple-800">
{parseFloat(summary.totalUnits).toLocaleString()}
</div>
</div>
</div>
)}
@@ -224,7 +371,10 @@ export const ReportingPage: React.FC = () => {
{/* Search and Refresh */}
<div className="flex gap-4 mb-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by employee, contractor, department..."
@@ -247,66 +397,86 @@ export const ReportingPage: React.FC = () => {
)}
{/* Table */}
{loading ? (
<div className="text-center py-8">Loading report data...</div>
) : filteredAllocations.length > 0 ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>Employee</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Assigned</TableHead>
<TableHead>Completed</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Units</TableHead>
<TableHead>Total ()</TableHead>
</TableHeader>
<TableBody>
{filteredAllocations.map((allocation) => {
const rate = parseFloat(allocation.rate) || 0;
const units = parseFloat(allocation.units) || 0;
const total = parseFloat(allocation.total_amount) || rate;
{loading
? <div className="text-center py-8">Loading report data...</div>
: filteredAllocations.length > 0
? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>Employee</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Assigned</TableHead>
<TableHead>Completed</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Units</TableHead>
<TableHead>Total ()</TableHead>
</TableHeader>
<TableBody>
{filteredAllocations.map((allocation) => {
const rate = parseFloat(allocation.rate) || 0;
const units = parseFloat(allocation.units) || 0;
const total = parseFloat(allocation.total_amount) || rate;
return (
<TableRow key={allocation.id}>
<TableCell>{allocation.id}</TableCell>
<TableCell className="font-medium">{allocation.employee_name || '-'}</TableCell>
<TableCell>{allocation.contractor_name || '-'}</TableCell>
<TableCell>{allocation.department_name || '-'}</TableCell>
<TableCell>{allocation.sub_department_name || '-'}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
allocation.activity === 'Loading' || allocation.activity === 'Unloading'
? 'bg-purple-100 text-purple-700'
: 'bg-gray-100 text-gray-700'
}`}>
{allocation.activity || 'Standard'}
</span>
</TableCell>
<TableCell>{new Date(allocation.assigned_date).toLocaleDateString()}</TableCell>
<TableCell>
{allocation.completion_date
? new Date(allocation.completion_date).toLocaleDateString()
: '-'}
</TableCell>
<TableCell>{rate.toFixed(2)}</TableCell>
<TableCell>{units > 0 ? units : '-'}</TableCell>
<TableCell className="font-semibold text-green-600">{total.toFixed(2)}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
) : (
<div className="text-center py-8 text-gray-500">
No completed work allocations found. Adjust your filters or check back later.
</div>
)}
return (
<TableRow key={allocation.id}>
<TableCell>{allocation.id}</TableCell>
<TableCell className="font-medium">
{allocation.employee_name || "-"}
</TableCell>
<TableCell>
{allocation.contractor_name || "-"}
</TableCell>
<TableCell>
{allocation.department_name || "-"}
</TableCell>
<TableCell>
{allocation.sub_department_name || "-"}
</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
allocation.activity === "Loading" ||
allocation.activity === "Unloading"
? "bg-purple-100 text-purple-700"
: "bg-gray-100 text-gray-700"
}`}
>
{allocation.activity || "Standard"}
</span>
</TableCell>
<TableCell>
{new Date(allocation.assigned_date)
.toLocaleDateString()}
</TableCell>
<TableCell>
{allocation.completion_date
? new Date(allocation.completion_date)
.toLocaleDateString()
: "-"}
</TableCell>
<TableCell>{rate.toFixed(2)}</TableCell>
<TableCell>{units > 0 ? units : "-"}</TableCell>
<TableCell className="font-semibold text-green-600">
{total.toFixed(2)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
)
: (
<div className="text-center py-8 text-gray-500">
No completed work allocations found. Adjust your filters or
check back later.
</div>
)}
</CardContent>
</Card>
</div>

View File

@@ -1,54 +1,72 @@
import React, { useState, useEffect, useMemo } from 'react';
import { RefreshCw, Trash2, Edit, DollarSign, Search, Scale, ArrowUpDown } from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select } from '../components/ui/Input';
import { api } from '../services/api';
import { useDepartments, useSubDepartments } from '../hooks/useDepartments';
import { useActivities } from '../hooks/useActivities';
import { useAuth } from '../contexts/AuthContext';
import React, { useEffect, useMemo, useState } from "react";
import {
ArrowUpDown,
DollarSign,
Edit,
RefreshCw,
Scale,
Search,
Trash2,
} from "lucide-react";
import { Card, CardContent } from "../components/ui/Card.tsx";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select } from "../components/ui/Input.tsx";
import { api } from "../services/api.ts";
import { useDepartments, useSubDepartments } from "../hooks/useDepartments.ts";
import { useActivities } from "../hooks/useActivities.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
export const StandardRatesPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'list' | 'add' | 'compare'>('list');
const [activeTab, setActiveTab] = useState<"list" | "add" | "compare">(
"list",
);
const { user } = useAuth();
const { departments } = useDepartments();
const [standardRates, setStandardRates] = useState<any[]>([]);
const [contractors, setContractors] = useState<any[]>([]);
const [comparisons, setComparisons] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [error, setError] = useState("");
const [searchQuery, setSearchQuery] = useState("");
// Form state
const [formData, setFormData] = useState({
subDepartmentId: '',
activity: '',
rate: '',
effectiveDate: new Date().toISOString().split('T')[0],
subDepartmentId: "",
activity: "",
rate: "",
effectiveDate: new Date().toISOString().split("T")[0],
});
const [selectedDept, setSelectedDept] = useState('');
const [selectedDept, setSelectedDept] = useState("");
const { subDepartments } = useSubDepartments(selectedDept);
const { activities } = useActivities(formData.subDepartmentId);
const [formError, setFormError] = useState('');
const [formError, setFormError] = useState("");
const [formLoading, setFormLoading] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
// Compare filters
const [compareContractorId, setCompareContractorId] = useState('');
const [compareContractorId, setCompareContractorId] = useState("");
const isSupervisor = user?.role === 'Supervisor';
const canManageRates = user?.role === 'SuperAdmin' || user?.role === 'Supervisor';
const isSupervisor = user?.role === "Supervisor";
const canManageRates = user?.role === "SuperAdmin" ||
user?.role === "Supervisor";
// Fetch standard rates
const fetchStandardRates = async () => {
setLoading(true);
setError('');
setError("");
try {
const data = await api.getStandardRates();
setStandardRates(data);
} catch (err: any) {
setError(err.message || 'Failed to fetch standard rates');
setError(err.message || "Failed to fetch standard rates");
} finally {
setLoading(false);
}
@@ -57,10 +75,10 @@ export const StandardRatesPage: React.FC = () => {
// Fetch contractors
const fetchContractors = async () => {
try {
const data = await api.getUsers({ role: 'Contractor' });
const data = await api.getUsers({ role: "Contractor" });
setContractors(data);
} catch (err) {
console.error('Failed to fetch contractors:', err);
console.error("Failed to fetch contractors:", err);
}
};
@@ -72,10 +90,12 @@ export const StandardRatesPage: React.FC = () => {
}
setLoading(true);
try {
const data = await api.compareRates({ contractorId: parseInt(compareContractorId) });
const data = await api.compareRates({
contractorId: parseInt(compareContractorId),
});
setComparisons(data.comparisons);
} catch (err: any) {
setError(err.message || 'Failed to fetch comparison');
setError(err.message || "Failed to fetch comparison");
} finally {
setLoading(false);
}
@@ -93,41 +113,43 @@ export const StandardRatesPage: React.FC = () => {
}, [isSupervisor, user?.department_id]);
useEffect(() => {
if (activeTab === 'compare' && compareContractorId) {
if (activeTab === "compare" && compareContractorId) {
fetchComparison();
}
}, [activeTab, compareContractorId]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const handleInputChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { name, value } = e.target;
// Clear activity when sub-department changes
if (name === 'subDepartmentId') {
setFormData(prev => ({ ...prev, [name]: value, activity: '' }));
if (name === "subDepartmentId") {
setFormData((prev) => ({ ...prev, [name]: value, activity: "" }));
} else {
setFormData(prev => ({ ...prev, [name]: value }));
setFormData((prev) => ({ ...prev, [name]: value }));
}
setFormError('');
setFormError("");
};
const resetForm = () => {
setFormData({
subDepartmentId: '',
activity: '',
rate: '',
effectiveDate: new Date().toISOString().split('T')[0],
subDepartmentId: "",
activity: "",
rate: "",
effectiveDate: new Date().toISOString().split("T")[0],
});
setEditingId(null);
setFormError('');
setFormError("");
};
const handleSubmit = async () => {
if (!formData.rate || !formData.effectiveDate) {
setFormError('Rate and effective date are required');
setFormError("Rate and effective date are required");
return;
}
setFormLoading(true);
setFormError('');
setFormError("");
try {
if (editingId) {
@@ -138,7 +160,9 @@ export const StandardRatesPage: React.FC = () => {
});
} else {
await api.createStandardRate({
subDepartmentId: formData.subDepartmentId ? parseInt(formData.subDepartmentId) : undefined,
subDepartmentId: formData.subDepartmentId
? parseInt(formData.subDepartmentId)
: undefined,
activity: formData.activity || undefined,
rate: parseFloat(formData.rate),
effectiveDate: formData.effectiveDate,
@@ -146,10 +170,10 @@ export const StandardRatesPage: React.FC = () => {
}
resetForm();
setActiveTab('list');
setActiveTab("list");
fetchStandardRates();
} catch (err: any) {
setFormError(err.message || 'Failed to save rate');
setFormError(err.message || "Failed to save rate");
} finally {
setFormLoading(false);
}
@@ -157,25 +181,28 @@ export const StandardRatesPage: React.FC = () => {
const handleEdit = (rate: any) => {
setFormData({
subDepartmentId: rate.sub_department_id ? String(rate.sub_department_id) : '',
activity: rate.activity || '',
subDepartmentId: rate.sub_department_id
? String(rate.sub_department_id)
: "",
activity: rate.activity || "",
rate: String(rate.rate),
effectiveDate: rate.effective_date?.split('T')[0] || new Date().toISOString().split('T')[0],
effectiveDate: rate.effective_date?.split("T")[0] ||
new Date().toISOString().split("T")[0],
});
if (rate.department_id) {
setSelectedDept(String(rate.department_id));
}
setEditingId(rate.id);
setActiveTab('add');
setActiveTab("add");
};
const handleDelete = async (id: number) => {
if (!confirm('Are you sure you want to delete this standard rate?')) return;
if (!confirm("Are you sure you want to delete this standard rate?")) return;
try {
await api.deleteStandardRate(id);
fetchStandardRates();
} catch (err: any) {
alert(err.message || 'Failed to delete rate');
alert(err.message || "Failed to delete rate");
}
};
@@ -183,7 +210,7 @@ export const StandardRatesPage: React.FC = () => {
const filteredRates = useMemo(() => {
if (!searchQuery) return standardRates;
const query = searchQuery.toLowerCase();
return standardRates.filter(rate =>
return standardRates.filter((rate) =>
rate.sub_department_name?.toLowerCase().includes(query) ||
rate.department_name?.toLowerCase().includes(query) ||
rate.activity?.toLowerCase().includes(query) ||
@@ -197,33 +224,36 @@ export const StandardRatesPage: React.FC = () => {
<div className="border-b border-gray-200">
<div className="flex space-x-8 px-6">
<button
onClick={() => { setActiveTab('list'); resetForm(); }}
onClick={() => {
setActiveTab("list");
resetForm();
}}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'list'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "list"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
Standard Rates
</button>
{canManageRates && (
<button
onClick={() => setActiveTab('add')}
onClick={() => setActiveTab("add")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'add'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "add"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
{editingId ? 'Edit Rate' : 'Add Standard Rate'}
{editingId ? "Edit Rate" : "Add Standard Rate"}
</button>
)}
<button
onClick={() => setActiveTab('compare')}
onClick={() => setActiveTab("compare")}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === 'compare'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
activeTab === "compare"
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
<Scale size={16} className="inline mr-1" />
@@ -233,11 +263,14 @@ export const StandardRatesPage: React.FC = () => {
</div>
<CardContent>
{activeTab === 'list' && (
{activeTab === "list" && (
<div>
<div className="flex gap-4 mb-4">
<div className="relative min-w-[300px] flex-1">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by sub-department, activity..."
@@ -254,8 +287,10 @@ export const StandardRatesPage: React.FC = () => {
<div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
<p className="text-sm text-blue-700">
<strong>Standard Rates</strong> are default rates set by supervisors for sub-departments and activities.
These are used as benchmarks to compare against contractor-specific rates.
<strong>Standard Rates</strong>{" "}
are default rates set by supervisors for sub-departments and
activities. These are used as benchmarks to compare against
contractor-specific rates.
</p>
</div>
@@ -265,85 +300,104 @@ export const StandardRatesPage: React.FC = () => {
</div>
)}
{loading ? (
<div className="text-center py-8">Loading standard rates...</div>
) : filteredRates.length > 0 ? (
<Table>
<TableHeader>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
<TableHead>Created By</TableHead>
{canManageRates && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredRates.map((rate) => (
<TableRow key={rate.id}>
<TableCell>{rate.department_name || '-'}</TableCell>
<TableCell className="font-medium">{rate.sub_department_name || 'All'}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
rate.unit_of_measurement === 'Per Bag'
? 'bg-blue-100 text-blue-700'
: 'bg-gray-100 text-gray-700'
}`}>
{rate.activity || 'Standard'}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">{rate.rate}</span>
</TableCell>
<TableCell>{new Date(rate.effective_date).toLocaleDateString()}</TableCell>
<TableCell className="text-gray-500">{rate.created_by_name || '-'}</TableCell>
{canManageRates && (
<TableCell>
<div className="flex gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(rate)}
className="text-blue-600"
title="Edit"
>
<Edit size={14} />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(rate.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
{loading
? (
<div className="text-center py-8">
Loading standard rates...
</div>
)
: filteredRates.length > 0
? (
<Table>
<TableHeader>
<TableHead>Department</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Rate ()</TableHead>
<TableHead>Effective Date</TableHead>
<TableHead>Created By</TableHead>
{canManageRates && <TableHead>Actions</TableHead>}
</TableHeader>
<TableBody>
{filteredRates.map((rate) => (
<TableRow key={rate.id}>
<TableCell>{rate.department_name || "-"}</TableCell>
<TableCell className="font-medium">
{rate.sub_department_name || "All"}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="text-center py-8 text-gray-500">
No standard rates configured yet. Add one to get started!
</div>
)}
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
rate.unit_of_measurement === "Per Bag"
? "bg-blue-100 text-blue-700"
: "bg-gray-100 text-gray-700"
}`}
>
{rate.activity || "Standard"}
</span>
</TableCell>
<TableCell>
<span className="text-green-600 font-semibold">
{rate.rate}
</span>
</TableCell>
<TableCell>
{new Date(rate.effective_date).toLocaleDateString()}
</TableCell>
<TableCell className="text-gray-500">
{rate.created_by_name || "-"}
</TableCell>
{canManageRates && (
<TableCell>
<div className="flex gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleEdit(rate)}
className="text-blue-600"
title="Edit"
>
<Edit size={14} />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(rate.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)
: (
<div className="text-center py-8 text-gray-500">
No standard rates configured yet. Add one to get started!
</div>
)}
</div>
)}
{activeTab === 'add' && canManageRates && (
{activeTab === "add" && canManageRates && (
<div className="max-w-2xl space-y-6">
<h3 className="text-lg font-semibold text-gray-800">
{editingId ? 'Edit Standard Rate' : 'Add New Standard Rate'}
{editingId ? "Edit Standard Rate" : "Add New Standard Rate"}
</h3>
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-md">
<h4 className="font-medium text-yellow-800 mb-2">About Standard Rates</h4>
<h4 className="font-medium text-yellow-800 mb-2">
About Standard Rates
</h4>
<p className="text-sm text-yellow-700">
Standard rates serve as default benchmarks for sub-departments and activities.
Contractor rates can be compared against these to identify deviations.
Standard rates serve as default benchmarks for sub-departments
and activities. Contractor rates can be compared against these
to identify deviations.
</p>
</div>
@@ -354,23 +408,30 @@ export const StandardRatesPage: React.FC = () => {
)}
<div className="grid grid-cols-2 gap-6">
{isSupervisor ? (
<Input
label="Department"
value={departments.find(d => d.id === user?.department_id)?.name || 'Loading...'}
disabled
/>
) : (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: '', label: 'Select Department' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
]}
/>
)}
{isSupervisor
? (
<Input
label="Department"
value={departments.find((d) =>
d.id === user?.department_id
)?.name || "Loading..."}
disabled
/>
)
: (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: "", label: "Select Department" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
)}
<Select
label="Sub-Department"
name="subDepartmentId"
@@ -378,8 +439,11 @@ export const StandardRatesPage: React.FC = () => {
onChange={handleInputChange}
disabled={!!editingId}
options={[
{ value: '', label: 'All Sub-Departments' },
...subDepartments.map(s => ({ value: String(s.id), label: s.name }))
{ value: "", label: "All Sub-Departments" },
...subDepartments.map((s) => ({
value: String(s.id),
label: s.name,
})),
]}
/>
<Select
@@ -389,18 +453,29 @@ export const StandardRatesPage: React.FC = () => {
onChange={handleInputChange}
disabled={!formData.subDepartmentId}
options={[
{ value: '', label: formData.subDepartmentId ? 'Standard (Default)' : 'Select Sub-Department First' },
...activities.map(a => ({
value: a.name,
label: `${a.name} (${a.unit_of_measurement === 'Per Bag' ? 'per unit' : 'flat rate'})`
}))
{
value: "",
label: formData.subDepartmentId
? "Standard (Default)"
: "Select Sub-Department First",
},
...activities.map((a) => ({
value: a.name,
label: `${a.name} (${
a.unit_of_measurement === "Per Bag"
? "per unit"
: "flat rate"
})`,
})),
]}
/>
<Input
label={(() => {
const selectedActivity = activities.find(a => a.name === formData.activity);
return selectedActivity?.unit_of_measurement === 'Per Bag'
? "Rate per Unit (₹)"
const selectedActivity = activities.find((a) =>
a.name === formData.activity
);
return selectedActivity?.unit_of_measurement === "Per Bag"
? "Rate per Unit (₹)"
: "Standard Rate (₹)";
})()}
name="rate"
@@ -421,14 +496,20 @@ export const StandardRatesPage: React.FC = () => {
</div>
<div className="flex justify-end gap-4">
<Button variant="outline" onClick={() => { setActiveTab('list'); resetForm(); }}>
<Button
variant="outline"
onClick={() => {
setActiveTab("list");
resetForm();
}}
>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={formLoading}>
{formLoading ? 'Saving...' : (
{formLoading ? "Saving..." : (
<>
<DollarSign size={16} className="mr-2" />
{editingId ? 'Update Rate' : 'Add Standard Rate'}
{editingId ? "Update Rate" : "Add Standard Rate"}
</>
)}
</Button>
@@ -436,7 +517,7 @@ export const StandardRatesPage: React.FC = () => {
</div>
)}
{activeTab === 'compare' && (
{activeTab === "compare" && (
<div>
<div className="mb-6">
<h3 className="text-lg font-semibold text-gray-800 mb-4">
@@ -451,81 +532,109 @@ export const StandardRatesPage: React.FC = () => {
value={compareContractorId}
onChange={(e) => setCompareContractorId(e.target.value)}
options={[
{ value: '', label: 'Select Contractor' },
...contractors.map(c => ({ value: String(c.id), label: c.name }))
{ value: "", label: "Select Contractor" },
...contractors.map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
</div>
<Button onClick={fetchComparison} disabled={!compareContractorId}>
<Button
onClick={fetchComparison}
disabled={!compareContractorId}
>
Compare
</Button>
</div>
</div>
{loading ? (
<div className="text-center py-8">Loading comparison...</div>
) : comparisons.length > 0 ? (
<Table>
<TableHeader>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Contractor Rate ()</TableHead>
<TableHead>Standard Rate ()</TableHead>
<TableHead>Difference ()</TableHead>
<TableHead>Status</TableHead>
</TableHeader>
<TableBody>
{comparisons.map((comp, idx) => (
<TableRow key={idx}>
<TableCell className="font-medium">{comp.sub_department_name || 'All'}</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
comp.unit_of_measurement === 'Per Bag'
? 'bg-blue-100 text-blue-700'
: 'bg-gray-100 text-gray-700'
}`}>
{comp.activity || 'Standard'}
</span>
</TableCell>
<TableCell className="font-semibold">{comp.rate}</TableCell>
<TableCell className="text-gray-600">{comp.standard_rate}</TableCell>
<TableCell>
<span className={`font-semibold ${
comp.difference > 0 ? 'text-red-600' :
comp.difference < 0 ? 'text-green-600' :
'text-gray-600'
}`}>
{comp.difference > 0 ? '+' : ''}{comp.difference.toFixed(2)}
</span>
</TableCell>
<TableCell>
{comp.is_above_standard ? (
<span className="px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-700">
Above Standard ({comp.percentage_difference}%)
{loading
? <div className="text-center py-8">Loading comparison...</div>
: comparisons.length > 0
? (
<Table>
<TableHeader>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Contractor Rate ()</TableHead>
<TableHead>Standard Rate ()</TableHead>
<TableHead>Difference ()</TableHead>
<TableHead>Status</TableHead>
</TableHeader>
<TableBody>
{comparisons.map((comp, idx) => (
<TableRow key={idx}>
<TableCell className="font-medium">
{comp.sub_department_name || "All"}
</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
comp.unit_of_measurement === "Per Bag"
? "bg-blue-100 text-blue-700"
: "bg-gray-100 text-gray-700"
}`}
>
{comp.activity || "Standard"}
</span>
) : comp.is_below_standard ? (
<span className="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700">
Below Standard ({comp.percentage_difference}%)
</TableCell>
<TableCell className="font-semibold">
{comp.rate}
</TableCell>
<TableCell className="text-gray-600">
{comp.standard_rate}
</TableCell>
<TableCell>
<span
className={`font-semibold ${
comp.difference > 0
? "text-red-600"
: comp.difference < 0
? "text-green-600"
: "text-gray-600"
}`}
>
{comp.difference > 0 ? "+" : ""}{comp.difference
.toFixed(2)}
</span>
) : (
<span className="px-2 py-1 rounded text-xs font-medium bg-gray-100 text-gray-700">
At Standard
</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : compareContractorId ? (
<div className="text-center py-8 text-gray-500">
No rates found for this contractor to compare.
</div>
) : (
<div className="text-center py-8 text-gray-500">
Select a contractor to compare their rates against standard rates.
</div>
)}
</TableCell>
<TableCell>
{comp.is_above_standard
? (
<span className="px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-700">
Above Standard ({comp.percentage_difference}%)
</span>
)
: comp.is_below_standard
? (
<span className="px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-700">
Below Standard ({comp.percentage_difference}%)
</span>
)
: (
<span className="px-2 py-1 rounded text-xs font-medium bg-gray-100 text-gray-700">
At Standard
</span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)
: compareContractorId
? (
<div className="text-center py-8 text-gray-500">
No rates found for this contractor to compare.
</div>
)
: (
<div className="text-center py-8 text-gray-500">
Select a contractor to compare their rates against standard
rates.
</div>
)}
</div>
)}
</CardContent>

File diff suppressed because it is too large Load Diff

View File

@@ -1,48 +1,65 @@
import React, { useState, useEffect } from 'react';
import { Plus, RefreshCw, CheckCircle, Trash2, Search } from 'lucide-react';
import { Card, CardContent } from '../components/ui/Card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '../components/ui/Table';
import { Button } from '../components/ui/Button';
import { Input, Select, TextArea } from '../components/ui/Input';
import { useWorkAllocations } from '../hooks/useWorkAllocations';
import { useDepartments, useSubDepartments } from '../hooks/useDepartments';
import { useEmployees } from '../hooks/useEmployees';
import { useActivities } from '../hooks/useActivities';
import { useAuth } from '../contexts/AuthContext';
import { api } from '../services/api';
import React, { useEffect, useState } from "react";
import { CheckCircle, Plus, RefreshCw, Search, Trash2 } from "lucide-react";
import { Card, CardContent } from "../components/ui/Card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../components/ui/Table.tsx";
import { Button } from "../components/ui/Button.tsx";
import { Input, Select, TextArea } from "../components/ui/Input.tsx";
import { useWorkAllocations } from "../hooks/useWorkAllocations.ts";
import { useDepartments, useSubDepartments } from "../hooks/useDepartments.ts";
import { useEmployees } from "../hooks/useEmployees.ts";
import { useActivities } from "../hooks/useActivities.ts";
import { useAuth } from "../contexts/AuthContext.tsx";
import { api } from "../services/api.ts";
export const WorkAllocationPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'create' | 'view' | 'summary'>('view');
const [searchQuery, setSearchQuery] = useState('');
const { allocations, loading, error, refresh, createAllocation, updateAllocation, deleteAllocation } = useWorkAllocations();
const [activeTab, setActiveTab] = useState<"create" | "view" | "summary">(
"view",
);
const [searchQuery, setSearchQuery] = useState("");
const {
allocations,
loading,
error,
refresh,
createAllocation,
updateAllocation,
deleteAllocation,
} = useWorkAllocations();
const { departments } = useDepartments();
const { employees } = useEmployees();
const { user } = useAuth();
const [contractors, setContractors] = useState<any[]>([]);
// Check if user is supervisor (limited to their department)
const isSupervisor = user?.role === 'Supervisor';
const canCreateAllocation = user?.role === 'SuperAdmin' || user?.role === 'Supervisor';
const isSupervisor = user?.role === "Supervisor";
// Get supervisor's department name
const supervisorDeptName = departments.find(d => d.id === user?.department_id)?.name || '';
const supervisorDeptName =
departments.find((d) => d.id === user?.department_id)?.name || "";
// Form state
const [formData, setFormData] = useState({
employeeId: '',
contractorId: '',
subDepartmentId: '',
activity: '',
description: '',
assignedDate: new Date().toISOString().split('T')[0],
rateId: '',
departmentId: '',
units: '',
employeeId: "",
contractorId: "",
subDepartmentId: "",
activity: "",
description: "",
assignedDate: new Date().toISOString().split("T")[0],
rateId: "",
departmentId: "",
units: "",
});
const [selectedDept, setSelectedDept] = useState('');
const [selectedDept, setSelectedDept] = useState("");
const { subDepartments } = useSubDepartments(selectedDept);
const { activities } = useActivities(formData.subDepartmentId);
const [formError, setFormError] = useState('');
const [formError, setFormError] = useState("");
const [formLoading, setFormLoading] = useState(false);
const [contractorRates, setContractorRates] = useState<any[]>([]);
@@ -58,15 +75,17 @@ export const WorkAllocationPage: React.FC = () => {
}, [formData.contractorId]);
// Get selected rate details
const selectedRate = contractorRates.find(r => r.id === parseInt(formData.rateId));
const selectedRate = contractorRates.find((r) =>
r.id === parseInt(formData.rateId)
);
// Get selected activity details
const selectedActivity = activities.find(a => a.name === formData.activity);
const selectedActivity = activities.find((a) => a.name === formData.activity);
// Check if rate is per unit based on activity's unit_of_measurement
const isPerUnitRate = selectedActivity?.unit_of_measurement === 'Per Bag' ||
selectedRate?.unit_of_measurement === 'Per Bag';
const isPerUnitRate = selectedActivity?.unit_of_measurement === "Per Bag" ||
selectedRate?.unit_of_measurement === "Per Bag";
// Calculate total amount
const unitCount = parseFloat(formData.units) || 0;
const rateAmount = parseFloat(selectedRate?.rate) || 0;
@@ -77,57 +96,74 @@ export const WorkAllocationPage: React.FC = () => {
if (isSupervisor && user?.department_id) {
const deptId = String(user.department_id);
setSelectedDept(deptId);
setFormData(prev => ({ ...prev, departmentId: deptId }));
setFormData((prev) => ({ ...prev, departmentId: deptId }));
}
}, [isSupervisor, user?.department_id]);
// Load contractors
useEffect(() => {
api.getUsers({ role: 'Contractor' }).then(setContractors).catch(console.error);
api.getUsers({ role: "Contractor" }).then(setContractors).catch(
console.error,
);
}, []);
// Filter employees by selected contractor
const filteredEmployees = formData.contractorId
? employees.filter(e => e.contractor_id === parseInt(formData.contractorId))
: employees.filter(e => e.role === 'Employee');
const filteredEmployees = formData.contractorId
? employees.filter((e) =>
e.contractor_id === parseInt(formData.contractorId)
)
: employees.filter((e) => e.role === "Employee");
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
const handleInputChange = (
e: React.ChangeEvent<
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
>,
) => {
const { name, value } = e.target;
// Auto-select department when contractor is selected
if (name === 'contractorId' && value) {
const selectedContractor = contractors.find(c => String(c.id) === value);
if (name === "contractorId" && value) {
const selectedContractor = contractors.find((c) =>
String(c.id) === value
);
if (selectedContractor?.department_id) {
setSelectedDept(String(selectedContractor.department_id));
// Clear sub-department and activity when contractor changes
setFormData(prev => ({ ...prev, [name]: value, subDepartmentId: '', activity: '', rateId: '' }));
setFormData((prev) => ({
...prev,
[name]: value,
subDepartmentId: "",
activity: "",
rateId: "",
}));
} else {
setFormData(prev => ({ ...prev, [name]: value }));
setFormData((prev) => ({ ...prev, [name]: value }));
}
}
// Clear activity when sub-department changes
else if (name === 'subDepartmentId') {
setFormData(prev => ({ ...prev, [name]: value, activity: '' }));
} // Clear activity when sub-department changes
else if (name === "subDepartmentId") {
setFormData((prev) => ({ ...prev, [name]: value, activity: "" }));
} else {
setFormData(prev => ({ ...prev, [name]: value }));
setFormData((prev) => ({ ...prev, [name]: value }));
}
setFormError('');
setFormError("");
};
const handleCreateAllocation = async () => {
if (!formData.employeeId || !formData.contractorId) {
setFormError('Please select employee and contractor');
setFormError("Please select employee and contractor");
return;
}
setFormLoading(true);
setFormError('');
setFormError("");
try {
await createAllocation({
employeeId: parseInt(formData.employeeId),
contractorId: parseInt(formData.contractorId),
subDepartmentId: formData.subDepartmentId ? parseInt(formData.subDepartmentId) : null,
subDepartmentId: formData.subDepartmentId
? parseInt(formData.subDepartmentId)
: null,
activity: formData.activity || null,
description: formData.description,
assignedDate: formData.assignedDate,
@@ -138,19 +174,19 @@ export const WorkAllocationPage: React.FC = () => {
// Reset form
setFormData({
employeeId: '',
contractorId: '',
subDepartmentId: '',
activity: '',
description: '',
assignedDate: new Date().toISOString().split('T')[0],
rateId: '',
departmentId: isSupervisor ? String(user?.department_id) : '',
units: '',
employeeId: "",
contractorId: "",
subDepartmentId: "",
activity: "",
description: "",
assignedDate: new Date().toISOString().split("T")[0],
rateId: "",
departmentId: isSupervisor ? String(user?.department_id) : "",
units: "",
});
setActiveTab('view');
setActiveTab("view");
} catch (err: any) {
setFormError(err.message || 'Failed to create allocation');
setFormError(err.message || "Failed to create allocation");
} finally {
setFormLoading(false);
}
@@ -158,27 +194,31 @@ export const WorkAllocationPage: React.FC = () => {
const handleMarkComplete = async (id: number) => {
try {
await updateAllocation(id, 'Completed', new Date().toISOString().split('T')[0]);
await updateAllocation(
id,
"Completed",
new Date().toISOString().split("T")[0],
);
} catch (err: any) {
alert(err.message || 'Failed to update allocation');
alert(err.message || "Failed to update allocation");
}
};
const handleDelete = async (id: number) => {
if (!confirm('Are you sure you want to delete this allocation?')) return;
if (!confirm("Are you sure you want to delete this allocation?")) return;
try {
await deleteAllocation(id);
} catch (err: any) {
alert(err.message || 'Failed to delete allocation');
alert(err.message || "Failed to delete allocation");
}
};
// Calculate summary stats
const stats = {
total: allocations.length,
completed: allocations.filter(a => a.status === 'Completed').length,
inProgress: allocations.filter(a => a.status === 'InProgress').length,
pending: allocations.filter(a => a.status === 'Pending').length,
completed: allocations.filter((a) => a.status === "Completed").length,
inProgress: allocations.filter((a) => a.status === "InProgress").length,
pending: allocations.filter((a) => a.status === "Pending").length,
};
return (
@@ -186,29 +226,31 @@ export const WorkAllocationPage: React.FC = () => {
<Card>
<div className="border-b border-gray-200">
<div className="flex space-x-8 px-6">
{['create', 'view', 'summary'].map((tab) => (
{["create", "view", "summary"].map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab as any)}
className={`py-4 px-2 border-b-2 font-medium text-sm ${
activeTab === tab
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
? "border-blue-500 text-blue-600"
: "border-transparent text-gray-500 hover:text-gray-700"
}`}
>
{tab === 'create' && 'Create Allocation'}
{tab === 'view' && 'View Allocations'}
{tab === 'summary' && 'Work Summary'}
{tab === "create" && "Create Allocation"}
{tab === "view" && "View Allocations"}
{tab === "summary" && "Work Summary"}
</button>
))}
</div>
</div>
<CardContent>
{activeTab === 'create' && (
{activeTab === "create" && (
<div className="max-w-3xl space-y-6">
<h3 className="text-lg font-semibold text-gray-800">Create New Work Allocation</h3>
<h3 className="text-lg font-semibold text-gray-800">
Create New Work Allocation
</h3>
{formError && (
<div className="p-3 bg-red-100 text-red-700 rounded-md">
{formError}
@@ -223,8 +265,11 @@ export const WorkAllocationPage: React.FC = () => {
onChange={handleInputChange}
required
options={[
{ value: '', label: 'Select Contractor' },
...contractors.map(c => ({ value: String(c.id), label: c.name }))
{ value: "", label: "Select Contractor" },
...contractors.map((c) => ({
value: String(c.id),
label: c.name,
})),
]}
/>
<Select
@@ -234,35 +279,46 @@ export const WorkAllocationPage: React.FC = () => {
onChange={handleInputChange}
required
options={[
{ value: '', label: 'Select Employee' },
...filteredEmployees.map(e => ({ value: String(e.id), label: e.name }))
{ value: "", label: "Select Employee" },
...filteredEmployees.map((e) => ({
value: String(e.id),
label: e.name,
})),
]}
/>
{isSupervisor ? (
<Input
label="Department"
value={supervisorDeptName || 'Loading...'}
disabled
/>
) : (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: '', label: 'Select Department' },
...departments.map(d => ({ value: String(d.id), label: d.name }))
]}
/>
)}
{isSupervisor
? (
<Input
label="Department"
value={supervisorDeptName || "Loading..."}
disabled
/>
)
: (
<Select
label="Department"
value={selectedDept}
onChange={(e) => setSelectedDept(e.target.value)}
options={[
{ value: "", label: "Select Department" },
...departments.map((d) => ({
value: String(d.id),
label: d.name,
})),
]}
/>
)}
<Select
label="Sub-Department"
name="subDepartmentId"
value={formData.subDepartmentId}
onChange={handleInputChange}
options={[
{ value: '', label: 'Select Sub-Department' },
...subDepartments.map(s => ({ value: String(s.id), label: s.name }))
{ value: "", label: "Select Sub-Department" },
...subDepartments.map((s) => ({
value: String(s.id),
label: s.name,
})),
]}
/>
<Select
@@ -272,11 +328,20 @@ export const WorkAllocationPage: React.FC = () => {
onChange={handleInputChange}
disabled={!formData.subDepartmentId}
options={[
{ value: '', label: formData.subDepartmentId ? 'Select Activity' : 'Select Sub-Department First' },
...activities.map(a => ({
value: a.name,
label: `${a.name} (${a.unit_of_measurement === 'Per Bag' ? 'per unit' : 'flat rate'})`
}))
{
value: "",
label: formData.subDepartmentId
? "Select Activity"
: "Select Sub-Department First",
},
...activities.map((a) => ({
value: a.name,
label: `${a.name} (${
a.unit_of_measurement === "Per Bag"
? "per unit"
: "flat rate"
})`,
})),
]}
/>
<Input
@@ -294,11 +359,20 @@ export const WorkAllocationPage: React.FC = () => {
onChange={handleInputChange}
disabled={!formData.contractorId}
options={[
{ value: '', label: formData.contractorId ? 'Select Rate' : 'Select Contractor First' },
...contractorRates.map(r => ({
value: String(r.id),
label: `${r.rate} - ${r.activity || 'Standard'} ${r.sub_department_name ? `(${r.sub_department_name})` : ''}`
}))
{
value: "",
label: formData.contractorId
? "Select Rate"
: "Select Contractor First",
},
...contractorRates.map((r) => ({
value: String(r.id),
label: `${r.rate} - ${r.activity || "Standard"} ${
r.sub_department_name
? `(${r.sub_department_name})`
: ""
}`,
})),
]}
/>
{isPerUnitRate && (
@@ -322,37 +396,51 @@ export const WorkAllocationPage: React.FC = () => {
rows={3}
/>
</div>
{/* Calculation Box */}
{selectedRate && (
<div className="col-span-2 p-4 bg-blue-50 border border-blue-200 rounded-lg">
<h4 className="font-semibold text-blue-800 mb-3">Rate Calculation</h4>
<h4 className="font-semibold text-blue-800 mb-3">
Rate Calculation
</h4>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-gray-600">Rate Type:</span>
<span className="ml-2 font-medium">{isPerUnitRate ? 'Per Unit' : 'Flat Rate'}</span>
<span className="ml-2 font-medium">
{isPerUnitRate ? "Per Unit" : "Flat Rate"}
</span>
</div>
<div>
<span className="text-gray-600">Rate:</span>
<span className="ml-2 font-medium">{rateAmount.toFixed(2)}</span>
<span className="ml-2 font-medium">
{rateAmount.toFixed(2)}
</span>
</div>
{isPerUnitRate && (
<>
<div>
<span className="text-gray-600">Units:</span>
<span className="ml-2 font-medium">{unitCount || 0}</span>
<span className="ml-2 font-medium">
{unitCount || 0}
</span>
</div>
<div>
<span className="text-gray-600">Calculation:</span>
<span className="ml-2 font-medium">{unitCount} × {rateAmount.toFixed(2)}</span>
<span className="ml-2 font-medium">
{unitCount} × {rateAmount.toFixed(2)}
</span>
</div>
</>
)}
</div>
<div className="mt-4 pt-3 border-t border-blue-300">
<div className="flex justify-between items-center">
<span className="text-lg font-semibold text-blue-800">Total Amount:</span>
<span className="text-2xl font-bold text-green-600">{totalAmount.toFixed(2)}</span>
<span className="text-lg font-semibold text-blue-800">
Total Amount:
</span>
<span className="text-2xl font-bold text-green-600">
{totalAmount.toFixed(2)}
</span>
</div>
</div>
</div>
@@ -360,11 +448,11 @@ export const WorkAllocationPage: React.FC = () => {
</div>
<div className="flex justify-end gap-4 mt-6">
<Button variant="outline" onClick={() => setActiveTab('view')}>
<Button variant="outline" onClick={() => setActiveTab("view")}>
Cancel
</Button>
<Button onClick={handleCreateAllocation} disabled={formLoading}>
{formLoading ? 'Creating...' : (
{formLoading ? "Creating..." : (
<>
<Plus size={16} className="mr-2" />
Create Allocation
@@ -375,11 +463,14 @@ export const WorkAllocationPage: React.FC = () => {
</div>
)}
{activeTab === 'view' && (
{activeTab === "view" && (
<div>
<div className="flex gap-4 mb-4">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
size={18}
/>
<input
type="text"
placeholder="Search by employee, contractor, sub-department..."
@@ -399,9 +490,9 @@ export const WorkAllocationPage: React.FC = () => {
Error: {error}
</div>
)}
{(() => {
const filteredAllocations = allocations.filter(a => {
const filteredAllocations = allocations.filter((a) => {
if (!searchQuery) return true;
const query = searchQuery.toLowerCase();
return (
@@ -412,122 +503,187 @@ export const WorkAllocationPage: React.FC = () => {
a.status?.toLowerCase().includes(query)
);
});
return loading ? (
<div className="text-center py-8">Loading work allocations...</div>
) : filteredAllocations.length > 0 ? (
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>Employee</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Date</TableHead>
<TableHead>Rate Details</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableHeader>
<TableBody>
{filteredAllocations.map((allocation) => {
const isPerUnit = allocation.activity === 'Loading' || allocation.activity === 'Unloading';
const units = parseFloat(allocation.units) || 0;
const rate = parseFloat(allocation.rate) || 0;
const total = parseFloat(allocation.total_amount) || (isPerUnit ? units * rate : rate);
return (
<TableRow key={allocation.id}>
<TableCell>{allocation.id}</TableCell>
<TableCell>{allocation.employee_name || '-'}</TableCell>
<TableCell>{allocation.contractor_name || '-'}</TableCell>
<TableCell>{allocation.sub_department_name || '-'}</TableCell>
<TableCell>
{allocation.activity ? (
<span className={`px-2 py-1 rounded text-xs font-medium ${
allocation.activity === 'Loading' || allocation.activity === 'Unloading'
? 'bg-purple-100 text-purple-700'
: 'bg-gray-100 text-gray-700'
}`}>
{allocation.activity}
</span>
) : '-'}
</TableCell>
<TableCell>{new Date(allocation.assigned_date).toLocaleDateString()}</TableCell>
<TableCell>
{rate > 0 ? (
<div className="text-sm">
{isPerUnit && units > 0 ? (
<div>
<div className="text-gray-500">{units} × {rate.toFixed(2)}</div>
<div className="font-semibold text-green-600">= {total.toFixed(2)}</div>
</div>
) : (
<div className="font-semibold text-green-600">{rate.toFixed(2)}</div>
)}
</div>
) : '-'}
</TableCell>
<TableCell>
<span className={`px-2 py-1 rounded text-xs font-medium ${
allocation.status === 'Completed' ? 'bg-green-100 text-green-700' :
allocation.status === 'InProgress' ? 'bg-blue-100 text-blue-700' :
allocation.status === 'Cancelled' ? 'bg-red-100 text-red-700' :
'bg-yellow-100 text-yellow-700'
}`}>
{allocation.status}
</span>
</TableCell>
<TableCell>
<div className="flex gap-2">
{allocation.status !== 'Completed' && (
<Button
variant="ghost"
size="sm"
onClick={() => handleMarkComplete(allocation.id)}
className="text-green-600"
title="Mark Complete"
return loading
? (
<div className="text-center py-8">
Loading work allocations...
</div>
)
: filteredAllocations.length > 0
? (
<Table>
<TableHeader>
<TableHead>ID</TableHead>
<TableHead>Employee</TableHead>
<TableHead>Contractor</TableHead>
<TableHead>Sub-Department</TableHead>
<TableHead>Activity</TableHead>
<TableHead>Date</TableHead>
<TableHead>Rate Details</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableHeader>
<TableBody>
{filteredAllocations.map((allocation) => {
const isPerUnit = allocation.activity === "Loading" ||
allocation.activity === "Unloading";
const units = parseFloat(allocation.units) || 0;
const rate = parseFloat(allocation.rate) || 0;
const total = parseFloat(allocation.total_amount) ||
(isPerUnit ? units * rate : rate);
return (
<TableRow key={allocation.id}>
<TableCell>{allocation.id}</TableCell>
<TableCell>
{allocation.employee_name || "-"}
</TableCell>
<TableCell>
{allocation.contractor_name || "-"}
</TableCell>
<TableCell>
{allocation.sub_department_name || "-"}
</TableCell>
<TableCell>
{allocation.activity
? (
<span
className={`px-2 py-1 rounded text-xs font-medium ${
allocation.activity === "Loading" ||
allocation.activity === "Unloading"
? "bg-purple-100 text-purple-700"
: "bg-gray-100 text-gray-700"
}`}
>
{allocation.activity}
</span>
)
: "-"}
</TableCell>
<TableCell>
{new Date(allocation.assigned_date)
.toLocaleDateString()}
</TableCell>
<TableCell>
{rate > 0
? (
<div className="text-sm">
{isPerUnit && units > 0
? (
<div>
<div className="text-gray-500">
{units} × {rate.toFixed(2)}
</div>
<div className="font-semibold text-green-600">
= {total.toFixed(2)}
</div>
</div>
)
: (
<div className="font-semibold text-green-600">
{rate.toFixed(2)}
</div>
)}
</div>
)
: "-"}
</TableCell>
<TableCell>
<span
className={`px-2 py-1 rounded text-xs font-medium ${
allocation.status === "Completed"
? "bg-green-100 text-green-700"
: allocation.status === "InProgress"
? "bg-blue-100 text-blue-700"
: allocation.status === "Cancelled"
? "bg-red-100 text-red-700"
: "bg-yellow-100 text-yellow-700"
}`}
>
<CheckCircle size={14} />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(allocation.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
) : (
<div className="text-center py-8 text-gray-500">
{searchQuery ? 'No matching allocations found.' : 'No work allocations found. Create one to get started!'}
</div>
)
{allocation.status}
</span>
</TableCell>
<TableCell>
<div className="flex gap-2">
{allocation.status !== "Completed" && (
<Button
variant="ghost"
size="sm"
onClick={() =>
handleMarkComplete(allocation.id)}
className="text-green-600"
title="Mark Complete"
>
<CheckCircle size={14} />
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(allocation.id)}
className="text-red-600"
title="Delete"
>
<Trash2 size={14} />
</Button>
</div>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)
: (
<div className="text-center py-8 text-gray-500">
{searchQuery
? "No matching allocations found."
: "No work allocations found. Create one to get started!"}
</div>
);
})()}
</div>
)}
{activeTab === 'summary' && (
{activeTab === "summary" && (
<div>
<h3 className="text-lg font-semibold text-gray-800 mb-6">Work Summary & Statistics</h3>
<h3 className="text-lg font-semibold text-gray-800 mb-6">
Work Summary & Statistics
</h3>
<div className="grid grid-cols-4 gap-6">
{[
{ label: 'TOTAL ALLOCATIONS', value: stats.total, color: 'bg-gray-100' },
{ label: 'COMPLETED', value: stats.completed, color: 'bg-green-100' },
{ label: 'IN PROGRESS', value: stats.inProgress, color: 'bg-blue-100' },
{ label: 'PENDING', value: stats.pending, color: 'bg-yellow-100' },
{
label: "TOTAL ALLOCATIONS",
value: stats.total,
color: "bg-gray-100",
},
{
label: "COMPLETED",
value: stats.completed,
color: "bg-green-100",
},
{
label: "IN PROGRESS",
value: stats.inProgress,
color: "bg-blue-100",
},
{
label: "PENDING",
value: stats.pending,
color: "bg-yellow-100",
},
].map((stat) => (
<div key={stat.label} className={`${stat.color} border border-gray-200 rounded-lg p-6`}>
<div className="text-xs text-gray-500 mb-2">{stat.label}</div>
<div className="text-3xl font-bold text-gray-800">{stat.value}</div>
<div
key={stat.label}
className={`${stat.color} border border-gray-200 rounded-lg p-6`}
>
<div className="text-xs text-gray-500 mb-2">
{stat.label}
</div>
<div className="text-3xl font-bold text-gray-800">
{stat.value}
</div>
</div>
))}
</div>

View File

@@ -1,4 +1,5 @@
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ||
"http://localhost:3000/api";
class ApiService {
private baseURL: string;
@@ -8,18 +9,21 @@ class ApiService {
}
private getToken(): string | null {
return localStorage.getItem('token');
return localStorage.getItem("token");
}
private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
private async request<T>(
endpoint: string,
options: RequestInit = {},
): Promise<T> {
const token = this.getToken();
const headers: HeadersInit = {
'Content-Type': 'application/json',
...options.headers,
const headers: Record<string, string> = {
"Content-Type": "application/json",
...(options.headers as Record<string, string>),
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
headers["Authorization"] = `Bearer ${token}`;
}
const response = await fetch(`${this.baseURL}${endpoint}`, {
@@ -28,183 +32,216 @@ class ApiService {
});
if (response.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/';
throw new Error('Unauthorized');
localStorage.removeItem("token");
localStorage.removeItem("user");
globalThis.location.href = "/";
throw new Error("Unauthorized");
}
if (!response.ok) {
const error = await response.json().catch(() => ({ error: 'Request failed' }));
throw new Error(error.error || 'Request failed');
const error = await response.json().catch(() => ({
error: "Request failed",
}));
throw new Error(error.error || "Request failed");
}
return response.json();
}
// Auth
async login(username: string, password: string) {
return this.request<{ token: string; user: any }>('/auth/login', {
method: 'POST',
login(username: string, password: string) {
return this.request<{ token: string; user: any }>("/auth/login", {
method: "POST",
body: JSON.stringify({ username, password }),
});
}
async getMe() {
return this.request<any>('/auth/me');
getMe() {
return this.request<any>("/auth/me");
}
async changePassword(currentPassword: string, newPassword: string) {
return this.request<{ message: string }>('/auth/change-password', {
method: 'POST',
changePassword(currentPassword: string, newPassword: string) {
return this.request<{ message: string }>("/auth/change-password", {
method: "POST",
body: JSON.stringify({ currentPassword, newPassword }),
});
}
// Users
async getUsers(params?: { role?: string; departmentId?: number }) {
getUsers(params?: { role?: string; departmentId?: number }) {
const query = new URLSearchParams(params as any).toString();
return this.request<any[]>(`/users${query ? `?${query}` : ''}`);
return this.request<any[]>(`/users${query ? `?${query}` : ""}`);
}
async getUser(id: number) {
getUser(id: number) {
return this.request<any>(`/users/${id}`);
}
async createUser(data: any) {
return this.request<any>('/users', {
method: 'POST',
createUser(data: any) {
return this.request<any>("/users", {
method: "POST",
body: JSON.stringify(data),
});
}
async updateUser(id: number, data: any) {
updateUser(id: number, data: any) {
return this.request<any>(`/users/${id}`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify(data),
});
}
async deleteUser(id: number) {
deleteUser(id: number) {
return this.request<{ message: string }>(`/users/${id}`, {
method: 'DELETE',
method: "DELETE",
});
}
// Departments
async getDepartments() {
return this.request<any[]>('/departments');
getDepartments() {
return this.request<any[]>("/departments");
}
async getDepartment(id: number) {
getDepartment(id: number) {
return this.request<any>(`/departments/${id}`);
}
async getSubDepartments(departmentId: number) {
getSubDepartments(departmentId: number) {
return this.request<any[]>(`/departments/${departmentId}/sub-departments`);
}
async createDepartment(name: string) {
return this.request<any>('/departments', {
method: 'POST',
getAllSubDepartments() {
return this.request<any[]>("/departments/sub-departments/all");
}
createDepartment(name: string) {
return this.request<any>("/departments", {
method: "POST",
body: JSON.stringify({ name }),
});
}
// Sub-Departments
async createSubDepartment(data: { department_id: number; name: string }) {
return this.request<any>('/departments/sub-departments', {
method: 'POST',
createSubDepartment(data: { department_id: number; name: string }) {
return this.request<any>("/departments/sub-departments", {
method: "POST",
body: JSON.stringify(data),
});
}
async deleteSubDepartment(id: number) {
return this.request<{ message: string }>(`/departments/sub-departments/${id}`, {
method: 'DELETE',
});
deleteSubDepartment(id: number) {
return this.request<{ message: string }>(
`/departments/sub-departments/${id}`,
{
method: "DELETE",
},
);
}
// Work Allocations
async getWorkAllocations(params?: { employeeId?: number; status?: string; departmentId?: number }) {
getWorkAllocations(
params?: { employeeId?: number; status?: string; departmentId?: number },
) {
const query = new URLSearchParams(params as any).toString();
return this.request<any[]>(`/work-allocations${query ? `?${query}` : ''}`);
return this.request<any[]>(`/work-allocations${query ? `?${query}` : ""}`);
}
async getWorkAllocation(id: number) {
getWorkAllocation(id: number) {
return this.request<any>(`/work-allocations/${id}`);
}
async createWorkAllocation(data: any) {
return this.request<any>('/work-allocations', {
method: 'POST',
createWorkAllocation(data: any) {
return this.request<any>("/work-allocations", {
method: "POST",
body: JSON.stringify(data),
});
}
async updateWorkAllocationStatus(id: number, status: string, completionDate?: string) {
updateWorkAllocationStatus(
id: number,
status: string,
completionDate?: string,
) {
return this.request<any>(`/work-allocations/${id}/status`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify({ status, completionDate }),
});
}
async deleteWorkAllocation(id: number) {
deleteWorkAllocation(id: number) {
return this.request<{ message: string }>(`/work-allocations/${id}`, {
method: 'DELETE',
method: "DELETE",
});
}
// Attendance
async getAttendance(params?: { employeeId?: number; startDate?: string; endDate?: string; status?: string }) {
getAttendance(
params?: {
employeeId?: number;
startDate?: string;
endDate?: string;
status?: string;
},
) {
const query = new URLSearchParams(params as any).toString();
return this.request<any[]>(`/attendance${query ? `?${query}` : ''}`);
return this.request<any[]>(`/attendance${query ? `?${query}` : ""}`);
}
async checkIn(employeeId: number, workDate: string) {
return this.request<any>('/attendance/check-in', {
method: 'POST',
checkIn(employeeId: number, workDate: string) {
return this.request<any>("/attendance/check-in", {
method: "POST",
body: JSON.stringify({ employeeId, workDate }),
});
}
async checkOut(employeeId: number, workDate: string) {
return this.request<any>('/attendance/check-out', {
method: 'POST',
checkOut(employeeId: number, workDate: string) {
return this.request<any>("/attendance/check-out", {
method: "POST",
body: JSON.stringify({ employeeId, workDate }),
});
}
async getAttendanceSummary(params?: { startDate?: string; endDate?: string; departmentId?: number }) {
getAttendanceSummary(
params?: { startDate?: string; endDate?: string; departmentId?: number },
) {
const query = new URLSearchParams(params as any).toString();
return this.request<any[]>(`/attendance/summary/stats${query ? `?${query}` : ''}`);
return this.request<any[]>(
`/attendance/summary/stats${query ? `?${query}` : ""}`,
);
}
async updateAttendanceStatus(id: number, status: string, remark?: string) {
updateAttendanceStatus(id: number, status: string, remark?: string) {
return this.request<any>(`/attendance/${id}/status`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify({ status, remark }),
});
}
async markAbsent(employeeId: number, workDate: string, remark?: string) {
return this.request<any>('/attendance/mark-absent', {
method: 'POST',
markAbsent(employeeId: number, workDate: string, remark?: string) {
return this.request<any>("/attendance/mark-absent", {
method: "POST",
body: JSON.stringify({ employeeId, workDate, remark }),
});
}
// Employee Swaps
async getEmployeeSwaps(params?: { status?: string; employeeId?: number; startDate?: string; endDate?: string }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
return this.request<any[]>(`/employee-swaps${query ? `?${query}` : ''}`);
getEmployeeSwaps(
params?: {
status?: string;
employeeId?: number;
startDate?: string;
endDate?: string;
},
) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<any[]>(`/employee-swaps${query ? `?${query}` : ""}`);
}
async getEmployeeSwap(id: number) {
getEmployeeSwap(id: number) {
return this.request<any>(`/employee-swaps/${id}`);
}
async createEmployeeSwap(data: {
createEmployeeSwap(data: {
employeeId: number;
targetDepartmentId: number;
targetContractorId?: number;
@@ -213,160 +250,195 @@ class ApiService {
workCompletionPercentage?: number;
swapDate: string;
}) {
return this.request<any>('/employee-swaps', {
method: 'POST',
return this.request<any>("/employee-swaps", {
method: "POST",
body: JSON.stringify(data),
});
}
async completeEmployeeSwap(id: number) {
completeEmployeeSwap(id: number) {
return this.request<any>(`/employee-swaps/${id}/complete`, {
method: 'PUT',
method: "PUT",
});
}
async cancelEmployeeSwap(id: number) {
cancelEmployeeSwap(id: number) {
return this.request<any>(`/employee-swaps/${id}/cancel`, {
method: 'PUT',
method: "PUT",
});
}
// Contractor Rates
async getContractorRates(params?: { contractorId?: number; subDepartmentId?: number }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
return this.request<any[]>(`/contractor-rates${query ? `?${query}` : ''}`);
getContractorRates(
params?: { contractorId?: number; subDepartmentId?: number },
) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<any[]>(`/contractor-rates${query ? `?${query}` : ""}`);
}
async getCurrentRate(contractorId: number, subDepartmentId?: number) {
const query = subDepartmentId ? `?subDepartmentId=${subDepartmentId}` : '';
return this.request<any>(`/contractor-rates/contractor/${contractorId}/current${query}`);
getCurrentRate(contractorId: number, subDepartmentId?: number) {
const query = subDepartmentId ? `?subDepartmentId=${subDepartmentId}` : "";
return this.request<any>(
`/contractor-rates/contractor/${contractorId}/current${query}`,
);
}
async setContractorRate(data: {
contractorId: number;
subDepartmentId?: number;
activity?: string;
rate: number;
effectiveDate: string
setContractorRate(data: {
contractorId: number;
subDepartmentId?: number;
activity?: string;
rate: number;
effectiveDate: string;
}) {
return this.request<any>('/contractor-rates', {
method: 'POST',
return this.request<any>("/contractor-rates", {
method: "POST",
body: JSON.stringify(data),
});
}
async updateContractorRate(id: number, data: { rate?: number; activity?: string; effectiveDate?: string }) {
updateContractorRate(
id: number,
data: { rate?: number; activity?: string; effectiveDate?: string },
) {
return this.request<any>(`/contractor-rates/${id}`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify(data),
});
}
async deleteContractorRate(id: number) {
deleteContractorRate(id: number) {
return this.request<{ message: string }>(`/contractor-rates/${id}`, {
method: 'DELETE',
method: "DELETE",
});
}
// Reports
async getCompletedAllocationsReport(params?: {
startDate?: string;
endDate?: string;
getCompletedAllocationsReport(params?: {
startDate?: string;
endDate?: string;
departmentId?: number;
contractorId?: number;
employeeId?: number;
}) {
const query = params ? new URLSearchParams(params as any).toString() : '';
return this.request<{
allocations: any[];
summary: { totalAllocations: number; totalAmount: string; totalUnits: string }
}>(`/reports/completed-allocations${query ? `?${query}` : ''}`);
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<{
allocations: any[];
summary: {
totalAllocations: number;
totalAmount: string;
totalUnits: string;
};
}>(`/reports/completed-allocations${query ? `?${query}` : ""}`);
}
async getReportSummary(params?: { startDate?: string; endDate?: string }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
getReportSummary(params?: { startDate?: string; endDate?: string }) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<{
byContractor: any[];
bySubDepartment: any[];
byActivity: any[];
}>(`/reports/summary${query ? `?${query}` : ''}`);
}>(`/reports/summary${query ? `?${query}` : ""}`);
}
// Standard Rates
async getStandardRates(params?: { departmentId?: number; subDepartmentId?: number; activity?: string }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
return this.request<any[]>(`/standard-rates${query ? `?${query}` : ''}`);
getStandardRates(
params?: {
departmentId?: number;
subDepartmentId?: number;
activity?: string;
},
) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<any[]>(`/standard-rates${query ? `?${query}` : ""}`);
}
async getAllRates(params?: { departmentId?: number; startDate?: string; endDate?: string }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
getAllRates(
params?: { departmentId?: number; startDate?: string; endDate?: string },
) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<{
allRates: any[];
summary: { totalContractorRates: number; totalStandardRates: number; totalRates: number };
}>(`/standard-rates/all-rates${query ? `?${query}` : ''}`);
summary: {
totalContractorRates: number;
totalStandardRates: number;
totalRates: number;
};
}>(`/standard-rates/all-rates${query ? `?${query}` : ""}`);
}
async compareRates(params?: { contractorId?: number; subDepartmentId?: number }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
compareRates(params?: { contractorId?: number; subDepartmentId?: number }) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<{
standardRates: any[];
contractorRates: any[];
comparisons: any[];
}>(`/standard-rates/compare${query ? `?${query}` : ''}`);
}>(`/standard-rates/compare${query ? `?${query}` : ""}`);
}
async createStandardRate(data: {
subDepartmentId?: number;
activity?: string;
rate: number;
effectiveDate: string
createStandardRate(data: {
subDepartmentId?: number;
activity?: string;
rate: number;
effectiveDate: string;
}) {
return this.request<any>('/standard-rates', {
method: 'POST',
return this.request<any>("/standard-rates", {
method: "POST",
body: JSON.stringify(data),
});
}
async updateStandardRate(id: number, data: { rate?: number; activity?: string; effectiveDate?: string }) {
updateStandardRate(
id: number,
data: { rate?: number; activity?: string; effectiveDate?: string },
) {
return this.request<any>(`/standard-rates/${id}`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify(data),
});
}
async deleteStandardRate(id: number) {
deleteStandardRate(id: number) {
return this.request<{ message: string }>(`/standard-rates/${id}`, {
method: 'DELETE',
method: "DELETE",
});
}
// Activities
async getActivities(params?: { departmentId?: number; subDepartmentId?: number }) {
const query = params ? new URLSearchParams(params as any).toString() : '';
return this.request<any[]>(`/activities${query ? `?${query}` : ''}`);
getActivities(params?: { departmentId?: number; subDepartmentId?: number }) {
const query = params ? new URLSearchParams(params as any).toString() : "";
return this.request<any[]>(`/activities${query ? `?${query}` : ""}`);
}
async getActivity(id: number) {
getActivity(id: number) {
return this.request<any>(`/activities/${id}`);
}
async createActivity(data: { sub_department_id: number; name: string; unit_of_measurement?: string }) {
return this.request<any>('/activities', {
method: 'POST',
createActivity(
data: {
sub_department_id: number;
name: string;
unit_of_measurement?: string;
},
) {
return this.request<any>("/activities", {
method: "POST",
body: JSON.stringify(data),
});
}
async updateActivity(id: number, data: { name?: string; unit_of_measurement?: string }) {
updateActivity(
id: number,
data: { name?: string; unit_of_measurement?: string },
) {
return this.request<any>(`/activities/${id}`, {
method: 'PUT',
method: "PUT",
body: JSON.stringify(data),
});
}
async deleteActivity(id: number) {
deleteActivity(id: number) {
return this.request<{ message: string }>(`/activities/${id}`, {
method: 'DELETE',
method: "DELETE",
});
}
}

View File

@@ -4,7 +4,7 @@ export interface Employee {
dept: string;
sub: string;
activity: string;
status: 'Present' | 'Absent';
status: "Present" | "Absent";
in: string;
out: string;
remark: string;
@@ -56,3 +56,32 @@ export interface ChartData {
color?: string;
fill?: string;
}
export type AttendanceStatus = "CheckedIn" | "CheckedOut" | "Absent" | "HalfDay" | "Late";
export type SwapStatus = "Active" | "Completed" | "Cancelled";
export type SwapReason = "LeftWork" | "Sick" | "FinishedEarly" | "Other";
export interface EmployeeSwap {
id: number;
employee_id: number;
employee_name?: string;
original_department_id: number;
original_department_name?: string;
original_contractor_id?: number;
original_contractor_name?: string;
target_department_id: number;
target_department_name?: string;
target_contractor_id?: number;
target_contractor_name?: string;
swap_reason: SwapReason;
reason_details?: string;
work_completion_percentage: number;
swap_date: string;
swapped_by_id: number;
swapped_by_name?: string;
status: SwapStatus;
created_at: string;
updated_at: string;
}

View File

@@ -3,7 +3,7 @@ export interface User {
username: string;
name: string;
email: string;
role: 'SuperAdmin' | 'Supervisor' | 'Contractor' | 'Employee';
role: "SuperAdmin" | "Supervisor" | "Contractor" | "Employee";
department_id?: number;
contractor_id?: number;
is_active: boolean;
@@ -13,13 +13,11 @@ export interface User {
sub_department_id?: number;
sub_department_name?: string;
primary_activity?: string;
// Common fields for Employee and Contractor
phone_number?: string;
aadhar_number?: string;
bank_account_number?: string;
bank_name?: string;
bank_ifsc?: string;
// Contractor-specific fields
contractor_agreement_number?: string;
pf_number?: string;
esic_number?: string;
@@ -45,7 +43,7 @@ export interface Activity {
id: number;
sub_department_id: number;
name: string;
unit_of_measurement: 'Per Bag' | 'Fixed Rate-Per Person';
unit_of_measurement: "Per Bag" | "Fixed Rate-Per Person";
created_at: string;
sub_department_name?: string;
department_id?: number;
@@ -60,7 +58,7 @@ export interface WorkAllocation {
sub_department_id?: number;
description?: string;
assigned_date: string;
status: 'Pending' | 'InProgress' | 'Completed' | 'Cancelled';
status: "Pending" | "InProgress" | "Completed" | "Cancelled";
completion_date?: string;
rate?: number;
created_at: string;
@@ -73,7 +71,12 @@ export interface WorkAllocation {
department_name?: string;
}
export type AttendanceStatus = 'CheckedIn' | 'CheckedOut' | 'Absent' | 'HalfDay' | 'Late';
export type AttendanceStatus =
| "CheckedIn"
| "CheckedOut"
| "Absent"
| "HalfDay"
| "Late";
export interface Attendance {
id: number;
@@ -93,8 +96,8 @@ export interface Attendance {
contractor_name?: string;
}
export type SwapReason = 'LeftWork' | 'Sick' | 'FinishedEarly' | 'Other';
export type SwapStatus = 'Active' | 'Completed' | 'Cancelled';
export type SwapReason = "LeftWork" | "Sick" | "FinishedEarly" | "Other";
export type SwapStatus = "Active" | "Completed" | "Cancelled";
export interface EmployeeSwap {
id: number;

View File

@@ -1,4 +1,4 @@
import * as XLSX from 'xlsx';
import * as XLSX from "xlsx";
interface AllocationData {
id: number;
@@ -44,16 +44,20 @@ interface WorkReportData {
export const exportWorkReportToXLSX = (
allocations: AllocationData[],
departmentName: string,
_dateRange: { startDate: string; endDate: string }
_dateRange: { startDate: string; endDate: string },
) => {
// Group allocations by work (activity + sub_department) and date
const workDataMap = new Map<string, WorkReportData>();
const allDates = new Set<string>();
allocations.forEach(allocation => {
const workKey = `${allocation.sub_department_name || ''} ${allocation.activity || 'Standard'}`.trim();
const date = allocation.assigned_date ? new Date(allocation.assigned_date).getDate().toString() : '';
allocations.forEach((allocation) => {
const workKey = `${allocation.sub_department_name || ""} ${
allocation.activity || "Standard"
}`.trim();
const date = allocation.assigned_date
? new Date(allocation.assigned_date).getDate().toString()
: "";
if (date) {
allDates.add(date);
}
@@ -68,14 +72,15 @@ export const exportWorkReportToXLSX = (
}
const workData = workDataMap.get(workKey)!;
if (!workData.dates[date]) {
workData.dates[date] = { bag: 0, rate: 0, total: 0 };
}
const bag = parseFloat(String(allocation.units)) || 0;
const rate = parseFloat(String(allocation.rate)) || 0;
const total = parseFloat(String(allocation.total_amount)) || (bag * rate) || rate;
const total = parseFloat(String(allocation.total_amount)) || (bag * rate) ||
rate;
workData.dates[date].bag += bag;
workData.dates[date].rate = rate; // Use latest rate
@@ -85,61 +90,66 @@ export const exportWorkReportToXLSX = (
});
// Sort dates numerically
const sortedDates = Array.from(allDates).sort((a, b) => parseInt(a) - parseInt(b));
const sortedDates = Array.from(allDates).sort((a, b) =>
parseInt(a) - parseInt(b)
);
// Create workbook and worksheet
const wb = XLSX.utils.book_new();
const wsData: (string | number | null)[][] = [];
// Row 1: DATE header with merged cells for each date
const dateHeaderRow: (string | number | null)[] = ['', 'DATE'];
sortedDates.forEach(date => {
dateHeaderRow.push(date, '', ''); // Each date spans 3 columns (Bag, Rate, Total)
const dateHeaderRow: (string | number | null)[] = ["", "DATE"];
sortedDates.forEach((date) => {
dateHeaderRow.push(date, "", ""); // Each date spans 3 columns (Bag, Rate, Total)
});
dateHeaderRow.push('', 'Total', '', '', 'Total-As per Standered', '', '');
dateHeaderRow.push("", "Total", "", "", "Total-As per Standered", "", "");
wsData.push(dateHeaderRow);
// Row 2: WORK and Bag/Rate/Total sub-headers
const subHeaderRow: (string | number | null)[] = ['', 'WORK'];
const subHeaderRow: (string | number | null)[] = ["", "WORK"];
sortedDates.forEach(() => {
subHeaderRow.push('Bag', 'Rate', 'Total');
subHeaderRow.push("Bag", "Rate", "Total");
});
subHeaderRow.push('', 'Bag', 'Rate', 'Total', 'Bag', 'Rate', 'Total');
subHeaderRow.push("", "Bag", "Rate", "Total", "Bag", "Rate", "Total");
wsData.push(subHeaderRow);
// Row 3: Department header (yellow background)
const deptHeaderRow: (string | number | null)[] = ['', `${departmentName.toUpperCase()} Department`];
const deptHeaderRow: (string | number | null)[] = [
"",
`${departmentName.toUpperCase()} Department`,
];
const deptHeaderCols = sortedDates.length * 3 + 7;
for (let col = 0; col < deptHeaderCols; col++) {
deptHeaderRow.push('');
deptHeaderRow.push("");
}
wsData.push(deptHeaderRow);
// Data rows for each work item
const workDataArray = Array.from(workDataMap.values());
workDataArray.forEach((workData, index) => {
const dataRow: (string | number | null)[] = [index + 1, workData.work];
sortedDates.forEach(date => {
sortedDates.forEach((date) => {
const dateData = workData.dates[date] || { bag: 0, rate: 0, total: 0 };
dataRow.push(
dateData.bag || '',
dateData.rate || '',
dateData.total || ''
dateData.bag || "",
dateData.rate || "",
dateData.total || "",
);
});
// Total columns
dataRow.push(''); // Empty column
dataRow.push(workData.totalBag || '');
dataRow.push(''); // Rate for total (could be average)
dataRow.push(workData.totalAmount || '');
dataRow.push(""); // Empty column
dataRow.push(workData.totalBag || "");
dataRow.push(""); // Rate for total (could be average)
dataRow.push(workData.totalAmount || "");
// Standard columns (placeholder - would need standard rates data)
dataRow.push('');
dataRow.push('');
dataRow.push('');
dataRow.push("");
dataRow.push("");
dataRow.push("");
wsData.push(dataRow);
});
@@ -148,33 +158,36 @@ export const exportWorkReportToXLSX = (
wsData.push([]);
// Sub Total row
const subTotalRow: (string | number | null)[] = ['', 'Sub Total'];
const subTotalRow: (string | number | null)[] = ["", "Sub Total"];
// Calculate totals for each date
sortedDates.forEach(date => {
sortedDates.forEach((date) => {
let dateBagTotal = 0;
let dateTotalAmount = 0;
workDataArray.forEach(workData => {
workDataArray.forEach((workData) => {
const dateData = workData.dates[date];
if (dateData) {
dateBagTotal += dateData.bag;
dateTotalAmount += dateData.total;
}
});
subTotalRow.push(dateBagTotal || '', '', dateTotalAmount || '');
subTotalRow.push(dateBagTotal || "", "", dateTotalAmount || "");
});
// Grand totals
const grandTotalBag = workDataArray.reduce((sum, w) => sum + w.totalBag, 0);
const grandTotalAmount = workDataArray.reduce((sum, w) => sum + w.totalAmount, 0);
subTotalRow.push('');
subTotalRow.push(grandTotalBag || '');
subTotalRow.push('');
subTotalRow.push(grandTotalAmount || '');
subTotalRow.push('');
subTotalRow.push('');
subTotalRow.push(grandTotalAmount || ''); // Standard total same as actual for now
const grandTotalAmount = workDataArray.reduce(
(sum, w) => sum + w.totalAmount,
0,
);
subTotalRow.push("");
subTotalRow.push(grandTotalBag || "");
subTotalRow.push("");
subTotalRow.push(grandTotalAmount || "");
subTotalRow.push("");
subTotalRow.push("");
subTotalRow.push(grandTotalAmount || ""); // Standard total same as actual for now
wsData.push(subTotalRow);
@@ -183,37 +196,37 @@ export const exportWorkReportToXLSX = (
// Set column widths
const colWidths: { wch: number }[] = [
{ wch: 4 }, // A - Row number
{ wch: 4 }, // A - Row number
{ wch: 35 }, // B - Work name
];
// Add widths for date columns
sortedDates.forEach(() => {
colWidths.push({ wch: 8 }); // Bag
colWidths.push({ wch: 6 }); // Rate
colWidths.push({ wch: 8 }); // Bag
colWidths.push({ wch: 6 }); // Rate
colWidths.push({ wch: 10 }); // Total
});
// Total columns
colWidths.push({ wch: 3 }); // Empty
colWidths.push({ wch: 3 }); // Empty
colWidths.push({ wch: 10 }); // Total Bag
colWidths.push({ wch: 6 }); // Total Rate
colWidths.push({ wch: 6 }); // Total Rate
colWidths.push({ wch: 12 }); // Total Amount
colWidths.push({ wch: 10 }); // Standard Bag
colWidths.push({ wch: 6 }); // Standard Rate
colWidths.push({ wch: 6 }); // Standard Rate
colWidths.push({ wch: 12 }); // Standard Total
ws['!cols'] = colWidths;
ws["!cols"] = colWidths;
// Merge cells for DATE headers
const merges: XLSX.Range[] = [];
// Merge DATE header cells for each date (row 1)
let colIndex = 2; // Start after row number and WORK columns
sortedDates.forEach(() => {
merges.push({
s: { r: 0, c: colIndex },
e: { r: 0, c: colIndex + 2 }
e: { r: 0, c: colIndex + 2 },
});
colIndex += 3;
});
@@ -221,28 +234,30 @@ export const exportWorkReportToXLSX = (
// Merge Total header
merges.push({
s: { r: 0, c: colIndex + 1 },
e: { r: 0, c: colIndex + 3 }
e: { r: 0, c: colIndex + 3 },
});
// Merge "Total-As per Standered" header
merges.push({
s: { r: 0, c: colIndex + 4 },
e: { r: 0, c: colIndex + 6 }
e: { r: 0, c: colIndex + 6 },
});
// Merge department header row
merges.push({
s: { r: 2, c: 1 },
e: { r: 2, c: colIndex + 6 }
e: { r: 2, c: colIndex + 6 },
});
ws['!merges'] = merges;
ws["!merges"] = merges;
// Add worksheet to workbook
XLSX.utils.book_append_sheet(wb, ws, 'Work Report');
XLSX.utils.book_append_sheet(wb, ws, "Work Report");
// Generate filename
const filename = `work_report_${departmentName.toLowerCase().replace(/\s+/g, '_')}_${new Date().toISOString().split('T')[0]}.xlsx`;
const filename = `work_report_${
departmentName.toLowerCase().replace(/\s+/g, "_")
}_${new Date().toISOString().split("T")[0]}.xlsx`;
// Write and download
XLSX.writeFile(wb, filename);
@@ -253,27 +268,31 @@ export const exportWorkReportToXLSX = (
*/
export const exportAllocationsToXLSX = (
allocations: AllocationData[],
filename?: string
filename?: string,
) => {
if (allocations.length === 0) {
alert('No data to export');
alert("No data to export");
return;
}
// Transform data for export
const exportData = allocations.map((a, index) => ({
'S.No': index + 1,
'Employee Name': a.employee_name || '',
'Contractor': a.contractor_name || '',
'Department': a.department_name || '',
'Sub-Department': a.sub_department_name || '',
'Activity': a.activity || 'Standard',
'Assigned Date': a.assigned_date ? new Date(a.assigned_date).toLocaleDateString() : '',
'Completion Date': a.completion_date ? new Date(a.completion_date).toLocaleDateString() : '',
'Rate': a.rate || 0,
'Units': a.units || '',
'Total Amount': a.total_amount || a.rate || 0,
'Status': a.status || '',
"S.No": index + 1,
"Employee Name": a.employee_name || "",
"Contractor": a.contractor_name || "",
"Department": a.department_name || "",
"Sub-Department": a.sub_department_name || "",
"Activity": a.activity || "Standard",
"Assigned Date": a.assigned_date
? new Date(a.assigned_date).toLocaleDateString()
: "",
"Completion Date": a.completion_date
? new Date(a.completion_date).toLocaleDateString()
: "",
"Rate": a.rate || 0,
"Units": a.units || "",
"Total Amount": a.total_amount || a.rate || 0,
"Status": a.status || "",
}));
// Create workbook
@@ -281,8 +300,8 @@ export const exportAllocationsToXLSX = (
const ws = XLSX.utils.json_to_sheet(exportData);
// Set column widths
ws['!cols'] = [
{ wch: 6 }, // S.No
ws["!cols"] = [
{ wch: 6 }, // S.No
{ wch: 25 }, // Employee Name
{ wch: 20 }, // Contractor
{ wch: 15 }, // Department
@@ -291,15 +310,16 @@ export const exportAllocationsToXLSX = (
{ wch: 12 }, // Assigned Date
{ wch: 14 }, // Completion Date
{ wch: 10 }, // Rate
{ wch: 8 }, // Units
{ wch: 8 }, // Units
{ wch: 12 }, // Total Amount
{ wch: 10 }, // Status
];
XLSX.utils.book_append_sheet(wb, ws, 'Allocations');
XLSX.utils.book_append_sheet(wb, ws, "Allocations");
// Generate filename
const outputFilename = filename || `allocations_${new Date().toISOString().split('T')[0]}.xlsx`;
const outputFilename = filename ||
`allocations_${new Date().toISOString().split("T")[0]}.xlsx`;
// Write and download
XLSX.writeFile(wb, outputFilename);